Fix a use-after-freed error introduced by previous attempt to fix a Coverity scan...
[external/binutils.git] / readline / input.c
1 /* input.c -- character input functions for readline. */
2
3 /* Copyright (C) 1994-2010 Free Software Foundation, Inc.
4
5    This file is part of the GNU Readline Library (Readline), a library
6    for reading lines of text with interactive input and history editing.      
7
8    Readline is free software: you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation, either version 3 of the License, or
11    (at your option) any later version.
12
13    Readline is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Readline.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #define READLINE_LIBRARY
23
24 #if defined (__TANDEM)
25 #  include <floss.h>
26 #endif
27
28 #if defined (HAVE_CONFIG_H)
29 #  include <config.h>
30 #endif
31
32 #include <sys/types.h>
33 #include <fcntl.h>
34 #if defined (HAVE_SYS_FILE_H)
35 #  include <sys/file.h>
36 #endif /* HAVE_SYS_FILE_H */
37
38 #if defined (HAVE_UNISTD_H)
39 #  include <unistd.h>
40 #endif /* HAVE_UNISTD_H */
41
42 #if defined (HAVE_STDLIB_H)
43 #  include <stdlib.h>
44 #else
45 #  include "ansi_stdlib.h"
46 #endif /* HAVE_STDLIB_H */
47
48 #include "posixselect.h"
49
50 #if defined (FIONREAD_IN_SYS_IOCTL)
51 #  include <sys/ioctl.h>
52 #endif
53
54 #include <stdio.h>
55 #include <errno.h>
56
57 #if !defined (errno)
58 extern int errno;
59 #endif /* !errno */
60
61 /* System-specific feature definitions and include files. */
62 #include "rldefs.h"
63 #include "rlmbutil.h"
64
65 /* Some standard library routines. */
66 #include "readline.h"
67
68 #include "rlprivate.h"
69 #include "rlshell.h"
70 #include "xmalloc.h"
71
72 /* What kind of non-blocking I/O do we have? */
73 #if !defined (O_NDELAY) && defined (O_NONBLOCK)
74 #  define O_NDELAY O_NONBLOCK   /* Posix style */
75 #endif
76
77 /* Non-null means it is a pointer to a function to run while waiting for
78    character input. */
79 rl_hook_func_t *rl_event_hook = (rl_hook_func_t *)NULL;
80
81 rl_getc_func_t *rl_getc_function = rl_getc;
82
83 static int _keyboard_input_timeout = 100000;            /* 0.1 seconds; it's in usec */
84
85 static int ibuffer_space PARAMS((void));
86 static int rl_get_char PARAMS((int *));
87 static int rl_gather_tyi PARAMS((void));
88
89 #if defined (_WIN32) && !defined (__CYGWIN__)
90
91 /* 'isatty' in the Windows runtime returns non-zero for every
92    character device, including the null device.  Repair that.  */
93 #include <io.h>
94 #include <conio.h>
95 #define WIN32_LEAN_AND_MEAN 1
96 #include <windows.h>
97
98 int w32_isatty (int fd)
99 {
100   if (_isatty(fd))
101     {
102       HANDLE h = (HANDLE) _get_osfhandle (fd);
103       DWORD ignored;
104
105       if (h == INVALID_HANDLE_VALUE)
106         {
107           errno = EBADF;
108           return 0;
109         }
110       if (GetConsoleMode (h, &ignored) != 0)
111         return 1;
112     }
113   errno = ENOTTY;
114   return 0;
115 }
116
117 #define isatty(x)  w32_isatty(x)
118 #endif
119
120 /* **************************************************************** */
121 /*                                                                  */
122 /*                      Character Input Buffering                   */
123 /*                                                                  */
124 /* **************************************************************** */
125
126 static int pop_index, push_index;
127 static unsigned char ibuffer[512];
128 static int ibuffer_len = sizeof (ibuffer) - 1;
129
130 #define any_typein (push_index != pop_index)
131
132 int
133 _rl_any_typein ()
134 {
135   return any_typein;
136 }
137
138 /* Return the amount of space available in the buffer for stuffing
139    characters. */
140 static int
141 ibuffer_space ()
142 {
143   if (pop_index > push_index)
144     return (pop_index - push_index - 1);
145   else
146     return (ibuffer_len - (push_index - pop_index));
147 }
148
149 /* Get a key from the buffer of characters to be read.
150    Return the key in KEY.
151    Result is KEY if there was a key, or 0 if there wasn't. */
152 static int
153 rl_get_char (key)
154      int *key;
155 {
156   if (push_index == pop_index)
157     return (0);
158
159   *key = ibuffer[pop_index++];
160 #if 0
161   if (pop_index >= ibuffer_len)
162 #else
163   if (pop_index > ibuffer_len)
164 #endif
165     pop_index = 0;
166
167   return (1);
168 }
169
170 /* Stuff KEY into the *front* of the input buffer.
171    Returns non-zero if successful, zero if there is
172    no space left in the buffer. */
173 int
174 _rl_unget_char (key)
175      int key;
176 {
177   if (ibuffer_space ())
178     {
179       pop_index--;
180       if (pop_index < 0)
181         pop_index = ibuffer_len;
182       ibuffer[pop_index] = key;
183       return (1);
184     }
185   return (0);
186 }
187
188 int
189 _rl_pushed_input_available ()
190 {
191   return (push_index != pop_index);
192 }
193
194 /* If a character is available to be read, then read it and stuff it into
195    IBUFFER.  Otherwise, just return.  Returns number of characters read
196    (0 if none available) and -1 on error (EIO). */
197 static int
198 rl_gather_tyi ()
199 {
200   int tty;
201   register int tem, result;
202   int chars_avail, k;
203   char input;
204 #if defined(HAVE_SELECT)
205   fd_set readfds, exceptfds;
206   struct timeval timeout;
207 #endif
208
209   chars_avail = 0;
210   tty = fileno (rl_instream);
211
212 #if defined (HAVE_SELECT)
213   FD_ZERO (&readfds);
214   FD_ZERO (&exceptfds);
215   FD_SET (tty, &readfds);
216   FD_SET (tty, &exceptfds);
217   USEC_TO_TIMEVAL (_keyboard_input_timeout, timeout);
218   result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
219   if (result <= 0)
220     return 0;   /* Nothing to read. */
221 #endif
222
223   result = -1;
224 #if defined (FIONREAD)
225   errno = 0;
226   result = ioctl (tty, FIONREAD, &chars_avail);
227   if (result == -1 && errno == EIO)
228     return -1;
229 #endif
230
231 #if defined (O_NDELAY)
232   if (result == -1)
233     {
234       tem = fcntl (tty, F_GETFL, 0);
235
236       fcntl (tty, F_SETFL, (tem | O_NDELAY));
237       chars_avail = read (tty, &input, 1);
238
239       fcntl (tty, F_SETFL, tem);
240       if (chars_avail == -1 && errno == EAGAIN)
241         return 0;
242       if (chars_avail == 0)     /* EOF */
243         {
244           rl_stuff_char (EOF);
245           return (0);
246         }
247     }
248 #endif /* O_NDELAY */
249
250 #if defined (__MINGW32__)
251   /* Use getch/_kbhit to check for available console input, in the same way
252      that we read it normally. */
253    chars_avail = isatty (tty) ? _kbhit () : 0;
254    result = 0;
255 #endif
256
257   /* If there's nothing available, don't waste time trying to read
258      something. */
259   if (chars_avail <= 0)
260     return 0;
261
262   tem = ibuffer_space ();
263
264   if (chars_avail > tem)
265     chars_avail = tem;
266
267   /* One cannot read all of the available input.  I can only read a single
268      character at a time, or else programs which require input can be
269      thwarted.  If the buffer is larger than one character, I lose.
270      Damn! */
271   if (tem < ibuffer_len)
272     chars_avail = 0;
273
274   if (result != -1)
275     {
276       while (chars_avail--)
277         {
278           RL_CHECK_SIGNALS ();
279           k = (*rl_getc_function) (rl_instream);
280           if (rl_stuff_char (k) == 0)
281             break;                      /* some problem; no more room */
282           if (k == NEWLINE || k == RETURN)
283             break;
284         }
285     }
286   else
287     {
288       if (chars_avail)
289         rl_stuff_char (input);
290     }
291
292   return 1;
293 }
294
295 int
296 rl_set_keyboard_input_timeout (u)
297      int u;
298 {
299   int o;
300
301   o = _keyboard_input_timeout;
302   if (u >= 0)
303     _keyboard_input_timeout = u;
304   return (o);
305 }
306
307 /* Is there input available to be read on the readline input file
308    descriptor?  Only works if the system has select(2) or FIONREAD.
309    Uses the value of _keyboard_input_timeout as the timeout; if another
310    readline function wants to specify a timeout and not leave it up to
311    the user, it should use _rl_input_queued(timeout_value_in_microseconds)
312    instead. */
313 int
314 _rl_input_available ()
315 {
316 #if defined(HAVE_SELECT)
317   fd_set readfds, exceptfds;
318   struct timeval timeout;
319 #endif
320 #if !defined (HAVE_SELECT) && defined(FIONREAD)
321   int chars_avail;
322 #endif
323   int tty;
324
325   tty = fileno (rl_instream);
326
327 #if defined (HAVE_SELECT)
328   FD_ZERO (&readfds);
329   FD_ZERO (&exceptfds);
330   FD_SET (tty, &readfds);
331   FD_SET (tty, &exceptfds);
332   timeout.tv_sec = 0;
333   timeout.tv_usec = _keyboard_input_timeout;
334   return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
335 #else
336
337 #if defined (FIONREAD)
338   if (ioctl (tty, FIONREAD, &chars_avail) == 0)
339     return (chars_avail);
340 #endif
341
342 #endif
343
344 #if defined (__MINGW32__)
345   if (isatty (tty))
346     return (_kbhit ());
347 #endif
348
349   return 0;
350 }
351
352 int
353 _rl_input_queued (t)
354      int t;
355 {
356   int old_timeout, r;
357
358   old_timeout = rl_set_keyboard_input_timeout (t);
359   r = _rl_input_available ();
360   rl_set_keyboard_input_timeout (old_timeout);
361   return r;
362 }
363
364 void
365 _rl_insert_typein (c)
366      int c;     
367 {       
368   int key, t, i;
369   char *string;
370
371   i = key = 0;
372   string = (char *)xmalloc (ibuffer_len + 1);
373   string[i++] = (char) c;
374
375   while ((t = rl_get_char (&key)) &&
376          _rl_keymap[key].type == ISFUNC &&
377          _rl_keymap[key].function == rl_insert)
378     string[i++] = key;
379
380   if (t)
381     _rl_unget_char (key);
382
383   string[i] = '\0';
384   rl_insert_text (string);
385   xfree (string);
386 }
387
388 /* Add KEY to the buffer of characters to be read.  Returns 1 if the
389    character was stuffed correctly; 0 otherwise. */
390 int
391 rl_stuff_char (key)
392      int key;
393 {
394   if (ibuffer_space () == 0)
395     return 0;
396
397   if (key == EOF)
398     {
399       key = NEWLINE;
400       rl_pending_input = EOF;
401       RL_SETSTATE (RL_STATE_INPUTPENDING);
402     }
403   ibuffer[push_index++] = key;
404 #if 0
405   if (push_index >= ibuffer_len)
406 #else
407   if (push_index > ibuffer_len)
408 #endif
409     push_index = 0;
410
411   return 1;
412 }
413
414 /* Make C be the next command to be executed. */
415 int
416 rl_execute_next (c)
417      int c;
418 {
419   rl_pending_input = c;
420   RL_SETSTATE (RL_STATE_INPUTPENDING);
421   return 0;
422 }
423
424 /* Clear any pending input pushed with rl_execute_next() */
425 int
426 rl_clear_pending_input ()
427 {
428   rl_pending_input = 0;
429   RL_UNSETSTATE (RL_STATE_INPUTPENDING);
430   return 0;
431 }
432
433 /* **************************************************************** */
434 /*                                                                  */
435 /*                           Character Input                        */
436 /*                                                                  */
437 /* **************************************************************** */
438
439 /* Read a key, including pending input. */
440 int
441 rl_read_key ()
442 {
443   int c;
444
445   rl_key_sequence_length++;
446
447   if (rl_pending_input)
448     {
449       c = rl_pending_input;
450       rl_clear_pending_input ();
451     }
452   else
453     {
454       /* If input is coming from a macro, then use that. */
455       if (c = _rl_next_macro_key ())
456         return (c);
457
458       /* If the user has an event function, then call it periodically. */
459       if (rl_event_hook)
460         {
461           while (rl_event_hook)
462             {
463               if (rl_gather_tyi () < 0) /* XXX - EIO */
464                 {
465                   rl_done = 1;
466                   return ('\n');
467                 }
468               RL_CHECK_SIGNALS ();
469               if (rl_get_char (&c) != 0)
470                 break;
471               if (rl_done)              /* XXX - experimental */
472                 return ('\n');
473               (*rl_event_hook) ();
474             }
475         }
476       else
477         {
478           if (rl_get_char (&c) == 0)
479             c = (*rl_getc_function) (rl_instream);
480           RL_CHECK_SIGNALS ();
481         }
482     }
483
484   return (c);
485 }
486
487 int
488 rl_getc (stream)
489      FILE *stream;
490 {
491   int result;
492   unsigned char c;
493
494   while (1)
495     {
496       RL_CHECK_SIGNALS ();
497
498 #if defined (__MINGW32__)
499       /* Use _getch to make sure we call the function from MS runtime,
500          even if some curses library is linked in.  */
501       if (isatty (fileno (stream)))
502         return (_getch ());
503 #endif
504       result = read (fileno (stream), &c, sizeof (unsigned char));
505
506       if (result == sizeof (unsigned char))
507         return (c);
508
509       /* If zero characters are returned, then the file that we are
510          reading from is empty!  Return EOF in that case. */
511       if (result == 0)
512         return (EOF);
513
514 #if defined (__BEOS__)
515       if (errno == EINTR)
516         continue;
517 #endif
518
519 #if defined (EWOULDBLOCK)
520 #  define X_EWOULDBLOCK EWOULDBLOCK
521 #else
522 #  define X_EWOULDBLOCK -99
523 #endif
524
525 #if defined (EAGAIN)
526 #  define X_EAGAIN EAGAIN
527 #else
528 #  define X_EAGAIN -99
529 #endif
530
531       if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
532         {
533           if (sh_unset_nodelay_mode (fileno (stream)) < 0)
534             return (EOF);
535           continue;
536         }
537
538 #undef X_EWOULDBLOCK
539 #undef X_EAGAIN
540
541       /* If the error that we received was SIGINT, then try again,
542          this is simply an interrupted system call to read ().
543          Otherwise, some error ocurred, also signifying EOF. */
544       if (errno != EINTR)
545         return (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF);
546     }
547 }
548
549 #if defined (HANDLE_MULTIBYTE)
550 /* read multibyte char */
551 int
552 _rl_read_mbchar (mbchar, size)
553      char *mbchar;
554      int size;
555 {
556   int mb_len, c;
557   size_t mbchar_bytes_length;
558   wchar_t wc;
559   mbstate_t ps, ps_back;
560
561   memset(&ps, 0, sizeof (mbstate_t));
562   memset(&ps_back, 0, sizeof (mbstate_t));
563
564   mb_len = 0;  
565   while (mb_len < size)
566     {
567       RL_SETSTATE(RL_STATE_MOREINPUT);
568       c = rl_read_key ();
569       RL_UNSETSTATE(RL_STATE_MOREINPUT);
570
571       if (c < 0)
572         break;
573
574       mbchar[mb_len++] = c;
575
576       mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
577       if (mbchar_bytes_length == (size_t)(-1))
578         break;          /* invalid byte sequence for the current locale */
579       else if (mbchar_bytes_length == (size_t)(-2))
580         {
581           /* shorted bytes */
582           ps = ps_back;
583           continue;
584         } 
585       else if (mbchar_bytes_length == 0)
586         {
587           mbchar[0] = '\0';     /* null wide character */
588           mb_len = 1;
589           break;
590         }
591       else if (mbchar_bytes_length > (size_t)(0))
592         break;
593     }
594
595   return mb_len;
596 }
597
598 /* Read a multibyte-character string whose first character is FIRST into
599    the buffer MB of length MLEN.  Returns the last character read, which
600    may be FIRST.  Used by the search functions, among others.  Very similar
601    to _rl_read_mbchar. */
602 int
603 _rl_read_mbstring (first, mb, mlen)
604      int first;
605      char *mb;
606      int mlen;
607 {
608   int i, c;
609   mbstate_t ps;
610
611   c = first;
612   memset (mb, 0, mlen);
613   for (i = 0; c >= 0 && i < mlen; i++)
614     {
615       mb[i] = (char)c;
616       memset (&ps, 0, sizeof (mbstate_t));
617       if (_rl_get_char_len (mb, &ps) == -2)
618         {
619           /* Read more for multibyte character */
620           RL_SETSTATE (RL_STATE_MOREINPUT);
621           c = rl_read_key ();
622           RL_UNSETSTATE (RL_STATE_MOREINPUT);
623         }
624       else
625         break;
626     }
627   return c;
628 }
629 #endif /* HANDLE_MULTIBYTE */