1This file is read.def, from which is created read.c.
2It implements the builtin "read" in Bash.
3
4Copyright (C) 1987-2020 Free Software Foundation, Inc.
5
6This file is part of GNU Bash, the Bourne Again SHell.
7
8Bash is free software: you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
12
13Bash is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with Bash.  If not, see <http://www.gnu.org/licenses/>.
20
21$PRODUCES read.c
22
23$BUILTIN read
24$FUNCTION read_builtin
25$SHORT_DOC read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
26Read a line from the standard input and split it into fields.
27
28Reads a single line from the standard input, or from file descriptor FD
29if the -u option is supplied.  The line is split into fields as with word
30splitting, and the first word is assigned to the first NAME, the second
31word to the second NAME, and so on, with any leftover words assigned to
32the last NAME.  Only the characters found in $IFS are recognized as word
33delimiters.
34
35If no NAMEs are supplied, the line read is stored in the REPLY variable.
36
37Options:
38  -a array	assign the words read to sequential indices of the array
39		variable ARRAY, starting at zero
40  -d delim	continue until the first character of DELIM is read, rather
41		than newline
42  -e	use Readline to obtain the line
43  -i text	use TEXT as the initial text for Readline
44  -n nchars	return after reading NCHARS characters rather than waiting
45		for a newline, but honor a delimiter if fewer than
46		NCHARS characters are read before the delimiter
47  -N nchars	return only after reading exactly NCHARS characters, unless
48		EOF is encountered or read times out, ignoring any
49		delimiter
50  -p prompt	output the string PROMPT without a trailing newline before
51		attempting to read
52  -r	do not allow backslashes to escape any characters
53  -s	do not echo input coming from a terminal
54  -t timeout	time out and return failure if a complete line of
55		input is not read within TIMEOUT seconds.  The value of the
56		TMOUT variable is the default timeout.  TIMEOUT may be a
57		fractional number.  If TIMEOUT is 0, read returns
58		immediately, without trying to read any data, returning
59		success only if input is available on the specified
60		file descriptor.  The exit status is greater than 128
61		if the timeout is exceeded
62  -u fd	read from file descriptor FD instead of the standard input
63
64Exit Status:
65The return code is zero, unless end-of-file is encountered, read times out
66(in which case it's greater than 128), a variable assignment error occurs,
67or an invalid file descriptor is supplied as the argument to -u.
68$END
69
70#include <config.h>
71
72#include "bashtypes.h"
73#include "posixstat.h"
74
75#include <stdio.h>
76
77#include "bashansi.h"
78
79#if defined (HAVE_UNISTD_H)
80#  include <unistd.h>
81#endif
82
83#include <signal.h>
84#include <errno.h>
85
86#ifdef __CYGWIN__
87#  include <fcntl.h>
88#  include <io.h>
89#endif
90
91#include "../bashintl.h"
92
93#include "../shell.h"
94#include "common.h"
95#include "bashgetopt.h"
96#include "trap.h"
97
98#include <shtty.h>
99
100#if defined (READLINE)
101#include "../bashline.h"
102#include <readline/readline.h>
103#endif
104
105#if defined (BUFFERED_INPUT)
106#  include "input.h"
107#endif
108
109#include "shmbutil.h"
110
111#if !defined(errno)
112extern int errno;
113#endif
114
115struct ttsave
116{
117  int fd;
118  TTYSTRUCT attrs;
119};
120
121#if defined (READLINE)
122static void reset_attempted_completion_function PARAMS((char *));
123static int set_itext PARAMS((void));
124static char *edit_line PARAMS((char *, char *));
125static void set_eol_delim PARAMS((int));
126static void reset_eol_delim PARAMS((char *));
127#endif
128static SHELL_VAR *bind_read_variable PARAMS((char *, char *));
129#if defined (HANDLE_MULTIBYTE)
130static int read_mbchar PARAMS((int, char *, int, int, int));
131#endif
132static void ttyrestore PARAMS((struct ttsave *));
133
134static sighandler sigalrm PARAMS((int));
135static void reset_alarm PARAMS((void));
136
137/* Try this to see what the rest of the shell can do with the information. */
138procenv_t alrmbuf;
139int sigalrm_seen;
140
141static int reading, tty_modified;
142static SigHandler *old_alrm;
143static unsigned char delim;
144
145static struct ttsave termsave;
146
147/* In all cases, SIGALRM just sets a flag that we check periodically.  This
148   avoids problems with the semi-tricky stuff we do with the xfree of
149   input_string at the top of the unwind-protect list (see below). */
150
151/* Set a flag that CHECK_ALRM can check.  This relies on zread or read_builtin
152   calling trap.c:check_signals(), which knows about sigalrm_seen and alrmbuf. */
153static sighandler
154sigalrm (s)
155     int s;
156{
157  sigalrm_seen = 1;
158}
159
160static void
161reset_alarm ()
162{
163  /* Cancel alarm before restoring signal handler. */
164  falarm (0, 0);
165  set_signal_handler (SIGALRM, old_alrm);
166}
167
168/* Read the value of the shell variables whose names follow.
169   The reading is done from the current input stream, whatever
170   that may be.  Successive words of the input line are assigned
171   to the variables mentioned in LIST.  The last variable in LIST
172   gets the remainder of the words on the line.  If no variables
173   are mentioned in LIST, then the default variable is $REPLY. */
174int
175read_builtin (list)
176     WORD_LIST *list;
177{
178  register char *varname;
179  int size, nr, pass_next, saw_escape, eof, opt, retval, code, print_ps2, nflag;
180  volatile int i;
181  int input_is_tty, input_is_pipe, unbuffered_read, skip_ctlesc, skip_ctlnul;
182  int raw, edit, nchars, silent, have_timeout, ignore_delim, fd;
183  int lastsig, t_errno;
184  int mb_cur_max;
185  unsigned int tmsec, tmusec;
186  long ival, uval;
187  intmax_t intval;
188  char c;
189  char *input_string, *orig_input_string, *ifs_chars, *prompt, *arrayname;
190  char *e, *t, *t1, *ps2, *tofree;
191  struct stat tsb;
192  SHELL_VAR *var;
193  TTYSTRUCT ttattrs, ttset;
194#if defined (ARRAY_VARS)
195  WORD_LIST *alist;
196  int vflags;
197#endif
198#if defined (READLINE)
199  char *rlbuf, *itext;
200  int rlind;
201  FILE *save_instream;
202#endif
203
204  USE_VAR(size);
205  USE_VAR(i);
206  USE_VAR(pass_next);
207  USE_VAR(print_ps2);
208  USE_VAR(saw_escape);
209  USE_VAR(input_is_pipe);
210/*  USE_VAR(raw); */
211  USE_VAR(edit);
212  USE_VAR(tmsec);
213  USE_VAR(tmusec);
214  USE_VAR(nchars);
215  USE_VAR(silent);
216  USE_VAR(ifs_chars);
217  USE_VAR(prompt);
218  USE_VAR(arrayname);
219#if defined (READLINE)
220  USE_VAR(rlbuf);
221  USE_VAR(rlind);
222  USE_VAR(itext);
223#endif
224  USE_VAR(list);
225  USE_VAR(ps2);
226  USE_VAR(lastsig);
227
228  sigalrm_seen = reading = tty_modified = 0;
229
230  i = 0;		/* Index into the string that we are reading. */
231  raw = edit = 0;	/* Not reading raw input by default. */
232  silent = 0;
233  arrayname = prompt = (char *)NULL;
234  fd = 0;		/* file descriptor to read from */
235
236#if defined (READLINE)
237  rlbuf = itext = (char *)0;
238  rlind = 0;
239#endif
240
241  mb_cur_max = MB_CUR_MAX;
242  tmsec = tmusec = 0;		/* no timeout */
243  nr = nchars = input_is_tty = input_is_pipe = unbuffered_read = have_timeout = 0;
244  delim = '\n';		/* read until newline */
245  ignore_delim = nflag = 0;
246
247  reset_internal_getopt ();
248  while ((opt = internal_getopt (list, "ersa:d:i:n:p:t:u:N:")) != -1)
249    {
250      switch (opt)
251	{
252	case 'r':
253	  raw = 1;
254	  break;
255	case 'p':
256	  prompt = list_optarg;
257	  break;
258	case 's':
259	  silent = 1;
260	  break;
261	case 'e':
262#if defined (READLINE)
263	  edit = 1;
264#endif
265	  break;
266	case 'i':
267#if defined (READLINE)
268	  itext = list_optarg;
269#endif
270	  break;
271#if defined (ARRAY_VARS)
272	case 'a':
273	  arrayname = list_optarg;
274	  break;
275#endif
276	case 't':
277	  code = uconvert (list_optarg, &ival, &uval, (char **)NULL);
278	  if (code == 0 || ival < 0 || uval < 0)
279	    {
280	      builtin_error (_("%s: invalid timeout specification"), list_optarg);
281	      return (EXECUTION_FAILURE);
282	    }
283	  else
284	    {
285	      have_timeout = 1;
286	      tmsec = ival;
287	      tmusec = uval;
288	    }
289	  break;
290	case 'N':
291	  ignore_delim = 1;
292	  delim = -1;
293	case 'n':
294	  nflag = 1;
295	  code = legal_number (list_optarg, &intval);
296	  if (code == 0 || intval < 0 || intval != (int)intval)
297	    {
298	      sh_invalidnum (list_optarg);
299	      return (EXECUTION_FAILURE);
300	    }
301	  else
302	    nchars = intval;
303	  break;
304	case 'u':
305	  code = legal_number (list_optarg, &intval);
306	  if (code == 0 || intval < 0 || intval != (int)intval)
307	    {
308	      builtin_error (_("%s: invalid file descriptor specification"), list_optarg);
309	      return (EXECUTION_FAILURE);
310	    }
311	  else
312	    fd = intval;
313	  if (sh_validfd (fd) == 0)
314	    {
315	      builtin_error (_("%d: invalid file descriptor: %s"), fd, strerror (errno));
316	      return (EXECUTION_FAILURE);
317	    }
318	  break;
319	case 'd':
320	  delim = *list_optarg;
321	  break;
322	CASE_HELPOPT;
323	default:
324	  builtin_usage ();
325	  return (EX_USAGE);
326	}
327    }
328  list = loptend;
329
330  /* `read -t 0 var' tests whether input is available with select/FIONREAD,
331     and fails if those are unavailable */
332  if (have_timeout && tmsec == 0 && tmusec == 0)
333#if 0
334    return (EXECUTION_FAILURE);
335#else
336    return (input_avail (fd) ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
337#endif
338
339  /* Convenience: check early whether or not the first of possibly several
340     variable names is a valid identifier, and bail early if so. */
341#if defined (ARRAY_VARS)
342  vflags = assoc_expand_once ? (VA_NOEXPAND|VA_ONEWORD) : 0;
343  if (list && legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word, vflags) == 0)
344#else
345  if (list && legal_identifier (list->word->word) == 0)
346#endif
347    {
348      sh_invalidid (list->word->word);
349      return (EXECUTION_FAILURE);
350    }
351
352  /* If we're asked to ignore the delimiter, make sure we do. */
353  if (ignore_delim)
354    delim = -1;
355
356  /* IF IFS is unset, we use the default of " \t\n". */
357  ifs_chars = getifs ();
358  if (ifs_chars == 0)		/* XXX - shouldn't happen */
359    ifs_chars = "";
360  /* If we want to read exactly NCHARS chars, don't split on IFS */
361  if (ignore_delim)
362    ifs_chars = "";
363  for (skip_ctlesc = skip_ctlnul = 0, e = ifs_chars; *e; e++)
364    skip_ctlesc |= *e == CTLESC, skip_ctlnul |= *e == CTLNUL;
365
366  input_string = (char *)xmalloc (size = 112);	/* XXX was 128 */
367  input_string[0] = '\0';
368
369  /* More input and options validation */
370  if (nflag == 1 && nchars == 0)
371    {
372      retval = read (fd, &c, 0);
373      retval = (retval >= 0) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
374      goto assign_vars;		/* bail early if asked to read 0 chars */
375    }
376
377  /* $TMOUT, if set, is the default timeout for read. */
378  if (have_timeout == 0 && (e = get_string_value ("TMOUT")))
379    {
380      code = uconvert (e, &ival, &uval, (char **)NULL);
381      if (code == 0 || ival < 0 || uval < 0)
382	tmsec = tmusec = 0;
383      else
384	{
385	  tmsec = ival;
386	  tmusec = uval;
387	}
388    }
389
390  begin_unwind_frame ("read_builtin");
391
392#if defined (BUFFERED_INPUT)
393  if (interactive == 0 && default_buffered_input >= 0 && fd_is_bash_input (fd))
394    sync_buffered_stream (default_buffered_input);
395#endif
396
397#if 1
398  input_is_tty = isatty (fd);
399#else
400  input_is_tty = 1;
401#endif
402  if (input_is_tty == 0)
403#ifndef __CYGWIN__
404    input_is_pipe = (lseek (fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
405#else
406    input_is_pipe = 1;
407#endif
408
409  /* If the -p, -e or -s flags were given, but input is not coming from the
410     terminal, turn them off. */
411  if ((prompt || edit || silent) && input_is_tty == 0)
412    {
413      prompt = (char *)NULL;
414#if defined (READLINE)
415      itext = (char *)NULL;
416#endif
417      edit = silent = 0;
418    }
419
420#if defined (READLINE)
421  if (edit)
422    add_unwind_protect (xfree, rlbuf);
423#endif
424
425  pass_next = 0;	/* Non-zero signifies last char was backslash. */
426  saw_escape = 0;	/* Non-zero signifies that we saw an escape char */
427
428  if (tmsec > 0 || tmusec > 0)
429    {
430      /* Turn off the timeout if stdin is a regular file (e.g. from
431	 input redirection). */
432      if ((fstat (fd, &tsb) < 0) || S_ISREG (tsb.st_mode))
433	tmsec = tmusec = 0;
434    }
435
436  if (tmsec > 0 || tmusec > 0)
437    {
438      code = setjmp_nosigs (alrmbuf);
439      if (code)
440	{
441	  sigalrm_seen = 0;
442	  /* Tricky.  The top of the unwind-protect stack is the free of
443	     input_string.  We want to run all the rest and use input_string,
444	     so we have to save input_string temporarily, run the unwind-
445	     protects, then restore input_string so we can use it later */
446	  orig_input_string = 0;
447	  input_string[i] = '\0';	/* make sure it's terminated */
448	  if (i == 0)
449	    {
450	      t = (char *)xmalloc (1);
451	      t[0] = 0;
452	    }
453	  else
454	    t = savestring (input_string);
455
456	  run_unwind_frame ("read_builtin");
457	  input_string = t;
458	  retval = 128+SIGALRM;
459	  goto assign_vars;
460	}
461      if (interactive_shell == 0)
462	initialize_terminating_signals ();
463      old_alrm = set_signal_handler (SIGALRM, sigalrm);
464      add_unwind_protect (reset_alarm, (char *)NULL);
465#if defined (READLINE)
466      if (edit)
467	{
468	  add_unwind_protect (reset_attempted_completion_function, (char *)NULL);
469	  add_unwind_protect (bashline_reset_event_hook, (char *)NULL);
470	}
471#endif
472      falarm (tmsec, tmusec);
473    }
474
475  /* If we've been asked to read only NCHARS chars, or we're using some
476     character other than newline to terminate the line, do the right
477     thing to readline or the tty. */
478  if (nchars > 0 || delim != '\n')
479    {
480#if defined (READLINE)
481      if (edit)
482	{
483	  if (nchars > 0)
484	    {
485	      unwind_protect_int (rl_num_chars_to_read);
486	      rl_num_chars_to_read = nchars;
487	    }
488	  if (delim != '\n')
489	    {
490	      set_eol_delim (delim);
491	      add_unwind_protect (reset_eol_delim, (char *)NULL);
492	    }
493	}
494      else
495#endif
496      if (input_is_tty)
497	{
498	  /* ttsave() */
499	  termsave.fd = fd;
500	  ttgetattr (fd, &ttattrs);
501	  termsave.attrs = ttattrs;
502
503	  ttset = ttattrs;
504	  i = silent ? ttfd_cbreak (fd, &ttset) : ttfd_onechar (fd, &ttset);
505	  if (i < 0)
506	    sh_ttyerror (1);
507	  tty_modified = 1;
508	  add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
509	  if (interactive_shell == 0)
510	    initialize_terminating_signals ();
511	}
512    }
513  else if (silent)	/* turn off echo but leave term in canonical mode */
514    {
515      /* ttsave (); */
516      termsave.fd = fd;
517      ttgetattr (fd, &ttattrs);
518      termsave.attrs = ttattrs;
519
520      ttset = ttattrs;
521      i = ttfd_noecho (fd, &ttset);			/* ttnoecho (); */
522      if (i < 0)
523	sh_ttyerror (1);
524
525      tty_modified = 1;
526      add_unwind_protect ((Function *)ttyrestore, (char *)&termsave);
527      if (interactive_shell == 0)
528	initialize_terminating_signals ();
529    }
530
531#if defined (READLINE)
532  save_instream = 0;
533  if (edit && fd != 0)
534    {
535      if (bash_readline_initialized == 0)
536	initialize_readline ();
537
538      unwind_protect_var (rl_instream);
539      save_instream = rl_instream;
540      rl_instream = fdopen (fd, "r");
541    }
542#endif
543
544  /* This *must* be the top unwind-protect on the stack, so the manipulation
545     of the unwind-protect stack after the realloc() works right. */
546  add_unwind_protect (xfree, input_string);
547
548  CHECK_ALRM;
549  if ((nchars > 0) && (input_is_tty == 0) && ignore_delim)	/* read -N */
550    unbuffered_read = 2;
551  else if ((nchars > 0) || (delim != '\n') || input_is_pipe)
552    unbuffered_read = 1;
553
554  if (prompt && edit == 0)
555    {
556      fprintf (stderr, "%s", prompt);
557      fflush (stderr);
558    }
559
560#if defined (__CYGWIN__) && defined (O_TEXT)
561  setmode (0, O_TEXT);
562#endif
563
564  ps2 = 0;
565  for (print_ps2 = eof = retval = 0;;)
566    {
567      CHECK_ALRM;
568
569#if defined (READLINE)
570      if (edit)
571	{
572	  /* If we have a null delimiter, don't treat NULL as ending the line */
573	  if (rlbuf && rlbuf[rlind] == '\0' && delim != '\0')
574	    {
575	      free (rlbuf);
576	      rlbuf = (char *)0;
577	    }
578	  if (rlbuf == 0)
579	    {
580	      reading = 1;
581	      rlbuf = edit_line (prompt ? prompt : "", itext);
582	      reading = 0;
583	      rlind = 0;
584	    }
585	  if (rlbuf == 0)
586	    {
587	      eof = 1;
588	      break;
589	    }
590	  c = rlbuf[rlind++];
591	}
592      else
593	{
594#endif
595
596      if (print_ps2)
597	{
598	  if (ps2 == 0)
599	    ps2 = get_string_value ("PS2");
600	  fprintf (stderr, "%s", ps2 ? ps2 : "");
601	  fflush (stderr);
602	  print_ps2 = 0;
603	}
604
605      reading = 1;
606      CHECK_ALRM;
607      errno = 0;
608      if (unbuffered_read == 2)
609	retval = posixly_correct ? zreadintr (fd, &c, 1) : zreadn (fd, &c, nchars - nr);
610      else if (unbuffered_read)
611	retval = posixly_correct ? zreadintr (fd, &c, 1) : zread (fd, &c, 1);
612      else
613	retval = posixly_correct ? zreadcintr (fd, &c) : zreadc (fd, &c);
614      reading = 0;
615
616      if (retval <= 0)
617	{
618	  int t;
619
620	  t = errno;
621	  if (retval < 0 && errno == EINTR)
622	    {
623	      check_signals ();		/* in case we didn't call zread via zreadc */
624	      lastsig = LASTSIG();
625	      if (lastsig == 0)
626		lastsig = trapped_signal_received;
627#if 0
628	      run_pending_traps ();	/* because interrupt_immediately is not set */
629#endif
630	    }
631	  else
632	    lastsig = 0;
633	  if (terminating_signal && tty_modified)
634	    ttyrestore (&termsave);	/* fix terminal before exiting */
635	  CHECK_TERMSIG;
636	  eof = 1;
637	  errno = t;	/* preserve it for the error message below */
638	  break;
639	}
640
641      QUIT;		/* in case we didn't call check_signals() */
642#if defined (READLINE)
643	}
644#endif
645
646      if (retval <= 0)			/* XXX shouldn't happen */
647	CHECK_ALRM;
648
649      /* XXX -- use i + mb_cur_max (at least 4) for multibyte/read_mbchar */
650      if (i + (mb_cur_max > 4 ? mb_cur_max : 4) >= size)
651	{
652	  char *t;
653	  t = (char *)xrealloc (input_string, size += 128);
654
655	  /* Only need to change unwind-protect if input_string changes */
656	  if (t != input_string)
657	    {
658	      input_string = t;
659	      remove_unwind_protect ();
660	      add_unwind_protect (xfree, input_string);
661	    }
662	}
663
664      /* If the next character is to be accepted verbatim, a backslash
665	 newline pair still disappears from the input. */
666      if (pass_next)
667	{
668	  pass_next = 0;
669	  if (c == '\n')
670	    {
671	      if (skip_ctlesc == 0 && i > 0)
672		i--;		/* back up over the CTLESC */
673	      if (interactive && input_is_tty && raw == 0)
674		print_ps2 = 1;
675	    }
676	  else
677	    goto add_char;
678	  continue;
679	}
680
681      /* This may cause problems if IFS contains CTLESC */
682      if (c == '\\' && raw == 0)
683	{
684	  pass_next++;
685	  if (skip_ctlesc == 0)
686	    {
687	      saw_escape++;
688	      input_string[i++] = CTLESC;
689	    }
690	  continue;
691	}
692
693      if (ignore_delim == 0 && (unsigned char)c == delim)
694	break;
695
696      if (c == '\0' && delim != '\0')
697	continue;		/* skip NUL bytes in input */
698
699      if ((skip_ctlesc == 0 && c == CTLESC) || (skip_ctlnul == 0 && c == CTLNUL))
700	{
701	  saw_escape++;
702	  input_string[i++] = CTLESC;
703	}
704
705add_char:
706      input_string[i++] = c;
707      CHECK_ALRM;
708
709#if defined (HANDLE_MULTIBYTE)
710      /* XXX - what if C == 127? Can DEL introduce a multibyte sequence? */
711      if (mb_cur_max > 1 && is_basic (c) == 0)
712	{
713	  input_string[i] = '\0';	/* for simplicity and debugging */
714	  /* If we got input from readline, grab the next multibyte char from
715	     rlbuf. */
716#  if defined (READLINE)
717	  if (edit)
718	    {
719	      size_t clen;
720	      clen = mbrlen (rlbuf + rlind - 1, mb_cur_max, (mbstate_t *)NULL);
721	      /* We only deal with valid multibyte sequences longer than one
722		 byte. If we get anything else, we leave the one character
723		 copied and move on to the next. */
724	      if ((int)clen > 1)
725		{
726		  memcpy (input_string+i, rlbuf+rlind, clen-1);
727		  i += clen - 1;
728		  rlind += clen - 1;
729		}
730	    }
731	  else
732#  endif
733	  if (locale_utf8locale == 0 || ((c & 0x80) != 0))
734	    i += read_mbchar (fd, input_string, i, c, unbuffered_read);
735	}
736#endif
737
738      nr++;
739
740      if (nchars > 0 && nr >= nchars)
741	break;
742    }
743  input_string[i] = '\0';
744  CHECK_ALRM;
745
746#if defined (READLINE)
747  if (edit)
748    free (rlbuf);
749#endif
750
751  if (retval < 0)
752    {
753      t_errno = errno;
754      if (errno != EINTR)
755	builtin_error (_("read error: %d: %s"), fd, strerror (errno));
756      run_unwind_frame ("read_builtin");
757      return ((t_errno != EINTR) ? EXECUTION_FAILURE : 128+lastsig);
758    }
759
760  if (tmsec > 0 || tmusec > 0)
761    reset_alarm ();
762
763  if (nchars > 0 || delim != '\n')
764    {
765#if defined (READLINE)
766      if (edit)
767	{
768	  if (nchars > 0)
769	    rl_num_chars_to_read = 0;
770	  if (delim != '\n')
771	    reset_eol_delim ((char *)NULL);
772	}
773      else
774#endif
775      if (input_is_tty)
776	ttyrestore (&termsave);
777    }
778  else if (silent)
779    ttyrestore (&termsave);
780
781  if (unbuffered_read == 0)
782    zsyncfd (fd);
783
784#if defined (READLINE)
785  if (save_instream)
786    rl_instream = save_instream;	/* can't portably free it */
787#endif
788
789  discard_unwind_frame ("read_builtin");
790
791  retval = eof ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
792
793assign_vars:
794
795#if defined (ARRAY_VARS)
796  /* If -a was given, take the string read, break it into a list of words,
797     an assign them to `arrayname' in turn. */
798  if (arrayname)
799    {
800      if (legal_identifier (arrayname) == 0)
801	{
802	  sh_invalidid (arrayname);
803	  free (input_string);
804	  return (EXECUTION_FAILURE);
805	}
806
807      var = find_or_make_array_variable (arrayname, 1);
808      if (var == 0)
809	{
810	  free (input_string);
811	  return EXECUTION_FAILURE;	/* readonly or noassign */
812	}
813      if (assoc_p (var))
814	{
815          builtin_error (_("%s: cannot convert associative to indexed array"), arrayname);
816	  free (input_string);
817	  return EXECUTION_FAILURE;	/* existing associative array */
818	}
819      else if (invisible_p (var))
820	VUNSETATTR (var, att_invisible);
821      array_flush (array_cell (var));
822
823      alist = list_string (input_string, ifs_chars, 0);
824      if (alist)
825	{
826	  if (saw_escape)
827	    dequote_list (alist);
828	  else
829	    word_list_remove_quoted_nulls (alist);
830	  assign_array_var_from_word_list (var, alist, 0);
831	  dispose_words (alist);
832	}
833      free (input_string);
834      return (retval);
835    }
836#endif /* ARRAY_VARS */
837
838  /* If there are no variables, save the text of the line read to the
839     variable $REPLY.  ksh93 strips leading and trailing IFS whitespace,
840     so that `read x ; echo "$x"' and `read ; echo "$REPLY"' behave the
841     same way, but I believe that the difference in behaviors is useful
842     enough to not do it.  Without the bash behavior, there is no way
843     to read a line completely without interpretation or modification
844     unless you mess with $IFS (e.g., setting it to the empty string).
845     If you disagree, change the occurrences of `#if 0' to `#if 1' below. */
846  if (list == 0)
847    {
848#if 0
849      orig_input_string = input_string;
850      for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
851	;
852      input_string = t;
853      input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
854#endif
855
856      if (saw_escape)
857	{
858	  t = dequote_string (input_string);
859	  var = bind_variable ("REPLY", t, 0);
860	  free (t);
861	}
862      else
863	var = bind_variable ("REPLY", input_string, 0);
864      if (var == 0 || readonly_p (var) || noassign_p (var))
865	retval = EXECUTION_FAILURE;
866      else
867	VUNSETATTR (var, att_invisible);
868
869      free (input_string);
870      return (retval);
871    }
872
873  /* This code implements the Posix.2 spec for splitting the words
874     read and assigning them to variables. */
875  orig_input_string = input_string;
876
877  /* Remove IFS white space at the beginning of the input string.  If
878     $IFS is null, no field splitting is performed. */
879  for (t = input_string; ifs_chars && *ifs_chars && spctabnl(*t) && isifs(*t); t++)
880    ;
881  input_string = t;
882  for (; list->next; list = list->next)
883    {
884      varname = list->word->word;
885#if defined (ARRAY_VARS)
886      if (legal_identifier (varname) == 0 && valid_array_reference (varname, vflags) == 0)
887#else
888      if (legal_identifier (varname) == 0)
889#endif
890	{
891	  sh_invalidid (varname);
892	  free (orig_input_string);
893	  return (EXECUTION_FAILURE);
894	}
895
896      /* If there are more variables than words read from the input,
897	 the remaining variables are set to the empty string. */
898      if (*input_string)
899	{
900	  /* This call updates INPUT_STRING. */
901	  t = get_word_from_string (&input_string, ifs_chars, &e);
902	  if (t)
903	    *e = '\0';
904	  /* Don't bother to remove the CTLESC unless we added one
905	     somewhere while reading the string. */
906	  if (t && saw_escape)
907	    {
908	      t1 = dequote_string (t);
909	      var = bind_read_variable (varname, t1);
910	      free (t1);
911	    }
912	  else
913	    var = bind_read_variable (varname, t ? t : "");
914	}
915      else
916	{
917	  t = (char *)0;
918	  var = bind_read_variable (varname, "");
919	}
920
921      FREE (t);
922      if (var == 0)
923	{
924	  free (orig_input_string);
925	  return (EXECUTION_FAILURE);
926	}
927
928      stupidly_hack_special_variables (varname);
929      VUNSETATTR (var, att_invisible);
930    }
931
932  /* Now assign the rest of the line to the last variable argument. */
933#if defined (ARRAY_VARS)
934  if (legal_identifier (list->word->word) == 0 && valid_array_reference (list->word->word, vflags) == 0)
935#else
936  if (legal_identifier (list->word->word) == 0)
937#endif
938    {
939      sh_invalidid (list->word->word);
940      free (orig_input_string);
941      return (EXECUTION_FAILURE);
942    }
943
944#if 0
945  /* This has to be done this way rather than using string_list
946     and list_string because Posix.2 says that the last variable gets the
947     remaining words and their intervening separators. */
948  input_string = strip_trailing_ifs_whitespace (input_string, ifs_chars, saw_escape);
949#else
950  /* Check whether or not the number of fields is exactly the same as the
951     number of variables. */
952  tofree = NULL;
953  if (*input_string)
954    {
955      t1 = input_string;
956      t = get_word_from_string (&input_string, ifs_chars, &e);
957      if (*input_string == 0)
958	tofree = input_string = t;
959      else
960	{
961	  input_string = strip_trailing_ifs_whitespace (t1, ifs_chars, saw_escape);
962	  tofree = t;
963	}
964    }
965#endif
966
967  if (saw_escape && input_string && *input_string)
968    {
969      t = dequote_string (input_string);
970      var = bind_read_variable (list->word->word, t);
971      free (t);
972    }
973  else
974    var = bind_read_variable (list->word->word, input_string ? input_string : "");
975
976  if (var)
977    {
978      stupidly_hack_special_variables (list->word->word);
979      VUNSETATTR (var, att_invisible);
980    }
981  else
982    retval = EXECUTION_FAILURE;
983
984  FREE (tofree);
985  free (orig_input_string);
986
987  return (retval);
988}
989
990static SHELL_VAR *
991bind_read_variable (name, value)
992     char *name, *value;
993{
994  SHELL_VAR *v;
995
996  v = builtin_bind_variable (name, value, 0);
997  return (v == 0 ? v
998		 : ((readonly_p (v) || noassign_p (v)) ? (SHELL_VAR *)NULL : v));
999}
1000
1001#if defined (HANDLE_MULTIBYTE)
1002static int
1003read_mbchar (fd, string, ind, ch, unbuffered)
1004     int fd;
1005     char *string;
1006     int ind, ch, unbuffered;
1007{
1008  char mbchar[MB_LEN_MAX + 1];
1009  int i, n, r;
1010  char c;
1011  size_t ret;
1012  mbstate_t ps, ps_back;
1013  wchar_t wc;
1014
1015  memset (&ps, '\0', sizeof (mbstate_t));
1016  memset (&ps_back, '\0', sizeof (mbstate_t));
1017
1018  mbchar[0] = ch;
1019  i = 1;
1020  for (n = 0; n <= MB_LEN_MAX; n++)
1021    {
1022      ps_back = ps;
1023      ret = mbrtowc (&wc, mbchar, i, &ps);
1024      if (ret == (size_t)-2)
1025	{
1026	  ps = ps_back;
1027
1028	  /* We don't want to be interrupted during a multibyte char read */
1029	  if (unbuffered == 2)
1030	    r = zreadn (fd, &c, 1);
1031	  else if (unbuffered)
1032	    r = zread (fd, &c, 1);
1033	  else
1034	    r = zreadc (fd, &c);
1035	  if (r <= 0)
1036	    goto mbchar_return;
1037	  mbchar[i++] = c;
1038	  continue;
1039	}
1040      else if (ret == (size_t)-1 || ret == (size_t)0 || ret > (size_t)0)
1041	break;
1042    }
1043
1044mbchar_return:
1045  if (i > 1)	/* read a multibyte char */
1046    /* mbchar[0] is already string[ind-1] */
1047    for (r = 1; r < i; r++)
1048      string[ind+r-1] = mbchar[r];
1049  return i - 1;
1050}
1051#endif
1052
1053
1054static void
1055ttyrestore (ttp)
1056     struct ttsave *ttp;
1057{
1058  ttsetattr (ttp->fd, &(ttp->attrs));
1059  tty_modified = 0;
1060}
1061
1062void
1063read_tty_cleanup ()
1064{
1065  if (tty_modified)
1066    ttyrestore (&termsave);
1067}
1068
1069int
1070read_tty_modified ()
1071{
1072  return (tty_modified);
1073}
1074
1075#if defined (READLINE)
1076static rl_completion_func_t *old_attempted_completion_function = 0;
1077static rl_hook_func_t *old_startup_hook;
1078static char *deftext;
1079
1080static void
1081reset_attempted_completion_function (cp)
1082     char *cp;
1083{
1084  if (rl_attempted_completion_function == 0 && old_attempted_completion_function)
1085    rl_attempted_completion_function = old_attempted_completion_function;
1086}
1087
1088static int
1089set_itext ()
1090{
1091  int r1, r2;
1092
1093  r1 = r2 = 0;
1094  if (old_startup_hook)
1095    r1 = (*old_startup_hook) ();
1096  if (deftext)
1097    {
1098      r2 = rl_insert_text (deftext);
1099      deftext = (char *)NULL;
1100      rl_startup_hook = old_startup_hook;
1101      old_startup_hook = (rl_hook_func_t *)NULL;
1102    }
1103  return (r1 || r2);
1104}
1105
1106static char *
1107edit_line (p, itext)
1108     char *p;
1109     char *itext;
1110{
1111  char *ret;
1112  int len;
1113
1114  if (bash_readline_initialized == 0)
1115    initialize_readline ();
1116
1117  old_attempted_completion_function = rl_attempted_completion_function;
1118  rl_attempted_completion_function = (rl_completion_func_t *)NULL;
1119  bashline_set_event_hook ();
1120  if (itext)
1121    {
1122      old_startup_hook = rl_startup_hook;
1123      rl_startup_hook = set_itext;
1124      deftext = itext;
1125    }
1126
1127  ret = readline (p);
1128
1129  rl_attempted_completion_function = old_attempted_completion_function;
1130  old_attempted_completion_function = (rl_completion_func_t *)NULL;
1131  bashline_reset_event_hook ();
1132
1133  if (ret == 0)
1134    return ret;
1135  len = strlen (ret);
1136  ret = (char *)xrealloc (ret, len + 2);
1137  ret[len++] = delim;
1138  ret[len] = '\0';
1139  return ret;
1140}
1141
1142static int old_delim_ctype;
1143static rl_command_func_t *old_delim_func;
1144static int old_newline_ctype;
1145static rl_command_func_t *old_newline_func;
1146
1147static unsigned char delim_char;
1148
1149static void
1150set_eol_delim (c)
1151     int c;
1152{
1153  Keymap cmap;
1154
1155  if (bash_readline_initialized == 0)
1156    initialize_readline ();
1157  cmap = rl_get_keymap ();
1158
1159  /* Save the old delimiter char binding */
1160  old_newline_ctype = cmap[RETURN].type;
1161  old_newline_func =  cmap[RETURN].function;
1162  old_delim_ctype = cmap[c].type;
1163  old_delim_func = cmap[c].function;
1164
1165  /* Change newline to self-insert */
1166  cmap[RETURN].type = ISFUNC;
1167  cmap[RETURN].function = rl_insert;
1168
1169  /* Bind the delimiter character to accept-line. */
1170  cmap[c].type = ISFUNC;
1171  cmap[c].function = rl_newline;
1172
1173  delim_char = c;
1174}
1175
1176static void
1177reset_eol_delim (cp)
1178     char *cp;
1179{
1180  Keymap cmap;
1181
1182  cmap = rl_get_keymap ();
1183
1184  cmap[RETURN].type = old_newline_ctype;
1185  cmap[RETURN].function = old_newline_func;
1186
1187  cmap[delim_char].type = old_delim_ctype;
1188  cmap[delim_char].function = old_delim_func;
1189}
1190#endif
1191