*: introduce and use FAST_FUNC: regparm on i386, otherwise no-on
[oweals/busybox.git] / libbb / lineedit.c
index 1397409ccb9bba16d514689ecec803311b4becc3..42f372fb944611170cad6038251141fd8abfe4f7 100644 (file)
@@ -65,7 +65,7 @@
 enum {
        /* We use int16_t for positions, need to limit line len */
        MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
-                      ? CONFIG_FEATURE_EDITING_MAX_LEN
+                     ? CONFIG_FEATURE_EDITING_MAX_LEN
                      : 0x7ff0
 };
 
@@ -74,16 +74,15 @@ static const char null_str[] ALIGN1 = "";
 #endif
 
 /* We try to minimize both static and stack usage. */
-struct statics {
+struct lineedit_statics {
        line_input_t *state;
 
        volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
        sighandler_t previous_SIGWINCH_handler;
 
-
-       int cmdedit_x;           /* real x terminal position */
-       int cmdedit_y;           /* pseudoreal y terminal position */
-       int cmdedit_prmt_len;    /* length of prompt (without colors etc) */
+       unsigned cmdedit_x;        /* real x terminal position */
+       unsigned cmdedit_y;        /* pseudoreal y terminal position */
+       unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
 
        unsigned cursor;
        unsigned command_len;
@@ -120,11 +119,10 @@ struct statics {
 #endif
 };
 
-/* Make it reside in writable memory, yet make compiler understand
- * that it is not going to change. */
-static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
+/* See lineedit_ptr_hack.c */
+extern struct lineedit_statics *const lineedit_ptr_to_statics;
 
-#define S (*ptr_to_statics)
+#define S (*lineedit_ptr_to_statics)
 #define state            (S.state           )
 #define cmdedit_termw    (S.cmdedit_termw   )
 #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
@@ -136,7 +134,7 @@ static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
 #define command_ps       (S.command_ps      )
 #define cmdedit_prompt   (S.cmdedit_prompt  )
 #define num_ok_lines     (S.num_ok_lines    )
-#define user_buf         (S.user_buf        ) 
+#define user_buf         (S.user_buf        )
 #define home_pwd_buf     (S.home_pwd_buf    )
 #define matches          (S.matches         )
 #define num_matches      (S.num_matches     )
@@ -145,7 +143,8 @@ static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
 #define delbuf           (S.delbuf          )
 
 #define INIT_S() do { \
-       (*(struct statics**)&ptr_to_statics) = xzalloc(sizeof(S)); \
+       (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
+       barrier(); \
        cmdedit_termw = 80; \
        USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
        USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
@@ -162,14 +161,21 @@ static void deinit_S(void)
        if (home_pwd_buf != null_str)
                free(home_pwd_buf);
 #endif
-       free(ptr_to_statics);
+       free(lineedit_ptr_to_statics);
 }
 #define DEINIT_S() deinit_S()
 
+
 /* Put 'command_ps[cursor]', cursor++.
  * Advance cursor on screen. If we reached right margin, scroll text up
  * and remove terminal margin effect by printing 'next_char' */
+#define HACK_FOR_WRONG_WIDTH 1
+#if HACK_FOR_WRONG_WIDTH
+static void cmdedit_set_out_char(void)
+#define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
+#else
 static void cmdedit_set_out_char(int next_char)
+#endif
 {
        int c = (unsigned char)command_ps[cursor];
 
@@ -196,9 +202,21 @@ static void cmdedit_set_out_char(int next_char)
                /* terminal is scrolled down */
                cmdedit_y++;
                cmdedit_x = 0;
+#if HACK_FOR_WRONG_WIDTH
+               /* This works better if our idea of term width is wrong
+                * and it is actually wider (often happens on serial lines).
+                * Printing CR,LF *forces* cursor to next line.
+                * OTOH if terminal width is correct AND terminal does NOT
+                * have automargin (IOW: it is moving cursor to next line
+                * by itself (which is wrong for VT-10x terminals)),
+                * this will break things: there will be one extra empty line */
+               puts("\r"); /* + implicit '\n' */
+#else
+               /* Works ok only if cmdedit_termw is correct */
                /* destroy "(auto)margin" */
                bb_putchar(next_char);
                bb_putchar('\b');
+#endif
        }
 // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
        cursor++;
@@ -246,7 +264,15 @@ static void input_backward(unsigned num)
        if (cmdedit_x >= num) {
                cmdedit_x -= num;
                if (num <= 4) {
-                       printf("\b\b\b\b" + (4-num));
+                       /* This is longer by 5 bytes on x86.
+                        * Also gets miscompiled for ARM users
+                        * (busybox.net/bugs/view.php?id=2274).
+                        * printf(("\b\b\b\b" + 4) - num);
+                        * return;
+                        */
+                       do {
+                               bb_putchar('\b');
+                       } while (--num);
                        return;
                }
                printf("\033[%uD", num);
@@ -255,9 +281,12 @@ static void input_backward(unsigned num)
 
        /* Need to go one or more lines up */
        num -= cmdedit_x;
-       count_y = 1 + (num / cmdedit_termw);
-       cmdedit_y -= count_y;
-       cmdedit_x = cmdedit_termw * count_y - num;
+       {
+               unsigned w = cmdedit_termw; /* volatile var */
+               count_y = 1 + (num / w);
+               cmdedit_y -= count_y;
+               cmdedit_x = w * count_y - num;
+       }
        /* go to 1st column; go up; go to correct column */
        printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
 }
@@ -265,10 +294,12 @@ static void input_backward(unsigned num)
 static void put_prompt(void)
 {
        out1str(cmdedit_prompt);
-       cmdedit_x = cmdedit_prmt_len;
        cursor = 0;
-// Huh? what if cmdedit_prmt_len >= width?
-       cmdedit_y = 0;                  /* new quasireal y */
+       {
+               unsigned w = cmdedit_termw; /* volatile var */
+               cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
+               cmdedit_x = cmdedit_prmt_len % w;
+       }
 }
 
 /* draw prompt, editor line, and clear tail */
@@ -285,11 +316,16 @@ static void redraw(int y, int back_cursor)
 
 /* Delete the char in front of the cursor, optionally saving it
  * for later putback */
+#if !ENABLE_FEATURE_EDITING_VI
+static void input_delete(void)
+#define input_delete(save) input_delete()
+#else
 static void input_delete(int save)
+#endif
 {
        int j = cursor;
 
-       if (j == command_len)
+       if (j == (int)command_len)
                return;
 
 #if ENABLE_FEATURE_EDITING_VI
@@ -504,8 +540,8 @@ static void exe_n_cwd_tab_completion(char *command, int type)
 
        for (i = 0; i < npaths; i++) {
                dir = opendir(paths[i]);
-               if (!dir)                       /* Don't print an error */
-                       continue;
+               if (!dir)
+                       continue; /* don't print an error */
 
                while ((next = readdir(dir)) != NULL) {
                        int len1;
@@ -515,18 +551,21 @@ static void exe_n_cwd_tab_completion(char *command, int type)
                        if (strncmp(str_found, pfind, strlen(pfind)))
                                continue;
                        /* not see .name without .match */
-                       if (*str_found == '.' && *pfind == 0) {
+                       if (*str_found == '.' && *pfind == '\0') {
                                if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
                                        continue;
                                str_found = ""; /* only "/" */
                        }
                        found = concat_path_file(paths[i], str_found);
-                       /* hmm, remover in progress? */
-                       if (stat(found, &st) < 0)
+                       /* hmm, remove in progress? */
+                       /* NB: stat() first so that we see is it a directory;
+                        * but if that fails, use lstat() so that
+                        * we still match dangling links */
+                       if (stat(found, &st) && lstat(found, &st))
                                goto cont;
                        /* find with dirs? */
                        if (paths[i] != dirbuf)
-                               strcpy(found, next->d_name);    /* only name */
+                               strcpy(found, next->d_name); /* only name */
 
                        len1 = strlen(found);
                        found = xrealloc(found, len1 + 2);
@@ -534,7 +573,7 @@ static void exe_n_cwd_tab_completion(char *command, int type)
                        found[len1+1] = '\0';
 
                        if (S_ISDIR(st.st_mode)) {
-                               /* name is directory      */
+                               /* name is a directory */
                                if (found[len1-1] != '/') {
                                        found[len1] = '/';
                                }
@@ -552,7 +591,7 @@ static void exe_n_cwd_tab_completion(char *command, int type)
                closedir(dir);
        }
        if (paths != path1) {
-               free(paths[0]);                 /* allocated memory only in first member */
+               free(paths[0]); /* allocated memory is only in first member */
                free(paths);
        }
 #undef dirbuf
@@ -787,11 +826,6 @@ static char *add_quote_for_spec_chars(char *found)
        return s;
 }
 
-static int match_compare(const void *a, const void *b)
-{
-       return strcmp(*(char**)a, *(char**)b);
-}
-
 /* Do TAB completion */
 static void input_tab(smallint *lastWasTab)
 {
@@ -800,7 +834,7 @@ static void input_tab(smallint *lastWasTab)
 
        if (!*lastWasTab) {
                char *tmp, *tmp1;
-               int len_found;
+               size_t len_found;
 /*             char matchBuf[MAX_LINELEN]; */
 #define matchBuf (S.input_tab__matchBuf)
                int find_type;
@@ -831,8 +865,9 @@ static void input_tab(smallint *lastWasTab)
                        exe_n_cwd_tab_completion(matchBuf, find_type);
                /* Sort, then remove any duplicates found */
                if (matches) {
-                       int i, n = 0;
-                       qsort(matches, num_matches, sizeof(char*), match_compare);
+                       unsigned i;
+                       int n = 0;
+                       qsort_string_vector(matches, num_matches);
                        for (i = 0; i < num_matches - 1; ++i) {
                                if (matches[i] && matches[i+1]) { /* paranoia */
                                        if (strcmp(matches[i], matches[i+1]) == 0) {
@@ -949,16 +984,18 @@ static void load_history(const char *fromfile)
        FILE *fp;
        int hi;
 
-       /* cleanup old */
-       for (hi = state->cnt_history; hi > 0;) {
-               hi--;
-               free(state->history[hi]);
-       }
+       /* NB: do not trash old history if file can't be opened */
 
        fp = fopen(fromfile, "r");
        if (fp) {
+               /* clean up old history */
+               for (hi = state->cnt_history; hi > 0;) {
+                       hi--;
+                       free(state->history[hi]);
+               }
+
                for (hi = 0; hi < MAX_HISTORY;) {
-                       char *hl = xmalloc_getline(fp);
+                       char *hl = xmalloc_fgetline(fp);
                        int l;
 
                        if (!hl)
@@ -973,8 +1010,8 @@ static void load_history(const char *fromfile)
                        state->history[hi++] = hl;
                }
                fclose(fp);
+               state->cur_history = state->cnt_history = hi;
        }
-       state->cur_history = state->cnt_history = hi;
 }
 
 /* state->flags is already checked to be nonzero */
@@ -1195,11 +1232,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
                                        break;
 #endif
                                case 'h':
-                                       pbuf = free_me = xzalloc(256);
-                                       if (gethostname(pbuf, 255) < 0) {
-                                               pbuf[0] = '?';
-                                               pbuf[1] = '\0';
-                                       }
+                                       pbuf = free_me = safe_gethostname();
                                        *strchrnul(pbuf, '.') = '\0';
                                        break;
                                case '$':
@@ -1289,7 +1322,7 @@ static void cmdedit_setwidth(unsigned w, int redraw_flg)
 
 static void win_changed(int nsig)
 {
-       int width;
+       unsigned width;
        get_terminal_width_height(0, &width, NULL);
        cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
        if (nsig == SIGWINCH)
@@ -1315,16 +1348,16 @@ static void win_changed(int nsig)
 #define CTRL(a) ((a) & ~0x40)
 
 /* Returns:
- * -1 on read errors or EOF, or on bare Ctrl-D.
- * 0  on ctrl-C,
+ * -1 on read errors or EOF, or on bare Ctrl-D,
+ * 0  on ctrl-C (the line entered is still returned in 'command'),
  * >0 length of input string, including terminating '\n'
  */
-int read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
+int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
 {
 #if ENABLE_FEATURE_TAB_COMPLETION
        smallint lastWasTab = FALSE;
 #endif
-       unsigned int ic;
+       unsigned ic;
        unsigned char c;
        smallint break_out = 0;
 #if ENABLE_FEATURE_EDITING_VI
@@ -1343,8 +1376,10 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                int len;
                parse_and_put_prompt(prompt);
                fflush(stdout);
-               fgets(command, maxsize, stdin);
-               len = strlen(command);
+               if (fgets(command, maxsize, stdin) == NULL)
+                       len = -1; /* EOF or error */
+               else
+                       len = strlen(command);
                DEINIT_S();
                return len;
        }
@@ -1398,9 +1433,9 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
        parse_and_put_prompt(prompt);
 
        while (1) {
-               fflush(stdout);
+               fflush(NULL);
 
-               if (safe_read(STDIN_FILENO, &c, 1) < 1) {
+               if (nonblock_safe_read(STDIN_FILENO, &c, 1) < 1) {
                        /* if we can't read input then exit */
                        goto prepare_to_die;
                }
@@ -1421,7 +1456,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        goto_new_line();
                        break_out = 1;
                        break;
-#if ENABLE_FEATURE_EDITING_FANCY_KEYS
                case CTRL('A'):
                vi_case('0'|vbit:)
                        /* Control-a -- Beginning of line */
@@ -1434,7 +1468,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        /* Control-b -- Move back one character */
                        input_backward(1);
                        break;
-#endif
                case CTRL('C'):
                vi_case(CTRL('C')|vbit:)
                        /* Control-c -- stop gathering input */
@@ -1455,7 +1488,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        input_delete(0);
                        break;
 
-#if ENABLE_FEATURE_EDITING_FANCY_KEYS
                case CTRL('E'):
                vi_case('$'|vbit:)
                        /* Control-e -- End of line */
@@ -1467,7 +1499,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        /* Control-f -- Move forward one character */
                        input_forward();
                        break;
-#endif
 
                case '\b':
                case '\x7f': /* DEL */
@@ -1481,7 +1512,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        break;
 #endif
 
-#if ENABLE_FEATURE_EDITING_FANCY_KEYS
                case CTRL('K'):
                        /* Control-k -- clear to end of line */
                        command[cursor] = 0;
@@ -1494,7 +1524,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        printf("\033[H");
                        redraw(0, command_len - cursor);
                        break;
-#endif
 
 #if MAX_HISTORY > 0
                case CTRL('N'):
@@ -1516,7 +1545,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        break;
 #endif
 
-#if ENABLE_FEATURE_EDITING_FANCY_KEYS
                case CTRL('U'):
                vi_case(CTRL('U')|vbit:)
                        /* Control-U -- Clear line before cursor */
@@ -1526,7 +1554,6 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                                redraw(cmdedit_y, command_len);
                        }
                        break;
-#endif
                case CTRL('W'):
                vi_case(CTRL('W')|vbit:)
                        /* Control-W -- Remove the last word */
@@ -1750,8 +1777,8 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                        break;
 
                default:        /* If it's regular input, do the normal thing */
-#if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
-                       /* Control-V -- Add non-printable symbol */
+
+                       /* Control-V -- force insert of next char */
                        if (c == CTRL('V')) {
                                if (safe_read(STDIN_FILENO, &c, 1) < 1)
                                        goto prepare_to_die;
@@ -1759,17 +1786,13 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
                                        beep();
                                        break;
                                }
-                       } else
-#endif
+                       }
 
 #if ENABLE_FEATURE_EDITING_VI
                        if (vi_cmdmode)  /* Don't self-insert */
                                break;
 #endif
-                       if (!Isprint(c)) /* Skip non-printable characters */
-                               break;
-
-                       if (command_len >= (maxsize - 2))        /* Need to leave space for enter */
+                       if ((int)command_len >= (maxsize - 2))        /* Need to leave space for enter */
                                break;
 
                        command_len++;
@@ -1822,7 +1845,7 @@ int read_line_input(const char *prompt, char *command, int maxsize, line_input_t
        return command_len;
 }
 
-line_input_t *new_line_input_t(int flags)
+line_input_t* FAST_FUNC new_line_input_t(int flags)
 {
        line_input_t *n = xzalloc(sizeof(*n));
        n->flags = flags;
@@ -1832,7 +1855,7 @@ line_input_t *new_line_input_t(int flags)
 #else
 
 #undef read_line_input
-int read_line_input(const char* prompt, char* command, int maxsize)
+int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
 {
        fputs(prompt, stdout);
        fflush(stdout);