No specific user configuration
[platform/upstream/bash.git] / input.c
1 /* input.c -- functions to perform buffered input with synchronization. */
2
3 /* Copyright (C) 1992-2009 Free Software Foundation, Inc.
4
5    This file is part of GNU Bash, the Bourne Again SHell.
6
7    Bash is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation, either version 3 of the License, or
10    (at your option) any later version.
11
12    Bash is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "config.h"
22
23 #include "bashtypes.h"
24 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
25 #  include <sys/file.h>
26 #endif
27 #include "filecntl.h"
28 #include "posixstat.h"
29 #include <stdio.h>
30 #include <errno.h>
31
32 #if defined (HAVE_UNISTD_H)
33 #  include <unistd.h>
34 #endif
35
36 #include "bashansi.h"
37 #include "bashintl.h"
38
39 #include "command.h"
40 #include "general.h"
41 #include "input.h"
42 #include "error.h"
43 #include "externs.h"
44 #include "quit.h"
45 #include "trap.h"
46
47 #if !defined (errno)
48 extern int errno;
49 #endif /* !errno */
50
51 #if defined (EAGAIN)
52 #  define X_EAGAIN EAGAIN
53 #else
54 #  define X_EAGAIN -99
55 #endif
56
57 #if defined (EWOULDBLOCK)
58 #  define X_EWOULDBLOCK EWOULDBLOCK
59 #else
60 #  define X_EWOULDBLOCK -99
61 #endif
62
63 extern void termsig_handler __P((int));
64
65 /* Functions to handle reading input on systems that don't restart read(2)
66    if a signal is received. */
67
68 static char localbuf[128];
69 static int local_index = 0, local_bufused = 0;
70
71 /* Posix and USG systems do not guarantee to restart read () if it is
72    interrupted by a signal.  We do the read ourselves, and restart it
73    if it returns EINTR. */
74 int
75 getc_with_restart (stream)
76      FILE *stream;
77 {
78   unsigned char uc;
79
80   CHECK_TERMSIG;
81
82   /* Try local buffering to reduce the number of read(2) calls. */
83   if (local_index == local_bufused || local_bufused == 0)
84     {
85       while (1)
86         {
87           QUIT;
88           run_pending_traps ();
89
90           local_bufused = read (fileno (stream), localbuf, sizeof(localbuf));
91           if (local_bufused > 0)
92             break;
93           else if (local_bufused == 0)
94             {
95               local_index = 0;
96               return EOF;
97             }
98           else if (errno == X_EAGAIN || errno == X_EWOULDBLOCK)
99             {
100               if (sh_unset_nodelay_mode (fileno (stream)) < 0)
101                 {
102                   sys_error (_("cannot reset nodelay mode for fd %d"), fileno (stream));
103                   local_index = local_bufused = 0;
104                   return EOF;
105                 }
106               continue;
107             }
108           else if (errno != EINTR)
109             {
110               local_index = local_bufused = 0;
111               return EOF;
112             }
113           else if (interrupt_state || terminating_signal)       /* QUIT; */
114             local_index = local_bufused = 0;
115         }
116       local_index = 0;
117     }
118   uc = localbuf[local_index++];
119   return uc;
120 }
121
122 int
123 ungetc_with_restart (c, stream)
124      int c;
125      FILE *stream;
126 {
127   if (local_index == 0 || c == EOF)
128     return EOF;
129   localbuf[--local_index] = c;
130   return c;
131 }
132
133 #if defined (BUFFERED_INPUT)
134
135 /* A facility similar to stdio, but input-only. */
136
137 #if defined (USING_BASH_MALLOC)
138 #  define MAX_INPUT_BUFFER_SIZE 8176
139 #else
140 #  define MAX_INPUT_BUFFER_SIZE 8192
141 #endif
142
143 #if !defined (SEEK_CUR)
144 #  define SEEK_CUR 1
145 #endif /* !SEEK_CUR */
146
147 #ifdef max
148 #  undef max
149 #endif
150 #define max(a, b)       (((a) > (b)) ? (a) : (b))
151 #ifdef min
152 #  undef min
153 #endif
154 #define min(a, b)       ((a) > (b) ? (b) : (a))
155
156 extern int interactive_shell;
157
158 int bash_input_fd_changed;
159
160 /* This provides a way to map from a file descriptor to the buffer
161    associated with that file descriptor, rather than just the other
162    way around.  This is needed so that buffers are managed properly
163    in constructs like 3<&4.  buffers[x]->b_fd == x -- that is how the
164    correspondence is maintained. */
165 static BUFFERED_STREAM **buffers = (BUFFERED_STREAM **)NULL;
166 static int nbuffers;
167
168 #define ALLOCATE_BUFFERS(n) \
169         do { if ((n) >= nbuffers) allocate_buffers (n); } while (0)
170
171 /* Make sure `buffers' has at least N elements. */
172 static void
173 allocate_buffers (n)
174      int n;
175 {
176   register int i, orig_nbuffers;
177
178   orig_nbuffers = nbuffers;
179   nbuffers = n + 20;
180   buffers = (BUFFERED_STREAM **)xrealloc
181     (buffers, nbuffers * sizeof (BUFFERED_STREAM *));
182
183   /* Zero out the new buffers. */
184   for (i = orig_nbuffers; i < nbuffers; i++)
185     buffers[i] = (BUFFERED_STREAM *)NULL;
186 }
187
188 /* Construct and return a BUFFERED_STREAM corresponding to file descriptor
189    FD, using BUFFER. */
190 static BUFFERED_STREAM *
191 make_buffered_stream (fd, buffer, bufsize)
192      int fd;
193      char *buffer;
194      size_t bufsize;
195 {
196   BUFFERED_STREAM *bp;
197
198   bp = (BUFFERED_STREAM *)xmalloc (sizeof (BUFFERED_STREAM));
199   ALLOCATE_BUFFERS (fd);
200   buffers[fd] = bp;
201   bp->b_fd = fd;
202   bp->b_buffer = buffer;
203   bp->b_size = bufsize;
204   bp->b_used = bp->b_inputp = bp->b_flag = 0;
205   if (bufsize == 1)
206     bp->b_flag |= B_UNBUFF;
207   if (O_TEXT && (fcntl (fd, F_GETFL) & O_TEXT) != 0)
208     bp->b_flag |= O_TEXT;
209   return (bp);
210 }
211
212 /* Allocate a new BUFFERED_STREAM, copy BP to it, and return the new copy. */
213 static BUFFERED_STREAM *
214 copy_buffered_stream (bp)
215      BUFFERED_STREAM *bp;
216 {
217   BUFFERED_STREAM *nbp;
218
219   if (!bp)
220     return ((BUFFERED_STREAM *)NULL);
221
222   nbp = (BUFFERED_STREAM *)xmalloc (sizeof (BUFFERED_STREAM));
223   xbcopy ((char *)bp, (char *)nbp, sizeof (BUFFERED_STREAM));
224   return (nbp);
225 }
226
227 int
228 set_bash_input_fd (fd)
229      int fd;
230 {
231   if (bash_input.type == st_bstream)
232     bash_input.location.buffered_fd = fd;
233   else if (interactive_shell == 0)
234     default_buffered_input = fd;
235   return 0;
236 }
237
238 int
239 fd_is_bash_input (fd)
240      int fd;
241 {
242   if (bash_input.type == st_bstream && bash_input.location.buffered_fd == fd)
243     return 1;
244   else if (interactive_shell == 0 && default_buffered_input == fd)
245     return 1;
246   return 0;
247 }
248
249 /* Save the buffered stream corresponding to file descriptor FD (which bash
250    is using to read input) to a buffered stream associated with NEW_FD.  If
251    NEW_FD is -1, a new file descriptor is allocated with fcntl.  The new
252    file descriptor is returned on success, -1 on error. */
253 int
254 save_bash_input (fd, new_fd)
255      int fd, new_fd;
256 {
257   int nfd;
258
259   /* Sync the stream so we can re-read from the new file descriptor.  We
260      might be able to avoid this by copying the buffered stream verbatim
261      to the new file descriptor. */
262   if (buffers[fd])
263     sync_buffered_stream (fd);
264
265   /* Now take care of duplicating the file descriptor that bash is
266      using for input, so we can reinitialize it later. */
267   nfd = (new_fd == -1) ? fcntl (fd, F_DUPFD, 10) : new_fd;
268   if (nfd == -1)
269     {
270       if (fcntl (fd, F_GETFD, 0) == 0)
271         sys_error (_("cannot allocate new file descriptor for bash input from fd %d"), fd);
272       return -1;
273     }
274
275   if (buffers[nfd])
276     {
277       /* What's this?  A stray buffer without an associated open file
278          descriptor?  Free up the buffer and report the error. */
279       internal_error (_("save_bash_input: buffer already exists for new fd %d"), nfd);
280       free_buffered_stream (buffers[nfd]);
281     }
282
283   /* Reinitialize bash_input.location. */
284   if (bash_input.type == st_bstream)
285     {
286       bash_input.location.buffered_fd = nfd;
287       fd_to_buffered_stream (nfd);
288       close_buffered_fd (fd);   /* XXX */
289     }
290   else
291     /* If the current input type is not a buffered stream, but the shell
292        is not interactive and therefore using a buffered stream to read
293        input (e.g. with an `eval exec 3>output' inside a script), note
294        that the input fd has been changed.  pop_stream() looks at this
295        value and adjusts the input fd to the new value of
296        default_buffered_input accordingly. */
297     bash_input_fd_changed++;
298
299   if (default_buffered_input == fd)
300     default_buffered_input = nfd;
301
302   SET_CLOSE_ON_EXEC (nfd);
303   return nfd;
304 }
305
306 /* Check that file descriptor FD is not the one that bash is currently
307    using to read input from a script.  FD is about to be duplicated onto,
308    which means that the kernel will close it for us.  If FD is the bash
309    input file descriptor, we need to seek backwards in the script (if
310    possible and necessary -- scripts read from stdin are still unbuffered),
311    allocate a new file descriptor to use for bash input, and re-initialize
312    the buffered stream.  Make sure the file descriptor used to save bash
313    input is set close-on-exec. Returns 0 on success, -1 on failure.  This
314    works only if fd is > 0 -- if fd == 0 and bash is reading input from
315    fd 0, sync_buffered_stream is used instead, to cooperate with input
316    redirection (look at redir.c:add_undo_redirect()). */
317 int
318 check_bash_input (fd)
319      int fd;
320 {
321   if (fd_is_bash_input (fd))
322     {
323       if (fd > 0)
324         return ((save_bash_input (fd, -1) == -1) ? -1 : 0);
325       else if (fd == 0)
326         return ((sync_buffered_stream (fd) == -1) ? -1 : 0);
327     }
328   return 0;
329 }
330       
331 /* This is the buffered stream analogue of dup2(fd1, fd2).  The
332    BUFFERED_STREAM corresponding to fd2 is deallocated, if one exists.
333    BUFFERS[fd1] is copied to BUFFERS[fd2].  This is called by the
334    redirect code for constructs like 4<&0 and 3</etc/rc.local. */
335 int
336 duplicate_buffered_stream (fd1, fd2)
337      int fd1, fd2;
338 {
339   int is_bash_input, m;
340
341   if (fd1 == fd2)
342     return 0;
343
344   m = max (fd1, fd2);
345   ALLOCATE_BUFFERS (m);
346
347   /* If FD2 is the file descriptor bash is currently using for shell input,
348      we need to do some extra work to make sure that the buffered stream
349      actually exists (it might not if fd1 was not active, and the copy
350      didn't actually do anything). */
351   is_bash_input = (bash_input.type == st_bstream) &&
352                   (bash_input.location.buffered_fd == fd2);
353
354   if (buffers[fd2])
355     {
356       /* If the two objects share the same b_buffer, don't free it. */
357       if (buffers[fd1] && buffers[fd1]->b_buffer && buffers[fd1]->b_buffer == buffers[fd2]->b_buffer)
358         buffers[fd2] = (BUFFERED_STREAM *)NULL;
359       else
360         free_buffered_stream (buffers[fd2]);
361     }
362   buffers[fd2] = copy_buffered_stream (buffers[fd1]);
363   if (buffers[fd2])
364     buffers[fd2]->b_fd = fd2;
365
366   if (is_bash_input)
367     {
368       if (!buffers[fd2])
369         fd_to_buffered_stream (fd2);
370       buffers[fd2]->b_flag |= B_WASBASHINPUT;
371     }
372
373   return (fd2);
374 }
375
376 /* Return 1 if a seek on FD will succeed. */
377 #define fd_is_seekable(fd) (lseek ((fd), 0L, SEEK_CUR) >= 0)
378
379 /* Take FD, a file descriptor, and create and return a buffered stream
380    corresponding to it.  If something is wrong and the file descriptor
381    is invalid, return a NULL stream. */
382 BUFFERED_STREAM *
383 fd_to_buffered_stream (fd)
384      int fd;
385 {
386   char *buffer;
387   size_t size;
388   struct stat sb;
389
390   if (fstat (fd, &sb) < 0)
391     {
392       close (fd);
393       return ((BUFFERED_STREAM *)NULL);
394     }
395
396   size = (fd_is_seekable (fd)) ? min (sb.st_size, MAX_INPUT_BUFFER_SIZE) : 1;
397   if (size == 0)
398     size = 1;
399   buffer = (char *)xmalloc (size);
400
401   return (make_buffered_stream (fd, buffer, size));
402 }
403
404 /* Return a buffered stream corresponding to FILE, a file name. */
405 BUFFERED_STREAM *
406 open_buffered_stream (file)
407      char *file;
408 {
409   int fd;
410
411   fd = open (file, O_RDONLY);
412   return ((fd >= 0) ? fd_to_buffered_stream (fd) : (BUFFERED_STREAM *)NULL);
413 }
414
415 /* Deallocate a buffered stream and free up its resources.  Make sure we
416    zero out the slot in BUFFERS that points to BP. */
417 void
418 free_buffered_stream (bp)
419      BUFFERED_STREAM *bp;
420 {
421   int n;
422
423   if (!bp)
424     return;
425
426   n = bp->b_fd;
427   if (bp->b_buffer)
428     free (bp->b_buffer);
429   free (bp);
430   buffers[n] = (BUFFERED_STREAM *)NULL;
431 }
432
433 /* Close the file descriptor associated with BP, a buffered stream, and free
434    up the stream.  Return the status of closing BP's file descriptor. */
435 int
436 close_buffered_stream (bp)
437      BUFFERED_STREAM *bp;
438 {
439   int fd;
440
441   if (!bp)
442     return (0);
443   fd = bp->b_fd;
444   free_buffered_stream (bp);
445   return (close (fd));
446 }
447
448 /* Deallocate the buffered stream associated with file descriptor FD, and
449    close FD.  Return the status of the close on FD. */
450 int
451 close_buffered_fd (fd)
452      int fd;
453 {
454   if (fd < 0)
455     {
456       errno = EBADF;
457       return -1;
458     }
459   if (fd >= nbuffers || !buffers || !buffers[fd])
460     return (close (fd));
461   return (close_buffered_stream (buffers[fd]));
462 }
463
464 /* Make the BUFFERED_STREAM associated with buffers[FD] be BP, and return
465    the old BUFFERED_STREAM. */
466 BUFFERED_STREAM *
467 set_buffered_stream (fd, bp)
468      int fd;
469      BUFFERED_STREAM *bp;
470 {
471   BUFFERED_STREAM *ret;
472
473   ret = buffers[fd];
474   buffers[fd] = bp;
475   return ret;
476 }
477
478 /* Read a buffer full of characters from BP, a buffered stream. */
479 static int
480 b_fill_buffer (bp)
481      BUFFERED_STREAM *bp;
482 {
483   ssize_t nr;
484   off_t o;
485
486   CHECK_TERMSIG;
487   /* In an environment where text and binary files are treated differently,
488      compensate for lseek() on text files returning an offset different from
489      the count of characters read() returns.  Text-mode streams have to be
490      treated as unbuffered. */
491   if ((bp->b_flag & (B_TEXT | B_UNBUFF)) == B_TEXT)
492     {
493       o = lseek (bp->b_fd, 0, SEEK_CUR);
494       nr = zread (bp->b_fd, bp->b_buffer, bp->b_size);
495       if (nr > 0 && nr < lseek (bp->b_fd, 0, SEEK_CUR) - o)
496         {
497           lseek (bp->b_fd, o, SEEK_SET);
498           bp->b_flag |= B_UNBUFF;
499           bp->b_size = 1;
500           nr = zread (bp->b_fd, bp->b_buffer, bp->b_size);
501         }
502     }
503   else
504     nr = zread (bp->b_fd, bp->b_buffer, bp->b_size);
505   if (nr <= 0)
506     {
507       bp->b_used = 0;
508       bp->b_buffer[0] = 0;
509       if (nr == 0)
510         bp->b_flag |= B_EOF;
511       else
512         bp->b_flag |= B_ERROR;
513       return (EOF);
514     }
515
516   bp->b_used = nr;
517   bp->b_inputp = 0;
518   return (bp->b_buffer[bp->b_inputp++] & 0xFF);
519 }
520
521 /* Get a character from buffered stream BP. */
522 #define bufstream_getc(bp) \
523   (bp->b_inputp == bp->b_used || !bp->b_used) \
524                 ? b_fill_buffer (bp) \
525                 : bp->b_buffer[bp->b_inputp++] & 0xFF
526
527 /* Push C back onto buffered stream BP. */
528 static int
529 bufstream_ungetc(c, bp)
530      int c;
531      BUFFERED_STREAM *bp;
532 {
533   if (c == EOF || bp->b_inputp == 0)
534     return (EOF);
535
536   bp->b_buffer[--bp->b_inputp] = c;
537   return (c);
538 }
539
540 /* Seek backwards on file BFD to synchronize what we've read so far
541    with the underlying file pointer. */
542 int
543 sync_buffered_stream (bfd)
544      int bfd;
545 {
546   BUFFERED_STREAM *bp;
547   off_t chars_left;
548
549   if (buffers == 0 || (bp = buffers[bfd]) == 0)
550     return (-1);
551
552   chars_left = bp->b_used - bp->b_inputp;
553   if (chars_left)
554     lseek (bp->b_fd, -chars_left, SEEK_CUR);
555   bp->b_used = bp->b_inputp = 0;
556   return (0);
557 }
558
559 int
560 buffered_getchar ()
561 {
562   CHECK_TERMSIG;
563
564 #if !defined (DJGPP)
565   return (bufstream_getc (buffers[bash_input.location.buffered_fd]));
566 #else
567   /* On DJGPP, ignore \r. */
568   int ch;
569   while ((ch = bufstream_getc (buffers[bash_input.location.buffered_fd])) == '\r')
570     ;
571   return ch;
572 #endif
573 }
574
575 int
576 buffered_ungetchar (c)
577      int c;
578 {
579   return (bufstream_ungetc (c, buffers[bash_input.location.buffered_fd]));
580 }
581
582 /* Make input come from file descriptor BFD through a buffered stream. */
583 void
584 with_input_from_buffered_stream (bfd, name)
585      int bfd;
586      char *name;
587 {
588   INPUT_STREAM location;
589   BUFFERED_STREAM *bp;
590
591   location.buffered_fd = bfd;
592   /* Make sure the buffered stream exists. */
593   bp = fd_to_buffered_stream (bfd);
594   init_yy_io (bp == 0 ? return_EOF : buffered_getchar,
595               buffered_ungetchar, st_bstream, name, location);
596 }
597
598 #if defined (TEST)
599 void *
600 xmalloc(s)
601 int s;
602 {
603         return (malloc (s));
604 }
605
606 void *
607 xrealloc(s, size)
608 char    *s;
609 int     size;
610 {
611         if (!s)
612                 return(malloc (size));
613         else
614                 return(realloc (s, size));
615 }
616
617 void
618 init_yy_io ()
619 {
620 }
621
622 process(bp)
623 BUFFERED_STREAM *bp;
624 {
625         int c;
626
627         while ((c = bufstream_getc(bp)) != EOF)
628                 putchar(c);
629 }
630
631 BASH_INPUT bash_input;
632
633 struct stat dsb;                /* can be used from gdb */
634
635 /* imitate /bin/cat */
636 main(argc, argv)
637 int     argc;
638 char    **argv;
639 {
640         register int i;
641         BUFFERED_STREAM *bp;
642
643         if (argc == 1) {
644                 bp = fd_to_buffered_stream (0);
645                 process(bp);
646                 exit(0);
647         }
648         for (i = 1; i < argc; i++) {
649                 if (argv[i][0] == '-' && argv[i][1] == '\0') {
650                         bp = fd_to_buffered_stream (0);
651                         if (!bp)
652                                 continue;
653                         process(bp);
654                         free_buffered_stream (bp);
655                 } else {
656                         bp = open_buffered_stream (argv[i]);
657                         if (!bp)
658                                 continue;
659                         process(bp);
660                         close_buffered_stream (bp);
661                 }
662         }
663         exit(0);
664 }
665 #endif /* TEST */
666 #endif /* BUFFERED_INPUT */