|
103 | 103 |
|
104 | 104 | #define MEM_LIMIT_NORMAL (128*1024*1024) /* 128 MB */ |
105 | 105 | #define MEM_LIMIT_HIGH (2047*1024*1024) /* ~2 GB */ |
106 | | -#define LINEBUF_SIZE 65536 |
107 | 106 |
|
108 | 107 | static int main_argc = 0; |
109 | 108 | static char **main_argv = NULL; |
@@ -545,6 +544,9 @@ static int handle_fh(duk_context *ctx, FILE *f, const char *filename, const char |
545 | 544 | fprintf(stderr, "resizing read buffer: %ld -> %ld\n", (long) bufsz, (long) (bufsz * 2)); |
546 | 545 | #endif |
547 | 546 | newsz = bufsz + (bufsz >> 2) + 1024; /* +25% and some extra */ |
| 547 | + if (newsz < bufsz) { |
| 548 | + goto error; |
| 549 | + } |
548 | 550 | buf_new = (char *) realloc(buf, newsz); |
549 | 551 | if (!buf_new) { |
550 | 552 | goto error; |
@@ -789,37 +791,42 @@ static int handle_interactive(duk_context *ctx) { |
789 | 791 | #else /* DUK_CMDLINE_LINENOISE */ |
790 | 792 | static int handle_interactive(duk_context *ctx) { |
791 | 793 | const char *prompt = "duk> "; |
| 794 | + size_t bufsize = 0; |
792 | 795 | char *buffer = NULL; |
793 | 796 | int retval = 0; |
794 | 797 | int rc; |
795 | 798 | int got_eof = 0; |
796 | 799 |
|
797 | | - buffer = (char *) malloc(LINEBUF_SIZE); |
798 | | - if (!buffer) { |
799 | | - fprintf(stderr, "failed to allocated a line buffer\n"); |
800 | | - fflush(stderr); |
801 | | - retval = -1; |
802 | | - goto done; |
803 | | - } |
804 | | - |
805 | 800 | while (!got_eof) { |
806 | 801 | size_t idx = 0; |
807 | 802 |
|
808 | 803 | fwrite(prompt, 1, strlen(prompt), stdout); |
809 | 804 | fflush(stdout); |
810 | 805 |
|
811 | 806 | for (;;) { |
812 | | - int c = fgetc(stdin); |
| 807 | + int c; |
| 808 | + |
| 809 | + if (idx >= bufsize) { |
| 810 | + size_t newsize = bufsize + (bufsize >> 2) + 1024; /* +25% and some extra */ |
| 811 | + char *newptr; |
| 812 | + |
| 813 | + if (newsize < bufsize) { |
| 814 | + goto fail_realloc; |
| 815 | + } |
| 816 | + newptr = (char *) realloc(buffer, newsize); |
| 817 | + if (!newptr) { |
| 818 | + goto fail_realloc; |
| 819 | + } |
| 820 | + buffer = newptr; |
| 821 | + bufsize = newsize; |
| 822 | + } |
| 823 | + |
| 824 | + c = fgetc(stdin); |
813 | 825 | if (c == EOF) { |
814 | 826 | got_eof = 1; |
815 | 827 | break; |
816 | 828 | } else if (c == '\n') { |
817 | 829 | break; |
818 | | - } else if (idx >= LINEBUF_SIZE) { |
819 | | - fprintf(stderr, "line too long\n"); |
820 | | - fflush(stderr); |
821 | | - retval = -1; |
822 | | - goto done; |
823 | 830 | } else { |
824 | 831 | buffer[idx++] = (char) c; |
825 | 832 | } |
@@ -853,6 +860,12 @@ static int handle_interactive(duk_context *ctx) { |
853 | 860 | } |
854 | 861 |
|
855 | 862 | return retval; |
| 863 | + |
| 864 | + fail_realloc: |
| 865 | + fprintf(stderr, "failed to extend line buffer\n"); |
| 866 | + fflush(stderr); |
| 867 | + retval = -1; |
| 868 | + goto done; |
856 | 869 | } |
857 | 870 | #endif /* DUK_CMDLINE_LINENOISE */ |
858 | 871 |
|
|
0 commit comments