Imported from ../bash-1.14.7.tar.gz.
[platform/upstream/bash.git] / execute_cmd.c
1 /* execute_command.c -- Execute a COMMAND structure. */
2
3 /* Copyright (C) 1987,1991 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 it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 1, or (at your option)
10    any later version.
11
12    Bash is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash; see the file COPYING.  If not, write to the Free
19    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
20 #if defined (AIX) && defined (RISC6000) && !defined (__GNUC__)
21   #pragma alloca
22 #endif /* AIX && RISC6000 && !__GNUC__ */
23
24 #include <stdio.h>
25 #include <ctype.h>
26 #include "bashtypes.h"
27 #include <sys/file.h>
28 #include "filecntl.h"
29 #include "posixstat.h"
30 #include <signal.h>
31
32 #if !defined (SIGABRT)
33 #define SIGABRT SIGIOT
34 #endif
35
36 #include <sys/param.h>
37 #include <errno.h>
38
39 #if !defined (errno)
40 extern int errno;
41 #endif
42
43 #if defined (HAVE_STRING_H)
44 #  include <string.h>
45 #else /* !HAVE_STRING_H */
46 #  include <strings.h>
47 #endif /* !HAVE_STRING_H */
48
49 #include "shell.h"
50 #include "y.tab.h"
51 #include "flags.h"
52 #include "hash.h"
53 #include "jobs.h"
54 #include "execute_cmd.h"
55
56 #include "sysdefs.h"
57 #include "builtins/common.h"
58 #include "builtins/builtext.h"  /* list of builtins */
59
60 #include <glob/fnmatch.h>
61 #include <tilde/tilde.h>
62
63 #if defined (BUFFERED_INPUT)
64 #  include "input.h"
65 #endif
66
67 extern int posixly_correct;
68 extern int breaking, continuing, loop_level;
69 extern int interactive, interactive_shell, login_shell;
70 extern int parse_and_execute_level;
71 extern int command_string_index, variable_context, line_number;
72 extern int dot_found_in_search;
73 extern char **temporary_env, **function_env, **builtin_env;
74 extern char *the_printed_command, *shell_name;
75 extern pid_t last_command_subst_pid;
76 extern Function *last_shell_builtin, *this_shell_builtin;
77 extern jmp_buf top_level, subshell_top_level;
78 extern int subshell_argc;
79 extern char **subshell_argv, **subshell_envp;
80 extern int already_making_children;
81
82 extern int getdtablesize ();
83 extern int close ();
84
85 /* Static functions defined and used in this file. */
86 static void close_pipes (), do_piping (), execute_disk_command ();
87 static void execute_subshell_builtin_or_function ();
88 static void cleanup_redirects (), cleanup_func_redirects (), bind_lastarg ();
89 static void add_undo_close_redirect (), add_exec_redirect ();
90 static int do_redirection_internal (), do_redirections ();
91 static int expandable_redirection_filename (), execute_shell_script ();
92 static int execute_builtin_or_function (), add_undo_redirect ();
93 static char *find_user_command_internal (), *find_user_command_in_path ();
94
95 /* The line number that the currently executing function starts on. */
96 static int function_line_number = 0;
97
98 /* Set to 1 if fd 0 was the subject of redirection to a subshell. */
99 static int stdin_redir = 0;
100
101 /* The name of the command that is currently being executed.
102    `test' needs this, for example. */
103 char *this_command_name;
104
105 struct stat SB;         /* used for debugging */
106
107 static REDIRECTEE rd;
108
109 /* For catching RETURN in a function. */
110 int return_catch_flag = 0;
111 int return_catch_value;
112 jmp_buf return_catch;
113
114 /* The value returned by the last synchronous command. */
115 int last_command_exit_value = 0;
116
117 /* The list of redirections to perform which will undo the redirections
118    that I made in the shell. */
119 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
120
121 /* The list of redirections to perform which will undo the internal
122    redirections performed by the `exec' builtin.  These are redirections
123    that must be undone even when exec discards redirection_undo_list. */
124 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
125
126 /* Non-zero if we have just forked and are currently running in a subshell
127    environment. */
128 int subshell_environment = 0;
129
130 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
131
132 #define FD_BITMAP_DEFAULT_SIZE 32
133 /* Functions to allocate and deallocate the structures used to pass
134    information from the shell to its children about file descriptors
135    to close. */
136 struct fd_bitmap *
137 new_fd_bitmap (size)
138      long size;
139 {
140   struct fd_bitmap *ret;
141
142   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
143
144   ret->size = size;
145
146   if (size)
147     {
148       ret->bitmap = xmalloc (size);
149       bzero (ret->bitmap, size);
150     }
151   else
152     ret->bitmap = (char *)NULL;
153   return (ret);
154 }
155
156 void
157 dispose_fd_bitmap (fdbp)
158      struct fd_bitmap *fdbp;
159 {
160   FREE (fdbp->bitmap);
161   free (fdbp);
162 }
163
164 void
165 close_fd_bitmap (fdbp)
166      struct fd_bitmap *fdbp;
167 {
168   register int i;
169
170   if (fdbp)
171     {
172       for (i = 0; i < fdbp->size; i++)
173         if (fdbp->bitmap[i])
174           {
175             close (i);
176             fdbp->bitmap[i] = 0;
177           }
178     }
179 }
180
181 /* Execute the command passed in COMMAND.  COMMAND is exactly what
182    read_command () places into GLOBAL_COMMAND.  See "command.h" for the
183    details of the command structure.
184
185    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
186    return values.  Executing a command with nothing in it returns
187    EXECUTION_SUCCESS. */
188 execute_command (command)
189      COMMAND *command;
190 {
191   struct fd_bitmap *bitmap;
192   int result;
193
194   current_fds_to_close = (struct fd_bitmap *)NULL;
195   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
196   begin_unwind_frame ("execute-command");
197   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
198
199   /* Just do the command, but not asynchronously. */
200   result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
201
202   dispose_fd_bitmap (bitmap);
203   discard_unwind_frame ("execute-command");
204
205 #if defined (PROCESS_SUBSTITUTION)
206   unlink_fifo_list ();
207 #endif /* PROCESS_SUBSTITUTION */
208
209   return (result);
210 }
211
212 /* Return 1 if TYPE is a shell control structure type. */
213 static int
214 shell_control_structure (type)
215      enum command_type type;
216 {
217   switch (type)
218     {
219     case cm_for:
220 #if defined (SELECT_COMMAND)
221     case cm_select:
222 #endif
223     case cm_case:
224     case cm_while:
225     case cm_until:
226     case cm_if:
227     case cm_group:
228       return (1);
229
230     default:
231       return (0);
232     }
233 }
234
235 /* A function to use to unwind_protect the redirection undo list
236    for loops. */
237 static void
238 cleanup_redirects (list)
239      REDIRECT *list;
240 {
241   do_redirections (list, 1, 0, 0);
242   dispose_redirects (list);
243 }
244
245 /* Function to unwind_protect the redirections for functions and builtins. */
246 static void
247 cleanup_func_redirects (list)
248      REDIRECT *list;
249 {
250   do_redirections (list, 1, 0, 0);
251 }
252
253 static void
254 dispose_exec_redirects ()
255 {
256   if (exec_redirection_undo_list)
257     {
258       dispose_redirects (exec_redirection_undo_list);
259       exec_redirection_undo_list = (REDIRECT *)NULL;
260     }
261 }
262
263 #if defined (JOB_CONTROL)
264 /* A function to restore the signal mask to its proper value when the shell
265    is interrupted or errors occur while creating a pipeline. */
266 static int
267 restore_signal_mask (set)
268      sigset_t set;
269 {
270   return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
271 }
272 #endif /* JOB_CONTROL */
273
274 /* A debugging function that can be called from gdb, for instance. */
275 void
276 open_files ()
277 {
278   register int i;
279   int f, fd_table_size;
280
281   fd_table_size = getdtablesize ();
282
283   fprintf (stderr, "pid %d open files:", getpid ());
284   for (i = 3; i < fd_table_size; i++)
285     {
286       if ((f = fcntl (i, F_GETFD, 0)) != -1)
287         fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
288     }
289   fprintf (stderr, "\n");
290 }
291
292 #define DESCRIBE_PID(pid) if (interactive) describe_pid (pid)
293
294 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
295    COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
296    ASYNCHROUNOUS, if non-zero, says to do this command in the background.
297    PIPE_IN and PIPE_OUT are file descriptors saying where input comes
298    from and where it goes.  They can have the value of NO_PIPE, which means
299    I/O is stdin/stdout.
300    FDS_TO_CLOSE is a list of file descriptors to close once the child has
301    been forked.  This list often contains the unusable sides of pipes, etc.
302
303    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
304    return values.  Executing a command with nothing in it returns
305    EXECUTION_SUCCESS. */
306 execute_command_internal (command, asynchronous, pipe_in, pipe_out, 
307                           fds_to_close)
308      COMMAND *command;
309      int asynchronous;
310      int pipe_in, pipe_out;
311      struct fd_bitmap *fds_to_close;
312 {
313   int exec_result = EXECUTION_SUCCESS;
314   int invert, ignore_return;
315   REDIRECT *my_undo_list, *exec_undo_list;
316
317   if (!command || breaking || continuing)
318     return (EXECUTION_SUCCESS);
319
320   run_pending_traps ();
321
322   invert = (command->flags & CMD_INVERT_RETURN) != 0;
323
324   /* If a command was being explicitly run in a subshell, or if it is
325      a shell control-structure, and it has a pipe, then we do the command
326      in a subshell. */
327
328   if ((command->flags & CMD_WANT_SUBSHELL) ||
329       (command->flags & CMD_FORCE_SUBSHELL)  ||
330       (shell_control_structure (command->type) &&
331        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
332     {
333       pid_t paren_pid;
334
335       /* Fork a subshell, turn off the subshell bit, turn off job
336          control and call execute_command () on the command again. */
337       paren_pid = make_child (savestring (make_command_string (command)),
338                               asynchronous);
339       if (paren_pid == 0)
340         {
341           int user_subshell, return_code, function_value;
342
343           /* Cancel traps, in trap.c. */
344           restore_original_signals ();
345           if (asynchronous)
346             setup_async_signals ();
347
348 #if defined (JOB_CONTROL)
349           set_sigchld_handler ();
350 #endif /* JOB_CONTROL */
351
352           set_sigint_handler ();
353
354           user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
355           command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
356
357           /* If a command is asynchronous in a subshell (like ( foo ) & or
358              the special case of an asynchronous GROUP command where the
359              the subshell bit is turned on down in case cm_group: below), 
360              turn off `asynchronous', so that two subshells aren't spawned.
361
362              This seems semantically correct to me.  For example, 
363              ( foo ) & seems to say ``do the command `foo' in a subshell
364              environment, but don't wait for that subshell to finish'',
365              and "{ foo ; bar } &" seems to me to be like functions or
366              builtins in the background, which executed in a subshell
367              environment.  I just don't see the need to fork two subshells. */
368
369           /* Don't fork again, we are already in a subshell.  A `doubly
370              async' shell is not interactive, however. */
371           if (asynchronous)
372             {
373 #if defined (JOB_CONTROL)
374               /* If a construct like ( exec xxx yyy ) & is given while job
375                  control is active, we want to prevent exec from putting the
376                  subshell back into the original process group, carefully
377                  undoing all the work we just did in make_child. */
378               original_pgrp = -1;
379 #endif /* JOB_CONTROL */
380               interactive_shell = 0;
381               asynchronous = 0;
382             }
383
384           /* Subshells are neither login nor interactive. */
385           login_shell = interactive = 0;
386
387           subshell_environment = 1;
388
389 #if defined (JOB_CONTROL)
390           /* Delete all traces that there were any jobs running.  This is
391              only for subshells. */
392           without_job_control ();
393 #endif /* JOB_CONTROL */
394           do_piping (pipe_in, pipe_out);
395
396           /* If this is a user subshell, set a flag if stdin was redirected.
397              This is used later to decide whether to redirect fd 0 to
398              /dev/null for async commands in the subshell.  This adds more
399              sh compatibility, but I'm not sure it's the right thing to do. */
400           if (user_subshell)
401             {
402               REDIRECT *r;
403
404               for (r = command->redirects; r; r = r->next)
405                 switch (r->instruction)
406                   {
407                   case r_input_direction:
408                   case r_inputa_direction:
409                   case r_input_output:
410                   case r_reading_until:
411                   case r_deblank_reading_until:
412                     stdin_redir++;
413                     break;
414                   case r_duplicating_input:
415                   case r_duplicating_input_word:
416                   case r_close_this:
417                     if (r->redirector == 0)
418                       stdin_redir++;
419                     break;
420                   }
421             }
422
423           if (fds_to_close)
424             close_fd_bitmap (fds_to_close);
425
426           /* Do redirections, then dispose of them before recursive call. */
427           if (command->redirects)
428             {
429               if (do_redirections (command->redirects, 1, 0, 0) != 0)
430                 exit (EXECUTION_FAILURE);
431
432               dispose_redirects (command->redirects);
433               command->redirects = (REDIRECT *)NULL;
434             }
435
436           /* If this is a simple command, tell execute_disk_command that it
437              might be able to get away without forking and simply exec.
438              This means things like ( sleep 10 ) will only cause one fork. */
439           if (user_subshell && command->type == cm_simple)
440             {
441               command->flags |= CMD_NO_FORK;
442               command->value.Simple->flags |= CMD_NO_FORK;
443             }
444
445           /* If we're inside a function while executing this subshell, we
446              need to handle a possible `return'. */
447           function_value = 0;
448           if (return_catch_flag)
449             function_value =  setjmp (return_catch);
450
451           if (function_value)
452             return_code = return_catch_value;
453           else
454             return_code = execute_command_internal
455               (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
456
457           /* If we were explicitly placed in a subshell with (), we need
458              to do the `shell cleanup' things, such as running traps[0]. */
459           if (user_subshell && signal_is_trapped (0))
460             {
461               last_command_exit_value = return_code;
462               return_code = run_exit_trap ();
463             }
464
465           exit (return_code);
466         }
467       else
468         {
469           close_pipes (pipe_in, pipe_out);
470
471 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
472           unlink_fifo_list ();
473 #endif
474           /* If we are part of a pipeline, and not the end of the pipeline,
475              then we should simply return and let the last command in the
476              pipe be waited for.  If we are not in a pipeline, or are the
477              last command in the pipeline, then we wait for the subshell 
478              and return its exit status as usual. */
479           if (pipe_out != NO_PIPE)
480             return (EXECUTION_SUCCESS);
481
482           stop_pipeline (asynchronous, (COMMAND *)NULL);
483
484           if (!asynchronous)
485             {
486               last_command_exit_value = wait_for (paren_pid);
487
488               /* If we have to, invert the return value. */
489               if (invert)
490                 {
491                   if (last_command_exit_value == EXECUTION_SUCCESS)
492                     return (EXECUTION_FAILURE);
493                   else
494                     return (EXECUTION_SUCCESS);
495                 }
496               else
497                 return (last_command_exit_value);
498             }
499           else
500             {
501               DESCRIBE_PID (paren_pid);
502
503               run_pending_traps ();
504
505               return (EXECUTION_SUCCESS);
506             }
507         }
508     }
509
510   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
511      redirection.)  */
512   if (do_redirections (command->redirects, 1, 1, 0) != 0)
513     {
514       cleanup_redirects (redirection_undo_list);
515       redirection_undo_list = (REDIRECT *)NULL;
516       dispose_exec_redirects ();
517       return (EXECUTION_FAILURE);
518     }
519
520   if (redirection_undo_list)
521     {
522       my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
523       dispose_redirects (redirection_undo_list);
524       redirection_undo_list = (REDIRECT *)NULL;
525     }
526   else
527     my_undo_list = (REDIRECT *)NULL;
528
529   if (exec_redirection_undo_list)
530     {
531       exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
532       dispose_redirects (exec_redirection_undo_list);
533       exec_redirection_undo_list = (REDIRECT *)NULL;
534     }
535   else
536     exec_undo_list = (REDIRECT *)NULL;
537
538   if (my_undo_list || exec_undo_list)
539     begin_unwind_frame ("loop_redirections");
540
541   if (my_undo_list)
542     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
543
544   if (exec_undo_list)
545     add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
546
547   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
548
549   QUIT;
550
551   switch (command->type)
552     {
553     case cm_for:
554       if (ignore_return)
555         command->value.For->flags |= CMD_IGNORE_RETURN;
556       exec_result = execute_for_command (command->value.For);
557       break;
558
559 #if defined (SELECT_COMMAND)
560     case cm_select:
561       if (ignore_return)
562         command->value.Select->flags |= CMD_IGNORE_RETURN;
563       exec_result = execute_select_command (command->value.Select);
564       break;
565 #endif
566
567     case cm_case:
568       if (ignore_return)
569         command->value.Case->flags |= CMD_IGNORE_RETURN;
570       exec_result = execute_case_command (command->value.Case);
571       break;
572
573     case cm_while:
574       if (ignore_return)
575         command->value.While->flags |= CMD_IGNORE_RETURN;
576       exec_result = execute_while_command (command->value.While);
577       break;
578
579     case cm_until:
580       if (ignore_return)
581         command->value.While->flags |= CMD_IGNORE_RETURN;
582       exec_result = execute_until_command (command->value.While);
583       break;
584
585     case cm_if:
586       if (ignore_return)
587         command->value.If->flags |= CMD_IGNORE_RETURN;
588       exec_result = execute_if_command (command->value.If);
589       break;
590
591     case cm_group:
592
593       /* This code can be executed from either of two paths: an explicit
594          '{}' command, or via a function call.  If we are executed via a
595          function call, we have already taken care of the function being
596          executed in the background (down there in execute_simple_command ()),
597          and this command should *not* be marked as asynchronous.  If we
598          are executing a regular '{}' group command, and asynchronous == 1,
599          we must want to execute the whole command in the background, so we
600          need a subshell, and we want the stuff executed in that subshell
601          (this group command) to be executed in the foreground of that
602          subshell (i.e. there will not be *another* subshell forked).
603
604          What we do is to force a subshell if asynchronous, and then call
605          execute_command_internal again with asynchronous still set to 1,
606          but with the original group command, so the printed command will
607          look right.
608
609          The code above that handles forking off subshells will note that
610          both subshell and async are on, and turn off async in the child
611          after forking the subshell (but leave async set in the parent, so
612          the normal call to describe_pid is made).  This turning off
613          async is *crucial*; if it is not done, this will fall into an
614          infinite loop of executions through this spot in subshell after
615          subshell until the process limit is exhausted. */
616
617       if (asynchronous)
618         {
619           command->flags |= CMD_FORCE_SUBSHELL;
620           exec_result =
621             execute_command_internal (command, 1, pipe_in, pipe_out,
622                                       fds_to_close);
623         }
624       else
625         {
626           if (ignore_return && command->value.Group->command)
627             command->value.Group->command->flags |= CMD_IGNORE_RETURN;
628           exec_result =
629             execute_command_internal (command->value.Group->command,
630                                       asynchronous, pipe_in, pipe_out,
631                                       fds_to_close);
632         }
633       break;
634
635     case cm_simple:
636       {
637         /* We can't rely on this variable retaining its value across a
638            call to execute_simple_command if a longjmp occurs as the
639            result of a `return' builtin.  This is true for sure with gcc. */
640         pid_t last_pid = last_made_pid;
641
642         if (ignore_return && command->value.Simple)
643           command->value.Simple->flags |= CMD_IGNORE_RETURN;
644         exec_result =
645           execute_simple_command (command->value.Simple, pipe_in, pipe_out,
646                                   asynchronous, fds_to_close);
647
648         /* The temporary environment should be used for only the simple
649            command immediately following its definition. */
650         dispose_used_env_vars ();
651
652 #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
653         /* Reclaim memory allocated with alloca () on machines which
654            may be using the alloca emulation code. */
655         (void) alloca (0);
656 #endif /* (Ultrix && mips) || !HAVE_ALLOCA */
657
658         /* If we forked to do the command, then we must wait_for ()
659            the child. */
660
661         /* XXX - this is something to watch out for if there are problems
662            when the shell is compiled without job control. */
663         if (already_making_children && pipe_out == NO_PIPE &&
664             last_pid != last_made_pid)
665           {
666             stop_pipeline (asynchronous, (COMMAND *)NULL);
667
668             if (asynchronous)
669               {
670                 DESCRIBE_PID (last_made_pid);
671               }
672             else
673 #if !defined (JOB_CONTROL)
674               /* Do not wait for asynchronous processes started from
675                  startup files. */
676             if (last_made_pid != last_asynchronous_pid)
677 #endif
678             /* When executing a shell function that executes other
679                commands, this causes the last simple command in
680                the function to be waited for twice. */
681               exec_result = wait_for (last_made_pid);
682           }
683       }
684
685       if (!ignore_return && exit_immediately_on_error && !invert &&
686           (exec_result != EXECUTION_SUCCESS))
687         {
688           last_command_exit_value = exec_result;
689           run_pending_traps ();
690           longjmp (top_level, EXITPROG);
691         }
692
693       break;
694
695     case cm_connection:
696       switch (command->value.Connection->connector)
697         {
698           /* Do the first command asynchronously. */
699         case '&':
700           {
701             COMMAND *tc = command->value.Connection->first;
702             REDIRECT *rp;
703
704             if (!tc)
705               break;
706
707             rp = tc->redirects;
708
709             if (ignore_return && tc)
710               tc->flags |= CMD_IGNORE_RETURN;
711
712             /* If this shell was compiled without job control support, if
713                the shell is not running interactively, if we are currently
714                in a subshell via `( xxx )', or if job control is not active
715                then the standard input for an asynchronous command is
716                forced to /dev/null. */
717 #if defined (JOB_CONTROL)
718             if ((!interactive_shell || subshell_environment || !job_control) &&
719                 !stdin_redir)
720 #else
721             if (!stdin_redir)
722 #endif /* JOB_CONTROL */
723             {
724               REDIRECT *tr;
725
726               rd.filename = make_word ("/dev/null");
727               tr = make_redirection (0, r_inputa_direction, rd);
728               tr->next = tc->redirects;
729               tc->redirects = tr;
730             }
731
732             exec_result = execute_command_internal
733               (tc, 1, pipe_in, pipe_out, fds_to_close);
734
735 #if defined (JOB_CONTROL)
736             if ((!interactive_shell || subshell_environment || !job_control) &&
737                 !stdin_redir)
738 #else
739             if (!stdin_redir)
740 #endif /* JOB_CONTROL */
741             {
742               /* Remove the redirection we added above.  It matters,
743                  especially for loops, which call execute_command ()
744                  multiple times with the same command. */
745               REDIRECT *tr, *tl;
746
747               tr = tc->redirects;
748               do
749                 {
750                   tl = tc->redirects;
751                   tc->redirects = tc->redirects->next;
752                 }
753               while (tc->redirects && tc->redirects != rp);
754
755               tl->next = (REDIRECT *)NULL;
756               dispose_redirects (tr);
757             }
758
759             {
760               register COMMAND *second;
761
762               second = command->value.Connection->second;
763
764               if (second)
765                 {
766                   if (ignore_return)
767                     second->flags |= CMD_IGNORE_RETURN;
768
769                   exec_result = execute_command_internal
770                     (second, asynchronous, pipe_in, pipe_out, fds_to_close);
771                 }
772             }
773           }
774           break;
775
776         case ';':
777           /* Just call execute command on both of them. */
778           if (ignore_return)
779             {
780               if (command->value.Connection->first)
781                 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
782               if (command->value.Connection->second)
783                 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
784             }
785           QUIT;
786           execute_command (command->value.Connection->first);
787           QUIT;
788           exec_result =
789             execute_command_internal (command->value.Connection->second,
790                                       asynchronous, pipe_in, pipe_out,
791                                       fds_to_close);
792           break;
793
794         case '|':
795           {
796             int prev, fildes[2], new_bitmap_size, dummyfd;
797             COMMAND *cmd;
798             struct fd_bitmap *fd_bitmap;
799
800 #if defined (JOB_CONTROL)
801             sigset_t set, oset;
802             BLOCK_CHILD (set, oset);
803 #endif /* JOB_CONTROL */
804
805             prev = pipe_in;
806             cmd = command;
807
808             while (cmd &&
809                    cmd->type == cm_connection &&
810                    cmd->value.Connection &&
811                    cmd->value.Connection->connector == '|')
812               {
813                 /* Make a pipeline between the two commands. */
814                 if (pipe (fildes) < 0)
815                   {
816                     report_error ("pipe error: %s", strerror (errno));
817 #if defined (JOB_CONTROL)
818                     terminate_current_pipeline ();
819                     kill_current_pipeline ();
820 #endif /* JOB_CONTROL */
821                     last_command_exit_value = EXECUTION_FAILURE;
822                     /* The unwind-protects installed below will take care
823                        of closing all of the open file descriptors. */
824                     throw_to_top_level ();
825                   }
826                 else
827                   {
828                     /* Here is a problem: with the new file close-on-exec
829                        code, the read end of the pipe (fildes[0]) stays open
830                        in the first process, so that process will never get a
831                        SIGPIPE.  There is no way to signal the first process
832                        that it should close fildes[0] after forking, so it
833                        remains open.  No SIGPIPE is ever sent because there
834                        is still a file descriptor open for reading connected
835                        to the pipe.  We take care of that here.  This passes
836                        around a bitmap of file descriptors that must be
837                        closed after making a child process in
838                        execute_simple_command. */
839
840                     /* We need fd_bitmap to be at least as big as fildes[0].
841                        If fildes[0] is less than fds_to_close->size, then
842                        use fds_to_close->size. */
843                     if (fildes[0] < fds_to_close->size)
844                       new_bitmap_size = fds_to_close->size;
845                     else
846                       new_bitmap_size = fildes[0] + 8;
847
848                     fd_bitmap = new_fd_bitmap (new_bitmap_size);
849
850                     /* Now copy the old information into the new bitmap. */
851                     xbcopy ((char *)fds_to_close->bitmap,
852                             (char *)fd_bitmap->bitmap, fds_to_close->size);
853
854                     /* And mark the pipe file descriptors to be closed. */
855                     fd_bitmap->bitmap[fildes[0]] = 1;
856
857                     /* In case there are pipe or out-of-processes errors, we
858                        want all these file descriptors to be closed when
859                        unwind-protects are run, and the storage used for the
860                        bitmaps freed up. */
861                     begin_unwind_frame ("pipe-file-descriptors");
862                     add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
863                     add_unwind_protect (close_fd_bitmap, fd_bitmap);
864                     if (prev >= 0)
865                       add_unwind_protect (close, prev);
866                     dummyfd = fildes[1];
867                     add_unwind_protect (close, dummyfd);
868
869 #if defined (JOB_CONTROL)
870                     add_unwind_protect (restore_signal_mask, oset);
871 #endif /* JOB_CONTROL */
872
873                     if (ignore_return && cmd->value.Connection->first)
874                       cmd->value.Connection->first->flags |=
875                         CMD_IGNORE_RETURN;
876                     execute_command_internal
877                       (cmd->value.Connection->first, asynchronous, prev,
878                        fildes[1], fd_bitmap);
879
880                     if (prev >= 0)
881                       close (prev);
882                     
883                     prev = fildes[0];
884                     close (fildes[1]);
885
886                     dispose_fd_bitmap (fd_bitmap);
887                     discard_unwind_frame ("pipe-file-descriptors");
888                   }
889                 cmd = cmd->value.Connection->second;
890               }
891
892             /* Now execute the rightmost command in the pipeline.  */
893             if (ignore_return && cmd)
894               cmd->flags |= CMD_IGNORE_RETURN;
895             exec_result =
896               execute_command_internal
897                 (cmd, asynchronous, prev, pipe_out, fds_to_close);
898
899             if (prev >= 0)
900               close (prev);
901
902 #if defined (JOB_CONTROL)
903             UNBLOCK_CHILD (oset);
904 #endif
905           }
906           break;
907
908         case AND_AND:
909         case OR_OR:
910           if (asynchronous)
911             {
912               /* If we have something like `a && b &' or `a || b &', run the
913                  && or || stuff in a subshell.  Force a subshell and just call
914                  execute_command_internal again.  Leave asynchronous on
915                  so that we get a report from the parent shell about the
916                  background job. */
917               command->flags |= CMD_FORCE_SUBSHELL;
918               exec_result = execute_command_internal (command, 1, pipe_in,
919                               pipe_out, fds_to_close);
920               break;
921             }
922
923           /* Execute the first command.  If the result of that is successful
924              and the connector is AND_AND, or the result is not successful
925              and the connector is OR_OR, then execute the second command,
926              otherwise return. */
927
928           if (command->value.Connection->first)
929             command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
930
931           exec_result = execute_command (command->value.Connection->first);
932           QUIT;
933           if (((command->value.Connection->connector == AND_AND) && 
934                (exec_result == EXECUTION_SUCCESS)) ||
935               ((command->value.Connection->connector == OR_OR) &&
936                (exec_result != EXECUTION_SUCCESS)))
937             {
938               if (ignore_return && command->value.Connection->second)
939                 command->value.Connection->second->flags |=
940                   CMD_IGNORE_RETURN;
941
942               exec_result =
943                 execute_command (command->value.Connection->second);
944             }
945           break;
946
947         default:
948           programming_error ("Bad connector `%d'!",
949                              command->value.Connection->connector);
950           longjmp (top_level, DISCARD);
951           break;
952         }
953       break;
954
955     case cm_function_def:
956       exec_result = intern_function (command->value.Function_def->name,
957                                      command->value.Function_def->command);
958       break;
959
960     default:
961       programming_error
962         ("execute_command: Bad command type `%d'!", command->type);
963     }
964
965   if (my_undo_list)
966     {
967       do_redirections (my_undo_list, 1, 0, 0);
968       dispose_redirects (my_undo_list);
969     }
970
971   if (exec_undo_list)
972     dispose_redirects (exec_undo_list);
973
974   if (my_undo_list || exec_undo_list)
975     discard_unwind_frame ("loop_redirections");
976
977   /* Invert the return value if we have to */
978   if (invert)
979     {
980       if (exec_result == EXECUTION_SUCCESS)
981         exec_result = EXECUTION_FAILURE;
982       else
983         exec_result = EXECUTION_SUCCESS;
984     }
985
986   last_command_exit_value = exec_result;
987   run_pending_traps ();
988   return (last_command_exit_value);
989 }
990
991 #if defined (JOB_CONTROL)
992 #  define REAP() \
993         do \
994           { \
995             if (!interactive_shell) \
996               reap_dead_jobs (); \
997           } \
998         while (0)
999 #else /* !JOB_CONTROL */
1000 #  define REAP() \
1001         do \
1002           { \
1003             if (!interactive_shell) \
1004               cleanup_dead_jobs (); \
1005           } \
1006         while (0)
1007 #endif /* !JOB_CONTROL */
1008
1009
1010 /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
1011    DO command; DONE */
1012 execute_for_command (for_command)
1013      FOR_COM *for_command;
1014 {
1015   /* I just noticed that the Bourne shell leaves word_desc bound to the
1016      last name in word_list after the FOR statement is done.  This seems
1017      wrong to me; I thought that the variable binding should be lexically
1018      scoped, i.e., only would last the duration of the FOR command.  This
1019      behaviour can be gotten by turning on the lexical_scoping switch. */
1020
1021   register WORD_LIST *releaser, *list;
1022   char *identifier;
1023   SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1024   int retval = EXECUTION_SUCCESS;
1025
1026   if (check_identifier (for_command->name, 1) == 0)
1027     return (EXECUTION_FAILURE);
1028
1029   loop_level++;
1030   identifier = for_command->name->word;
1031
1032   list = releaser = expand_words_no_vars (for_command->map_list);
1033
1034   begin_unwind_frame ("for");
1035   add_unwind_protect (dispose_words, releaser);
1036
1037   if (lexical_scoping)
1038     {
1039       old_value = copy_variable (find_variable (identifier));
1040       if (old_value)
1041         add_unwind_protect (dispose_variable, old_value);
1042     }
1043
1044   if (for_command->flags & CMD_IGNORE_RETURN)
1045     for_command->action->flags |= CMD_IGNORE_RETURN;
1046
1047   while (list)
1048     {
1049       QUIT;
1050       bind_variable (identifier, list->word->word);
1051       execute_command (for_command->action);
1052       retval = last_command_exit_value;
1053       REAP ();
1054       QUIT;
1055
1056       if (breaking)
1057         {
1058           breaking--; 
1059           break;
1060         }
1061
1062       if (continuing)
1063         {
1064           continuing--;
1065           if (continuing)
1066             break;
1067         }
1068
1069       list = list->next;
1070     }
1071
1072   loop_level--;
1073
1074   if (lexical_scoping)
1075     {
1076       if (!old_value)
1077         makunbound (identifier, shell_variables);
1078       else
1079         {
1080           SHELL_VAR *new_value;
1081
1082           new_value = bind_variable (identifier, value_cell(old_value));
1083           new_value->attributes = old_value->attributes;
1084           dispose_variable (old_value);
1085         }
1086     }
1087
1088   dispose_words (releaser);
1089   discard_unwind_frame ("for");
1090   return (retval);
1091 }
1092
1093 #if defined (SELECT_COMMAND)
1094 static int LINES, COLS, tabsize;
1095
1096 #define RP_SPACE ") "
1097 #define RP_SPACE_LEN 2
1098
1099 /* XXX - does not handle numbers > 1000000 at all. */
1100 #define NUMBER_LEN(s) \
1101 ((s < 10) ? 1 \
1102           : ((s < 100) ? 2 \
1103                       : ((s < 1000) ? 3 \
1104                                    : ((s < 10000) ? 4 \
1105                                                  : ((s < 100000) ? 5 \
1106                                                                 : 6)))))
1107
1108 static int
1109 print_index_and_element (len, ind, list)
1110       int len, ind;
1111       WORD_LIST *list;
1112 {
1113   register WORD_LIST *l;
1114   register int i;
1115
1116   if (list == 0)
1117     return (0);
1118   i = ind;
1119   l = list;
1120   while (l && --i)
1121     l = l->next;
1122   fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1123   return (STRLEN (l->word->word));
1124 }
1125
1126 static void
1127 indent (from, to)
1128      int from, to;
1129 {
1130   while (from < to)
1131     {
1132       if ((to / tabsize) > (from / tabsize))
1133         {
1134           putc ('\t', stderr);
1135           from += tabsize - from % tabsize;
1136         }
1137       else
1138         {
1139           putc (' ', stderr);
1140           from++;
1141         }
1142     }
1143 }
1144
1145 static void
1146 print_select_list (list, list_len, max_elem_len, indices_len)
1147      WORD_LIST *list;
1148      int list_len, max_elem_len, indices_len;
1149 {
1150   int ind, row, elem_len, pos, cols, rows;
1151   int first_column_indices_len, other_indices_len;
1152
1153   if (list == 0)
1154     {
1155       putc ('\n', stderr);
1156       return;
1157     }
1158
1159   cols = COLS / max_elem_len;
1160   if (cols == 0)
1161     cols = 1;
1162   rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1163   cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1164
1165   if (rows == 1)
1166     {
1167       rows = cols;
1168       cols = 1;
1169     }
1170
1171   first_column_indices_len = NUMBER_LEN (rows);
1172   other_indices_len = indices_len;
1173
1174   for (row = 0; row < rows; row++)
1175     {
1176       ind = row;
1177       pos = 0;
1178       while (1)
1179         {
1180           indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1181           elem_len = print_index_and_element (indices_len, ind + 1, list);
1182           elem_len += indices_len + RP_SPACE_LEN;
1183           ind += rows;
1184           if (ind >= list_len)
1185             break;
1186           indent (pos + elem_len, pos + max_elem_len);
1187           pos += max_elem_len;
1188         }
1189       putc ('\n', stderr);
1190     }
1191 }
1192
1193 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1194    LIST_LEN.  Then display PROMPT and wait for the user to enter a number.
1195    If the number is between 1 and LIST_LEN, return that selection.  If EOF
1196    is read, return a null string.  If a blank line is entered, the loop is
1197    executed again. */
1198 static char *
1199 select_query (list, list_len, prompt)
1200      WORD_LIST *list;
1201      int list_len;
1202      char *prompt;
1203 {
1204   int max_elem_len, indices_len, len, reply;
1205   WORD_LIST *l;
1206   char *repl_string, *t;
1207
1208   t = get_string_value ("LINES");
1209   LINES = (t && *t) ? atoi (t) : 24;
1210   t = get_string_value ("COLUMNS");
1211   COLS =  (t && *t) ? atoi (t) : 80;
1212
1213 #if 0
1214   t = get_string_value ("TABSIZE");
1215   tabsize = (t && *t) ? atoi (t) : 8;
1216   if (tabsize <= 0)
1217     tabsize = 8;
1218 #else
1219   tabsize = 8;
1220 #endif
1221
1222   max_elem_len = 0;
1223   for (l = list; l; l = l->next)
1224     {
1225       len = STRLEN (l->word->word);
1226       if (len > max_elem_len)
1227         max_elem_len = len;
1228     }
1229   indices_len = NUMBER_LEN (list_len);
1230   max_elem_len += indices_len + RP_SPACE_LEN + 2;
1231
1232   while (1)
1233     {
1234       print_select_list (list, list_len, max_elem_len, indices_len);
1235       printf ("%s", prompt);
1236       fflush (stdout);
1237       QUIT;
1238
1239       if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1240         {
1241           putchar ('\n');
1242           return ((char *)NULL);
1243         }
1244       repl_string = get_string_value ("REPLY");
1245       if (*repl_string == 0)
1246         continue;
1247       reply = atoi (repl_string);
1248       if (reply < 1 || reply > list_len)
1249         return "";
1250
1251       l = list;
1252       while (l && --reply)
1253         l = l->next;
1254       return (l->word->word);
1255     }
1256 }
1257
1258 /* Execute a SELECT command.  The syntax is:
1259    SELECT word IN list DO command_list DONE
1260    Only `break' or `return' in command_list will terminate
1261    the command. */
1262 execute_select_command (select_command)
1263      SELECT_COM *select_command;
1264 {
1265   WORD_LIST *releaser, *list;
1266   char *identifier, *ps3_prompt, *selection;
1267   int retval, list_len, return_val;
1268 #if 0
1269   SHELL_VAR *old_value = (SHELL_VAR *)0;
1270 #endif
1271
1272
1273   retval = EXECUTION_SUCCESS;
1274
1275   if (check_identifier (select_command->name, 1) == 0)
1276     return (EXECUTION_FAILURE);
1277
1278   loop_level++;
1279   identifier = select_command->name->word;
1280
1281   /* command and arithmetic substitution, parameter and variable expansion,
1282      word splitting, pathname expansion, and quote removal. */
1283   list = releaser = expand_words_no_vars (select_command->map_list);
1284   list_len = list_length (list);
1285   if (list == 0 || list_len == 0)
1286     {
1287       if (list)
1288         dispose_words (list);
1289       return (EXECUTION_SUCCESS);
1290     }
1291
1292   begin_unwind_frame ("select");
1293   add_unwind_protect (dispose_words, releaser);
1294
1295 #if 0
1296   if (lexical_scoping)
1297     {
1298       old_value = copy_variable (find_variable (identifier));
1299       if (old_value)
1300         add_unwind_protect (dispose_variable, old_value);
1301     }
1302 #endif
1303
1304   if (select_command->flags & CMD_IGNORE_RETURN)
1305     select_command->action->flags |= CMD_IGNORE_RETURN;
1306
1307   unwind_protect_int (return_catch_flag);
1308   unwind_protect_jmp_buf (return_catch);
1309   return_catch_flag++;
1310
1311   while (1)
1312     {
1313       ps3_prompt = get_string_value ("PS3");
1314       if (!ps3_prompt)
1315         ps3_prompt = "#? ";
1316
1317       QUIT;
1318       selection = select_query (list, list_len, ps3_prompt);
1319       QUIT;
1320       if (selection == 0)
1321         break;
1322       else
1323         bind_variable (identifier, selection);
1324
1325       return_val = setjmp (return_catch);
1326
1327       if (return_val)
1328         {
1329           retval = return_catch_value;
1330           break;
1331         }
1332       else
1333         retval = execute_command (select_command->action);
1334
1335       REAP ();
1336       QUIT;
1337
1338       if (breaking)
1339         {
1340           breaking--;
1341           break;
1342         }
1343     }
1344
1345   loop_level--;
1346
1347 #if 0
1348   if (lexical_scoping)
1349     {
1350       if (!old_value)
1351         makunbound (identifier, shell_variables);
1352       else
1353         {
1354           SHELL_VAR *new_value;
1355
1356           new_value = bind_variable (identifier, value_cell(old_value));
1357           new_value->attributes = old_value->attributes;
1358           dispose_variable (old_value);
1359         }
1360     }
1361 #endif
1362
1363   run_unwind_frame ("select");
1364   return (retval);
1365 }
1366 #endif /* SELECT_COMMAND */
1367
1368 /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
1369    The pattern_list is a linked list of pattern clauses; each clause contains
1370    some patterns to compare word_desc against, and an associated command to
1371    execute. */
1372 execute_case_command (case_command)
1373      CASE_COM *case_command;
1374 {
1375   register WORD_LIST *list;
1376   WORD_LIST *wlist;
1377   PATTERN_LIST *clauses;
1378   char *word;
1379   int retval;
1380
1381   /* Posix.2 specifies that the WORD is tilde expanded. */
1382   if (member ('~', case_command->word->word))
1383     {
1384       word = tilde_expand (case_command->word->word);
1385       free (case_command->word->word);
1386       case_command->word->word = word;
1387     }
1388
1389   wlist = expand_word_no_split (case_command->word, 0);
1390   clauses = case_command->clauses;
1391   word = (wlist) ? string_list (wlist) : savestring ("");
1392   retval = EXECUTION_SUCCESS;
1393
1394   begin_unwind_frame ("case");
1395   add_unwind_protect (dispose_words, wlist);
1396   add_unwind_protect ((Function *)xfree, word);
1397
1398   while (clauses)
1399     {
1400       QUIT;
1401       list = clauses->patterns;
1402       while (list)
1403         {
1404           char *pattern;
1405           WORD_LIST *es;
1406           int match;
1407
1408           /* Posix.2 specifies to tilde expand each member of the pattern
1409              list. */
1410           if (member ('~', list->word->word))
1411             {
1412               char *expansion = tilde_expand (list->word->word);
1413               free (list->word->word);
1414               list->word->word = expansion;
1415             }
1416
1417           es = expand_word_leave_quoted (list->word, 0);
1418
1419           if (es && es->word && es->word->word && *(es->word->word))
1420             pattern = quote_string_for_globbing (es->word->word, 1);
1421           else
1422             pattern = savestring ("");
1423
1424           /* Since the pattern does not undergo quote removal (as per
1425              Posix.2, section 3.9.4.3), the fnmatch () call must be able
1426              to recognize backslashes as escape characters. */
1427           match = (fnmatch (pattern, word, 0) != FNM_NOMATCH);
1428           free (pattern);
1429
1430           dispose_words (es);
1431
1432           if (match)
1433             {
1434               if (clauses->action && 
1435                   (case_command->flags & CMD_IGNORE_RETURN))
1436                 clauses->action->flags |= CMD_IGNORE_RETURN;
1437               execute_command (clauses->action);
1438               retval = last_command_exit_value;
1439               goto exit_command;
1440             }
1441
1442           list = list->next;
1443           QUIT;
1444         }
1445
1446       clauses = clauses->next;
1447     }
1448
1449  exit_command:
1450   dispose_words (wlist);
1451   free (word);  
1452   discard_unwind_frame ("case");
1453
1454   return (retval);
1455 }
1456
1457 #define CMD_WHILE 0
1458 #define CMD_UNTIL 1
1459
1460 /* The WHILE command.  Syntax: WHILE test DO action; DONE.
1461    Repeatedly execute action while executing test produces
1462    EXECUTION_SUCCESS. */
1463 execute_while_command (while_command)
1464      WHILE_COM *while_command;
1465 {
1466   return (execute_while_or_until (while_command, CMD_WHILE));
1467 }
1468
1469 /* UNTIL is just like WHILE except that the test result is negated. */
1470 execute_until_command (while_command)
1471      WHILE_COM *while_command;
1472 {
1473   return (execute_while_or_until (while_command, CMD_UNTIL));
1474 }
1475
1476 /* The body for both while and until.  The only difference between the
1477    two is that the test value is treated differently.  TYPE is
1478    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
1479    be EXECUTION_SUCCESS if no commands in the body are executed, and
1480    the status of the last command executed in the body otherwise. */
1481 execute_while_or_until (while_command, type)
1482      WHILE_COM *while_command;
1483      int type;
1484 {
1485   int return_value, body_status;
1486
1487   body_status = EXECUTION_SUCCESS;
1488   loop_level++;
1489
1490   while_command->test->flags |= CMD_IGNORE_RETURN;
1491   if (while_command->flags & CMD_IGNORE_RETURN)
1492     while_command->action->flags |= CMD_IGNORE_RETURN;
1493
1494   while (1)
1495     {
1496       return_value = execute_command (while_command->test);
1497       REAP ();
1498
1499       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
1500         break;
1501       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
1502         break;
1503
1504       QUIT;
1505       body_status = execute_command (while_command->action);
1506       QUIT;
1507
1508       if (breaking)
1509         {
1510           breaking--;
1511           break;
1512         }
1513
1514       if (continuing)
1515         {
1516           continuing--;
1517           if (continuing)
1518             break;
1519         }
1520     }
1521   loop_level--;
1522
1523   return (body_status);
1524 }
1525
1526 /* IF test THEN command [ELSE command].
1527    IF also allows ELIF in the place of ELSE IF, but
1528    the parser makes *that* stupidity transparent. */
1529 execute_if_command (if_command)
1530      IF_COM *if_command;
1531 {
1532   int return_value;
1533
1534   if_command->test->flags |= CMD_IGNORE_RETURN;
1535   return_value = execute_command (if_command->test);
1536
1537   if (return_value == EXECUTION_SUCCESS)
1538     {
1539       QUIT;
1540       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
1541           if_command->true_case->flags |= CMD_IGNORE_RETURN;
1542       return (execute_command (if_command->true_case));
1543     }
1544   else
1545     {
1546       QUIT;
1547
1548       if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
1549         if_command->false_case->flags |= CMD_IGNORE_RETURN;
1550
1551       return (execute_command (if_command->false_case));
1552     }
1553 }
1554
1555 static void
1556 bind_lastarg (arg)
1557      char *arg;
1558 {
1559   SHELL_VAR *var;
1560
1561   if (!arg)
1562     arg = "";
1563   var = bind_variable ("_", arg);
1564   var->attributes &= ~att_exported;
1565 }
1566
1567 /* The meaty part of all the executions.  We have to start hacking the
1568    real execution of commands here.  Fork a process, set things up,
1569    execute the command. */
1570 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
1571      SIMPLE_COM *simple_command;
1572      int pipe_in, pipe_out, async;
1573      struct fd_bitmap *fds_to_close;
1574 {
1575   WORD_LIST *words, *lastword;
1576   char *command_line, *lastarg;
1577   int first_word_quoted, result;
1578   pid_t old_last_command_subst_pid;
1579
1580   result = EXECUTION_SUCCESS;
1581
1582   /* If we're in a function, update the pseudo-line-number information. */
1583   if (variable_context)
1584     line_number = simple_command->line - function_line_number;
1585
1586   /* Remember what this command line looks like at invocation. */
1587   command_string_index = 0;
1588   print_simple_command (simple_command);
1589   command_line = (char *)alloca (1 + strlen (the_printed_command));
1590   strcpy (command_line, the_printed_command);
1591
1592   first_word_quoted =
1593     simple_command->words ? simple_command->words->word->quoted : 0;
1594
1595   old_last_command_subst_pid = last_command_subst_pid;
1596
1597   /* If we are re-running this as the result of executing the `command'
1598      builtin, do not expand the command words a second time. */
1599   if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
1600     {
1601       current_fds_to_close = fds_to_close;
1602       words = expand_words (simple_command->words);
1603       current_fds_to_close = (struct fd_bitmap *)NULL;
1604     }
1605   else
1606     words = copy_word_list (simple_command->words);
1607
1608   lastarg = (char *)NULL;
1609
1610   /* It is possible for WORDS not to have anything left in it.
1611      Perhaps all the words consisted of `$foo', and there was
1612      no variable `$foo'. */
1613   if (words)
1614     {
1615       Function *builtin;
1616       SHELL_VAR *func;
1617
1618       begin_unwind_frame ("simple-command");
1619
1620       if (echo_command_at_execute)
1621         {
1622           char *line = string_list (words);
1623
1624           if (line && *line)
1625             fprintf (stderr, "%s%s\n", indirection_level_string (), line);
1626
1627           FREE (line);
1628         }
1629
1630       if (simple_command->flags & CMD_NO_FUNCTIONS)
1631         func = (SHELL_VAR *)NULL;
1632       else
1633         func = find_function (words->word->word);
1634
1635       add_unwind_protect (dispose_words, words);
1636
1637       QUIT;
1638
1639       /* Bind the last word in this command to "$_" after execution. */
1640       for (lastword = words; lastword->next; lastword = lastword->next);
1641       lastarg = lastword->word->word;
1642
1643 #if defined (JOB_CONTROL)
1644       /* Is this command a job control related thing? */
1645       if (words->word->word[0] == '%')
1646         {
1647           int result;
1648
1649           if (async)
1650             this_command_name = "bg";
1651           else
1652             this_command_name = "fg";
1653
1654           last_shell_builtin = this_shell_builtin;
1655           this_shell_builtin = builtin_address (this_command_name);
1656           result = (*this_shell_builtin) (words);
1657           goto return_result;
1658         }
1659
1660       /* One other possiblilty.  The user may want to resume an existing job.
1661          If they do, find out whether this word is a candidate for a running
1662          job. */
1663       {
1664         char *auto_resume_value = get_string_value ("auto_resume");
1665
1666         if (auto_resume_value &&
1667             !first_word_quoted &&
1668             !words->next &&
1669             words->word->word[0] &&
1670             !simple_command->redirects &&
1671             pipe_in == NO_PIPE &&
1672             pipe_out == NO_PIPE &&
1673             !async)
1674           {
1675             char *word = words->word->word;
1676             register int i;
1677             int wl, cl, exact, substring, match, started_status;
1678             register PROCESS *p;
1679
1680             exact = STREQ (auto_resume_value, "exact");
1681             substring = STREQ (auto_resume_value, "substring");
1682             wl = strlen (word);
1683             for (i = job_slots - 1; i > -1; i--)
1684               {
1685                 if (!jobs[i] || (JOBSTATE (i) != JSTOPPED))
1686                   continue;
1687
1688                 p = jobs[i]->pipe;
1689                 do
1690                   {
1691                     if (exact)
1692                       {
1693                         cl = strlen (p->command);
1694                         match = STREQN (p->command, word, cl);
1695                       }
1696                     else if (substring)
1697                       match = strindex (p->command, word) != (char *)0;
1698                     else
1699                       match = STREQN (p->command, word, wl);
1700
1701                     if (match == 0)
1702                       {
1703                         p = p->next;
1704                         continue;
1705                       }
1706
1707                     run_unwind_frame ("simple-command");
1708                     last_shell_builtin = this_shell_builtin;
1709                     this_shell_builtin = builtin_address ("fg");
1710
1711                     started_status = start_job (i, 1);
1712
1713                     if (started_status < 0)
1714                       return (EXECUTION_FAILURE);
1715                     else
1716                       return (started_status);
1717                   }
1718                 while (p != jobs[i]->pipe);
1719               }
1720           }
1721       }
1722 #endif /* JOB_CONTROL */
1723
1724       /* Remember the name of this command globally. */
1725       this_command_name = words->word->word;
1726
1727       QUIT;
1728
1729       /* This command could be a shell builtin or a user-defined function.
1730          If so, and we have pipes, then fork a subshell in here.  Else, just
1731          do the command. */
1732
1733       if (func)
1734         builtin = (Function *)NULL;
1735       else
1736         builtin = find_shell_builtin (this_command_name);
1737
1738       last_shell_builtin = this_shell_builtin;
1739       this_shell_builtin = builtin;
1740
1741       if (builtin || func)
1742         {
1743           if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
1744             {
1745               if (make_child (savestring (command_line), async) == 0)
1746                 {
1747                   /* Cancel traps, in trap.c. */
1748                   restore_original_signals ();
1749
1750                   if (async)
1751                     setup_async_signals ();
1752
1753                   execute_subshell_builtin_or_function
1754                     (words, simple_command->redirects, builtin, func,
1755                      pipe_in, pipe_out, async, fds_to_close,
1756                      simple_command->flags);
1757                 }
1758               else
1759                 {
1760                   close_pipes (pipe_in, pipe_out);
1761 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1762                   unlink_fifo_list ();
1763 #endif
1764                   goto return_result;
1765                 }
1766             }
1767           else
1768             {
1769               result = execute_builtin_or_function
1770                 (words, builtin, func, simple_command->redirects, fds_to_close,
1771                  simple_command->flags);
1772
1773               goto return_result;
1774             }
1775         }
1776
1777       execute_disk_command (words, simple_command->redirects, command_line,
1778                             pipe_in, pipe_out, async, fds_to_close,
1779                             (simple_command->flags & CMD_NO_FORK));
1780
1781       goto return_result;
1782     }
1783   else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
1784     {
1785       /* We have a null command, but we really want a subshell to take
1786          care of it.  Just fork, do piping and redirections, and exit. */
1787       if (make_child (savestring (""), async) == 0)
1788         {
1789           /* Cancel traps, in trap.c. */
1790           restore_original_signals ();
1791
1792           do_piping (pipe_in, pipe_out);
1793
1794           subshell_environment = 1;
1795
1796           if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
1797             exit (EXECUTION_SUCCESS);
1798           else
1799             exit (EXECUTION_FAILURE);
1800         }
1801       else
1802         {
1803           close_pipes (pipe_in, pipe_out);
1804 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1805           unlink_fifo_list ();
1806 #endif
1807           result = EXECUTION_SUCCESS;
1808           goto return_result;
1809         }
1810     }
1811   else
1812     {
1813       /* Even if there aren't any command names, pretend to do the
1814          redirections that are specified.  The user expects the side
1815          effects to take place.  If the redirections fail, then return
1816          failure.  Otherwise, if a command substitution took place while
1817          expanding the command or a redirection, return the value of that
1818          substitution.  Otherwise, return EXECUTION_SUCCESS. */
1819
1820       if (do_redirections (simple_command->redirects, 0, 0, 0) != 0)
1821         result = EXECUTION_FAILURE;
1822       else if (old_last_command_subst_pid != last_command_subst_pid)
1823         result = last_command_exit_value;
1824       else
1825         result = EXECUTION_SUCCESS;
1826     }
1827
1828  return_result:
1829   bind_lastarg (lastarg);
1830   /* The unwind-protect frame is set up only if WORDS is not empty. */
1831   if (words)
1832     run_unwind_frame ("simple-command");
1833   return (result);
1834 }
1835
1836 static int
1837 execute_builtin (builtin, words, flags, subshell)
1838      Function *builtin;
1839      WORD_LIST *words;
1840      int flags, subshell;
1841 {
1842   int old_e_flag = exit_immediately_on_error;
1843   int result;
1844
1845   /* The eval builtin calls parse_and_execute, which does not know about
1846      the setting of flags, and always calls the execution functions with
1847      flags that will exit the shell on an error if -e is set.  If the
1848      eval builtin is being called, and we're supposed to ignore the exit
1849      value of the command, we turn the -e flag off ourselves, then
1850      restore it when the command completes. */
1851   if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
1852     {
1853       begin_unwind_frame ("eval_builtin");
1854       unwind_protect_int (exit_immediately_on_error);
1855       exit_immediately_on_error = 0;
1856     }
1857
1858   /* The temporary environment for a builtin is supposed to apply to
1859      all commands executed by that builtin.  Currently, this is a
1860      problem only with the `source' builtin. */
1861   if (builtin == source_builtin)
1862     {
1863       if (subshell == 0)
1864         begin_unwind_frame ("builtin_env");
1865
1866       if (temporary_env)
1867         {
1868           builtin_env = copy_array (temporary_env);
1869           if (subshell == 0)
1870             add_unwind_protect (dispose_builtin_env, (char *)NULL);
1871           dispose_used_env_vars ();
1872         }
1873 #if 0
1874       else
1875         builtin_env = (char **)NULL;
1876 #endif
1877     }
1878
1879   result = ((*builtin) (words->next));
1880
1881   if (subshell == 0 && builtin == source_builtin)
1882     {
1883       dispose_builtin_env ();
1884       discard_unwind_frame ("builtin_env");
1885     }
1886
1887   if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
1888     {
1889       exit_immediately_on_error += old_e_flag;
1890       discard_unwind_frame ("eval_builtin");
1891     }
1892
1893   return (result);
1894 }
1895
1896 /* XXX -- why do we need to set up unwind-protects for the case where
1897    subshell == 1 at all? */
1898 static int
1899 execute_function (var, words, flags, fds_to_close, async, subshell)
1900      SHELL_VAR *var;
1901      WORD_LIST *words;
1902      int flags, subshell, async;
1903      struct fd_bitmap *fds_to_close;
1904 {
1905   int return_val, result;
1906   COMMAND *tc, *fc;
1907
1908   tc = (COMMAND *)copy_command (function_cell (var));
1909   if (tc && (flags & CMD_IGNORE_RETURN))
1910     tc->flags |= CMD_IGNORE_RETURN;
1911
1912   if (subshell)
1913     begin_unwind_frame ("subshell_function_calling");
1914   else
1915     begin_unwind_frame ("function_calling");
1916
1917   if (subshell == 0)
1918     {
1919       push_context ();
1920       add_unwind_protect (pop_context, (char *)NULL);
1921       unwind_protect_int (line_number);
1922     }
1923   else
1924     unwind_protect_int (variable_context);
1925
1926   unwind_protect_int (loop_level);
1927   unwind_protect_int (return_catch_flag);
1928   unwind_protect_jmp_buf (return_catch);
1929   add_unwind_protect (dispose_command, (char *)tc);
1930
1931   /* The temporary environment for a function is supposed to apply to
1932      all commands executed within the function body. */
1933   if (temporary_env)
1934     {
1935       function_env = copy_array (temporary_env);
1936       add_unwind_protect (dispose_function_env, (char *)NULL);
1937       dispose_used_env_vars ();
1938     }
1939 #if 0
1940   else
1941     function_env = (char **)NULL;
1942 #endif
1943
1944   /* Note the second argument of "1", meaning that we discard
1945      the current value of "$*"!  This is apparently the right thing. */
1946   remember_args (words->next, 1);
1947
1948   line_number = function_line_number = tc->line;
1949
1950   if (subshell)
1951     {
1952 #if defined (JOB_CONTROL)
1953       stop_pipeline (async, (COMMAND *)NULL);
1954 #endif
1955       if (tc->type == cm_group)
1956         fc = tc->value.Group->command;
1957       else
1958         fc = tc;
1959
1960       if (fc && (flags & CMD_IGNORE_RETURN))
1961         fc->flags |= CMD_IGNORE_RETURN;
1962
1963       variable_context++;
1964     }
1965   else
1966     fc = tc;
1967
1968   return_catch_flag++;
1969   return_val = setjmp (return_catch);
1970
1971   if (return_val)
1972     result = return_catch_value;
1973   else
1974     result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
1975
1976   if (subshell)
1977     run_unwind_frame ("subshell_function_calling");
1978   else
1979     run_unwind_frame ("function_calling");
1980
1981   return (result);
1982 }
1983
1984 /* Execute a shell builtin or function in a subshell environment.  This
1985    routine does not return; it only calls exit().  If BUILTIN is non-null,
1986    it points to a function to call to execute a shell builtin; otherwise
1987    VAR points at the body of a function to execute.  WORDS is the arguments
1988    to the command, REDIRECTS specifies redirections to perform before the
1989    command is executed. */
1990 static void
1991 execute_subshell_builtin_or_function (words, redirects, builtin, var,
1992                                       pipe_in, pipe_out, async, fds_to_close,
1993                                       flags)
1994      WORD_LIST *words;
1995      REDIRECT *redirects;
1996      Function *builtin;
1997      SHELL_VAR *var;
1998      int pipe_in, pipe_out, async;
1999      struct fd_bitmap *fds_to_close;
2000      int flags;
2001 {
2002   /* A subshell is neither a login shell nor interactive. */
2003   login_shell = interactive = 0;
2004
2005   subshell_environment = 1;
2006
2007   maybe_make_export_env ();
2008
2009 #if defined (JOB_CONTROL)
2010   /* Eradicate all traces of job control after we fork the subshell, so
2011      all jobs begun by this subshell are in the same process group as
2012      the shell itself. */
2013
2014   /* Allow the output of `jobs' to be piped. */
2015   if (builtin == jobs_builtin && !async &&
2016       (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
2017     kill_current_pipeline ();
2018   else
2019     without_job_control ();
2020
2021   set_sigchld_handler ();
2022 #endif /* JOB_CONTROL */
2023
2024   set_sigint_handler ();
2025
2026   do_piping (pipe_in, pipe_out);
2027
2028   if (fds_to_close)
2029     close_fd_bitmap (fds_to_close);
2030
2031   if (do_redirections (redirects, 1, 0, 0) != 0)
2032     exit (EXECUTION_FAILURE);
2033
2034   if (builtin)
2035     {
2036       int result;
2037
2038       /* Give builtins a place to jump back to on failure,
2039          so we don't go back up to main(). */
2040       result = setjmp (top_level);
2041
2042       if (result == EXITPROG)
2043         exit (last_command_exit_value);
2044       else if (result)
2045         exit (EXECUTION_FAILURE);
2046       else
2047         exit (execute_builtin (builtin, words, flags, 1));
2048     }
2049   else
2050     {
2051       exit (execute_function (var, words, flags, fds_to_close, async, 1));
2052     }
2053 }
2054
2055 /* Execute a builtin or function in the current shell context.  If BUILTIN
2056    is non-null, it is the builtin command to execute, otherwise VAR points
2057    to the body of a function.  WORDS are the command's arguments, REDIRECTS
2058    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
2059    file descriptors to close.
2060
2061    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2062    not undone before this function returns. */
2063 static int
2064 execute_builtin_or_function (words, builtin, var, redirects,
2065                              fds_to_close, flags)
2066      WORD_LIST *words;
2067      Function *builtin;
2068      SHELL_VAR *var;
2069      REDIRECT *redirects;
2070      struct fd_bitmap *fds_to_close;
2071      int flags;
2072 {
2073   int result = EXECUTION_FAILURE;
2074   REDIRECT *saved_undo_list;
2075
2076   if (do_redirections (redirects, 1, 1, 0) != 0)
2077     {
2078       cleanup_redirects (redirection_undo_list);
2079       redirection_undo_list = (REDIRECT *)NULL;
2080       dispose_exec_redirects ();
2081       return (EXECUTION_FAILURE);
2082     }
2083
2084   saved_undo_list = redirection_undo_list;
2085
2086   /* Calling the "exec" builtin changes redirections forever. */
2087   if (builtin == exec_builtin)
2088     {
2089       dispose_redirects (saved_undo_list);
2090       saved_undo_list = exec_redirection_undo_list;
2091       exec_redirection_undo_list = (REDIRECT *)NULL;
2092     }
2093   else
2094     dispose_exec_redirects ();
2095
2096   if (saved_undo_list)
2097     {
2098       begin_unwind_frame ("saved redirects");
2099       add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
2100       add_unwind_protect (dispose_redirects, (char *)saved_undo_list);
2101     }
2102
2103   redirection_undo_list = (REDIRECT *)NULL;
2104
2105   if (builtin)
2106     result = execute_builtin (builtin, words, flags, 0);
2107   else
2108     result = execute_function (var, words, flags, fds_to_close, 0, 0);
2109
2110   if (saved_undo_list)
2111     {
2112       redirection_undo_list = saved_undo_list;
2113       discard_unwind_frame ("saved redirects");
2114     }
2115
2116   if (redirection_undo_list)
2117     {
2118       do_redirections (redirection_undo_list, 1, 0, 0);
2119       dispose_redirects (redirection_undo_list);
2120       redirection_undo_list = (REDIRECT *)NULL;
2121     }
2122
2123   return (result);
2124 }
2125
2126 void
2127 setup_async_signals ()
2128 {
2129 #if defined (JOB_CONTROL)
2130   if (job_control == 0)
2131 #endif
2132     {
2133       set_signal_handler (SIGINT, SIG_IGN);
2134       set_signal_ignored (SIGINT);
2135       set_signal_handler (SIGQUIT, SIG_IGN);
2136       set_signal_ignored (SIGQUIT);
2137     }
2138 }
2139
2140 /* Execute a simple command that is hopefully defined in a disk file
2141    somewhere.
2142
2143    1) fork ()
2144    2) connect pipes
2145    3) look up the command
2146    4) do redirections
2147    5) execve ()
2148    6) If the execve failed, see if the file has executable mode set.
2149    If so, and it isn't a directory, then execute its contents as
2150    a shell script.
2151
2152    Note that the filename hashing stuff has to take place up here,
2153    in the parent.  This is probably why the Bourne style shells
2154    don't handle it, since that would require them to go through
2155    this gnarly hair, for no good reason.  */
2156 static void
2157 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
2158                       async, fds_to_close, nofork)
2159      WORD_LIST *words;
2160      REDIRECT *redirects;
2161      char *command_line;
2162      int pipe_in, pipe_out, async;
2163      struct fd_bitmap *fds_to_close;
2164      int nofork;        /* Don't fork, just exec, if no pipes */
2165 {
2166   register char *pathname;
2167   char *hashed_file, *command, **args;
2168   int pid, temp_path;
2169   SHELL_VAR *path;
2170
2171   pathname = words->word->word;
2172 #if defined (RESTRICTED_SHELL)
2173   if (restricted && strchr (pathname, '/'))
2174     {
2175       report_error ("%s: restricted: cannot specify `/' in command names",
2176                     pathname);
2177       last_command_exit_value = EXECUTION_FAILURE;
2178       return;
2179     }
2180 #endif /* RESTRICTED_SHELL */
2181
2182   hashed_file = command = (char *)NULL;
2183
2184   /* If PATH is in the temporary environment for this command, don't use the
2185      hash table to search for the full pathname. */
2186   temp_path = 0;
2187   path = find_tempenv_variable ("PATH");
2188   if (path)
2189     temp_path = 1;
2190
2191   /* Don't waste time trying to find hashed data for a pathname
2192      that is already completely specified. */
2193
2194   if (!path && !absolute_program (pathname))
2195     hashed_file = find_hashed_filename (pathname);
2196
2197   /* If a command found in the hash table no longer exists, we need to
2198      look for it in $PATH.  Thank you Posix.2.  This forces us to stat
2199      every command found in the hash table.  It seems pretty stupid to me,
2200      so I am basing it on the presence of POSIXLY_CORRECT. */
2201
2202   if (hashed_file && posixly_correct)
2203     {
2204       int st;
2205
2206       st = file_status (hashed_file);
2207       if ((st ^ (FS_EXISTS | FS_EXECABLE)) != 0)
2208         {
2209           remove_hashed_filename (pathname);
2210           hashed_file = (char *)NULL;
2211         }
2212     }
2213
2214   if (hashed_file)
2215     command = savestring (hashed_file);
2216   else if (absolute_program (pathname))
2217     /* A command containing a slash is not looked up in PATH or saved in
2218        the hash table. */
2219     command = savestring (pathname);
2220   else
2221     {
2222       command = find_user_command (pathname);
2223       if (command && !hashing_disabled && !temp_path)
2224         remember_filename (pathname, command, dot_found_in_search, 1);
2225     }
2226
2227   maybe_make_export_env ();
2228
2229   if (command)
2230     put_command_name_into_env (command);
2231
2232   /* We have to make the child before we check for the non-existance
2233      of COMMAND, since we want the error messages to be redirected. */
2234   /* If we can get away without forking and there are no pipes to deal with,
2235      don't bother to fork, just directly exec the command. */
2236   if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
2237     pid = 0;
2238   else
2239     pid = make_child (savestring (command_line), async);
2240
2241   if (pid == 0)
2242     {
2243       int old_interactive;
2244
2245       /* Cancel traps, in trap.c. */
2246       restore_original_signals ();
2247
2248       /* restore_original_signals may have undone the work done
2249          by make_child to ensure that SIGINT and SIGQUIT are ignored
2250          in asynchronous children. */
2251       if (async)
2252         setup_async_signals ();
2253
2254       do_piping (pipe_in, pipe_out);
2255
2256       /* Execve expects the command name to be in args[0].  So we
2257          leave it there, in the same format that the user used to
2258          type it in. */
2259       args = make_word_array (words);
2260
2261       if (async)
2262         {
2263           old_interactive = interactive;
2264           interactive = 0;
2265         }
2266
2267       subshell_environment = 1;
2268
2269       /* This functionality is now provided by close-on-exec of the
2270          file descriptors manipulated by redirection and piping.
2271          Some file descriptors still need to be closed in all children
2272          because of the way bash does pipes; fds_to_close is a 
2273          bitmap of all such file descriptors. */
2274       if (fds_to_close)
2275         close_fd_bitmap (fds_to_close);
2276
2277       if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
2278         {
2279 #if defined (PROCESS_SUBSTITUTION)
2280           /* Try to remove named pipes that may have been created as the
2281              result of redirections. */
2282           unlink_fifo_list ();
2283 #endif /* PROCESS_SUBSTITUTION */
2284           exit (EXECUTION_FAILURE);
2285         }
2286
2287       if (async)
2288         interactive = old_interactive;
2289
2290       if (!command)
2291         {
2292           report_error ("%s: command not found", args[0]);
2293           exit (EX_NOTFOUND);   /* Posix.2 says the exit status is 127 */
2294         }
2295
2296       exit (shell_execve (command, args, export_env));
2297     }
2298   else
2299     {
2300       /* Make sure that the pipes are closed in the parent. */
2301       close_pipes (pipe_in, pipe_out);
2302 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2303       unlink_fifo_list ();
2304 #endif
2305       FREE (command);
2306     }
2307 }
2308
2309 /* If the operating system on which we're running does not handle
2310    the #! executable format, then help out.  SAMPLE is the text read
2311    from the file, SAMPLE_LEN characters.  COMMAND is the name of
2312    the script; it and ARGS, the arguments given by the user, will
2313    become arguments to the specified interpreter.  ENV is the environment
2314    to pass to the interpreter.
2315
2316    The word immediately following the #! is the interpreter to execute.
2317    A single argument to the interpreter is allowed. */
2318 static int
2319 execute_shell_script (sample, sample_len, command, args, env)
2320      unsigned char *sample;
2321      int sample_len;
2322      char *command;
2323      char **args, **env;
2324 {
2325   register int i;
2326   char *execname, *firstarg;
2327   int start, size_increment, larry;
2328
2329   /* Find the name of the interpreter to exec. */
2330   for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
2331     ;
2332
2333   for (start = i;
2334        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2335        i++)
2336     ;
2337
2338   execname = xmalloc (1 + (i - start));
2339   strncpy (execname, (char *) (sample + start), i - start);
2340   execname[i - start] = '\0';
2341   size_increment = 1;
2342
2343   /* Now the argument, if any. */
2344   firstarg = (char *)NULL;
2345   for (start = i;
2346        whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2347        i++)
2348     ;
2349
2350   /* If there is more text on the line, then it is an argument for the
2351      interpreter. */
2352   if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
2353     {
2354       for (start = i;
2355            !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2356            i++)
2357         ;
2358       firstarg = xmalloc (1 + (i - start));
2359       strncpy (firstarg, (char *)(sample + start), i - start);
2360       firstarg[i - start] = '\0';
2361
2362       size_increment = 2;
2363     }
2364
2365   larry = array_len (args) + size_increment;
2366
2367   args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
2368
2369   for (i = larry - 1; i; i--)
2370     args[i] = args[i - size_increment];
2371
2372   args[0] = execname;
2373   if (firstarg)
2374     {
2375       args[1] = firstarg;
2376       args[2] = command;
2377     }
2378   else
2379     args[1] = command;
2380
2381   args[larry] = (char *)NULL;
2382
2383   return (shell_execve (execname, args, env));
2384 }
2385
2386 /* Call execve (), handling interpreting shell scripts, and handling
2387    exec failures. */
2388 int
2389 shell_execve (command, args, env)
2390      char *command;
2391      char **args, **env;
2392 {
2393 #if defined (isc386) && defined (_POSIX_SOURCE)
2394   __setostype (0);              /* Turn on USGr3 semantics. */
2395   execve (command, args, env);
2396   __setostype (1);              /* Turn the POSIX semantics back on. */
2397 #else
2398   execve (command, args, env);
2399 #endif /* !(isc386 && _POSIX_SOURCE) */
2400
2401   /* If we get to this point, then start checking out the file.
2402      Maybe it is something we can hack ourselves. */
2403   {
2404     struct stat finfo;
2405
2406     if (errno != ENOEXEC)
2407       {
2408         if ((stat (command, &finfo) == 0) &&
2409             (S_ISDIR (finfo.st_mode)))
2410           report_error ("%s: is a directory", args[0]);
2411         else
2412           file_error (command);
2413
2414         return (EX_NOEXEC);     /* XXX Posix.2 says that exit status is 126 */
2415       }
2416     else
2417       {
2418         /* This file is executable.
2419            If it begins with #!, then help out people with losing operating
2420            systems.  Otherwise, check to see if it is a binary file by seeing
2421            if the first line (or up to 30 characters) are in the ASCII set.
2422            Execute the contents as shell commands. */
2423         int larray = array_len (args) + 1;
2424         int i, should_exec = 0;
2425
2426         {
2427           int fd = open (command, O_RDONLY);
2428           if (fd != -1)
2429             {
2430               unsigned char sample[80];
2431               int sample_len = read (fd, &sample[0], 80);
2432
2433               close (fd);
2434
2435               if (sample_len == 0)
2436                 return (EXECUTION_SUCCESS);
2437
2438               /* Is this supposed to be an executable script?
2439                  If so, the format of the line is "#! interpreter [argument]".
2440                  A single argument is allowed.  The BSD kernel restricts
2441                  the length of the entire line to 32 characters (32 bytes
2442                  being the size of the BSD exec header), but we allow 80
2443                  characters. */
2444
2445               if (sample_len > 0 && sample[0] == '#' && sample[1] == '!')
2446                 return (execute_shell_script
2447                         (sample, sample_len, command, args, env));
2448               else if ((sample_len != -1) &&
2449                        check_binary_file (sample, sample_len))
2450                 {
2451                   report_error ("%s: cannot execute binary file", command);
2452                   return (EX_BINARY_FILE);
2453                 }
2454             }
2455         }
2456 #if defined (JOB_CONTROL)
2457         /* Forget about the way that job control was working. We are
2458            in a subshell. */
2459         without_job_control ();
2460 #endif /* JOB_CONTROL */
2461 #if defined (ALIAS)
2462         /* Forget about any aliases that we knew of.  We are in a subshell. */
2463         delete_all_aliases ();
2464 #endif /* ALIAS */
2465
2466 #if defined (JOB_CONTROL)
2467         set_sigchld_handler ();
2468 #endif /* JOB_CONTROL */
2469         set_sigint_handler ();
2470
2471         /* Insert the name of this shell into the argument list. */
2472         args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
2473
2474         for (i = larray - 1; i; i--)
2475           args[i] = args[i - 1];
2476
2477         args[0] = shell_name;
2478         args[1] = command;
2479         args[larray] = (char *)NULL;
2480
2481         if (args[0][0] == '-')
2482           args[0]++;
2483
2484         if (should_exec)
2485           {
2486             struct stat finfo;
2487
2488 #if defined (isc386) && defined (_POSIX_SOURCE)
2489             __setostype (0);    /* Turn on USGr3 semantics. */
2490             execve (shell_name, args, env);
2491             __setostype (1);    /* Turn the POSIX semantics back on. */
2492 #else
2493             execve (shell_name, args, env);
2494 #endif /* isc386 && _POSIX_SOURCE */
2495
2496             /* Oh, no!  We couldn't even exec this! */
2497             if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
2498               report_error ("%s: is a directory", args[0]);
2499             else
2500               file_error (args[0]);
2501
2502             return (EXECUTION_FAILURE);
2503           }
2504         else
2505           {
2506             subshell_argc = larray;
2507             subshell_argv = args;
2508             subshell_envp = env;
2509             longjmp (subshell_top_level, 1);
2510           }
2511       }
2512   }
2513 }
2514
2515 #if defined (PROCESS_SUBSTITUTION)
2516 /* Currently unused */
2517 void
2518 close_all_files ()
2519 {
2520   register int i, fd_table_size;
2521
2522   fd_table_size = getdtablesize ();
2523   if (fd_table_size > 256)      /* clamp to a reasonable value */
2524         fd_table_size = 256;
2525
2526   for (i = 3; i < fd_table_size; i++)
2527     close (i);
2528 }
2529 #endif /* PROCESS_SUBSTITUTION */
2530
2531 static void
2532 close_pipes (in, out)
2533      int in, out;
2534 {
2535   if (in >= 0)
2536     close (in);
2537   if (out >= 0)
2538     close (out);
2539 }
2540
2541 /* Redirect input and output to be from and to the specified pipes.
2542    NO_PIPE and REDIRECT_BOTH are handled correctly. */
2543 static void
2544 do_piping (pipe_in, pipe_out)
2545      int pipe_in, pipe_out;
2546 {
2547   if (pipe_in != NO_PIPE)
2548     {
2549       if (dup2 (pipe_in, 0) < 0)
2550         internal_error ("cannot duplicate fd %d to fd 0: %s",
2551                         pipe_in, strerror (errno));
2552       if (pipe_in > 0)
2553         close (pipe_in);
2554     }
2555   if (pipe_out != NO_PIPE)
2556     {
2557       if (pipe_out != REDIRECT_BOTH)
2558         {
2559           if (dup2 (pipe_out, 1) < 0)
2560             internal_error ("cannot duplicate fd %d to fd 1: %s",
2561                             pipe_out, strerror (errno));
2562           if (pipe_out == 0 || pipe_out > 1)
2563             close (pipe_out);
2564         }
2565       else
2566         dup2 (1, 2);
2567     }
2568 }
2569
2570 #define AMBIGUOUS_REDIRECT  -1
2571 #define NOCLOBBER_REDIRECT  -2
2572 #define RESTRICTED_REDIRECT -3  /* Only can happen in restricted shells. */
2573
2574 /* Perform the redirections on LIST.  If FOR_REAL, then actually make
2575    input and output file descriptors, otherwise just do whatever is
2576    neccessary for side effecting.  INTERNAL says to remember how to
2577    undo the redirections later, if non-zero.  If SET_CLEXEC is non-zero,
2578    file descriptors opened in do_redirection () have their close-on-exec
2579    flag set. */
2580 static int
2581 do_redirections (list, for_real, internal, set_clexec)
2582      REDIRECT *list;
2583      int for_real, internal, set_clexec;
2584 {
2585   register int error;
2586   register REDIRECT *temp = list;
2587
2588   if (internal)
2589     {
2590       if (redirection_undo_list)
2591         {
2592           dispose_redirects (redirection_undo_list);
2593           redirection_undo_list = (REDIRECT *)NULL;
2594         }
2595       if (exec_redirection_undo_list)
2596         dispose_exec_redirects ();
2597     }
2598
2599   while (temp)
2600     {
2601       error = do_redirection_internal (temp, for_real, internal, set_clexec);
2602
2603       if (error)
2604         {
2605           char *filename;
2606
2607           if (expandable_redirection_filename (temp))
2608             {
2609               if (posixly_correct && !interactive_shell)
2610                 disallow_filename_globbing++;
2611               filename = redirection_expand (temp->redirectee.filename);
2612               if (posixly_correct && !interactive_shell)
2613                 disallow_filename_globbing--;
2614
2615               if (!filename)
2616                 filename = savestring ("");
2617             }
2618           else
2619             filename = itos (temp->redirectee.dest);
2620
2621           switch (error)
2622             {
2623             case AMBIGUOUS_REDIRECT:
2624               report_error ("%s: Ambiguous redirect", filename);
2625               break;
2626
2627             case NOCLOBBER_REDIRECT:
2628               report_error ("%s: Cannot clobber existing file", filename);
2629               break;
2630
2631 #if defined (RESTRICTED_SHELL)
2632             case RESTRICTED_REDIRECT:
2633               report_error ("%s: output redirection restricted", filename);
2634               break;
2635 #endif /* RESTRICTED_SHELL */
2636
2637             default:
2638               report_error ("%s: %s", filename, strerror (error));
2639               break;
2640             }
2641
2642           free (filename);
2643           return (error);
2644         }
2645
2646       temp = temp->next;
2647     }
2648   return (0);
2649 }
2650
2651 /* Return non-zero if the redirection pointed to by REDIRECT has a
2652    redirectee.filename that can be expanded. */
2653 static int
2654 expandable_redirection_filename (redirect)
2655      REDIRECT *redirect;
2656 {
2657   int result;
2658
2659   switch (redirect->instruction)
2660     {
2661     case r_output_direction:
2662     case r_appending_to:
2663     case r_input_direction:
2664     case r_inputa_direction:
2665     case r_err_and_out:
2666     case r_input_output:
2667     case r_output_force:
2668     case r_duplicating_input_word:
2669     case r_duplicating_output_word:
2670       result = 1;
2671       break;
2672
2673     default:
2674       result = 0;
2675     }
2676   return (result);
2677 }
2678 \f
2679 /* Expand the word in WORD returning a string.  If WORD expands to
2680    multiple words (or no words), then return NULL. */
2681 char *
2682 redirection_expand (word)
2683      WORD_DESC *word;
2684 {
2685   char *result;
2686   WORD_LIST *tlist1, *tlist2;
2687
2688   tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
2689   tlist2 = expand_words_no_vars (tlist1);
2690   dispose_words (tlist1);
2691
2692   if (!tlist2 || tlist2->next)
2693     {
2694       /* We expanded to no words, or to more than a single word.
2695          Dispose of the word list and return NULL. */
2696       if (tlist2)
2697         dispose_words (tlist2);
2698       return ((char *)NULL);
2699     }
2700   result = string_list (tlist2);
2701   dispose_words (tlist2);
2702   return (result);
2703 }
2704
2705 /* Do the specific redirection requested.  Returns errno in case of error.
2706    If FOR_REAL is zero, then just do whatever is neccessary to produce the
2707    appropriate side effects.   REMEMBERING, if non-zero, says to remember
2708    how to undo each redirection.  If SET_CLEXEC is non-zero, then
2709    we set all file descriptors > 2 that we open to be close-on-exec.  */
2710 static int
2711 do_redirection_internal (redirect, for_real, remembering, set_clexec)
2712      REDIRECT *redirect;
2713      int for_real, remembering, set_clexec;
2714 {
2715   WORD_DESC *redirectee = redirect->redirectee.filename;
2716   int redir_fd = redirect->redirectee.dest;
2717   int fd, redirector = redirect->redirector;
2718   char *redirectee_word;
2719   enum r_instruction ri = redirect->instruction;
2720   REDIRECT *new_redirect;
2721
2722   if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
2723     {
2724       /* We have [N]>&WORD or [N]<&WORD.  Expand WORD, then translate
2725          the redirection into a new one and continue. */
2726       redirectee_word = redirection_expand (redirectee);
2727
2728       if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
2729         {
2730           rd.dest = 0L;
2731           new_redirect = make_redirection (redirector, r_close_this, rd);
2732         }
2733       else if (all_digits (redirectee_word))
2734         {
2735           if (ri == r_duplicating_input_word)
2736             {
2737               rd.dest = atol (redirectee_word);
2738               new_redirect = make_redirection (redirector, r_duplicating_input, rd);
2739             }
2740           else
2741             {
2742               rd.dest = atol (redirectee_word);
2743               new_redirect = make_redirection (redirector, r_duplicating_output, rd);
2744             }
2745         }
2746       else if (ri == r_duplicating_output_word && redirector == 1)
2747         {
2748           if (!posixly_correct)
2749             {
2750               rd.filename = make_word (redirectee_word);
2751               new_redirect = make_redirection (1, r_err_and_out, rd);
2752             }
2753           else
2754             new_redirect = copy_redirect (redirect);
2755         }
2756       else
2757         {
2758           free (redirectee_word);
2759           return (AMBIGUOUS_REDIRECT);
2760         }
2761
2762       free (redirectee_word);
2763
2764       /* Set up the variables needed by the rest of the function from the
2765          new redirection. */
2766       if (new_redirect->instruction == r_err_and_out)
2767         {
2768           char *alloca_hack;
2769
2770           /* Copy the word without allocating any memory that must be
2771              explicitly freed. */
2772           redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
2773           xbcopy ((char *)new_redirect->redirectee.filename,
2774                  (char *)redirectee, sizeof (WORD_DESC));
2775
2776           alloca_hack = (char *)
2777             alloca (1 + strlen (new_redirect->redirectee.filename->word));
2778           redirectee->word = alloca_hack;
2779           strcpy (redirectee->word, new_redirect->redirectee.filename->word);
2780         }
2781       else
2782         /* It's guaranteed to be an integer, and shouldn't be freed. */
2783         redirectee = new_redirect->redirectee.filename;
2784
2785       redir_fd = new_redirect->redirectee.dest;
2786       redirector = new_redirect->redirector;
2787       ri = new_redirect->instruction;
2788
2789       /* Overwrite the flags element of the old redirect with the new value. */
2790       redirect->flags = new_redirect->flags;
2791       dispose_redirects (new_redirect);
2792     }
2793
2794   switch (ri)
2795     {
2796     case r_output_direction:
2797     case r_appending_to:
2798     case r_input_direction:
2799     case r_inputa_direction:
2800     case r_err_and_out:         /* command &>filename */
2801     case r_input_output:
2802     case r_output_force:
2803
2804       if (posixly_correct && !interactive_shell)
2805         disallow_filename_globbing++;
2806       redirectee_word = redirection_expand (redirectee);
2807       if (posixly_correct && !interactive_shell)
2808         disallow_filename_globbing--;
2809       
2810       if (!redirectee_word)
2811         return (AMBIGUOUS_REDIRECT);
2812
2813 #if defined (RESTRICTED_SHELL)
2814       if (restricted && (ri == r_output_direction ||
2815                          ri == r_input_output ||
2816                          ri == r_err_and_out ||
2817                          ri == r_appending_to ||
2818                          ri == r_output_force))
2819         {
2820           free (redirectee_word);
2821           return (RESTRICTED_REDIRECT);
2822         }
2823 #endif /* RESTRICTED_SHELL */
2824
2825       /* If we are in noclobber mode, you are not allowed to overwrite
2826          existing files.  Check first. */
2827       if (noclobber && (ri == r_output_direction ||
2828                       ri == r_input_output ||
2829                       ri == r_err_and_out))
2830         {
2831           struct stat finfo;
2832           int stat_result;
2833
2834           stat_result = stat (redirectee_word, &finfo);
2835
2836           if ((stat_result == 0) && (S_ISREG (finfo.st_mode)))
2837             {
2838               free (redirectee_word);
2839               return (NOCLOBBER_REDIRECT);
2840             }
2841
2842           /* If the file was not present, make sure we open it exclusively
2843              so that if it is created before we open it, our open will fail. */
2844           if (stat_result != 0)
2845             redirect->flags |= O_EXCL;
2846
2847           fd = open (redirectee_word, redirect->flags, 0666);
2848
2849           if ((fd < 0) && (errno == EEXIST))
2850             {
2851               free (redirectee_word);
2852               return (NOCLOBBER_REDIRECT);
2853             }
2854         }
2855       else
2856         {
2857           fd = open (redirectee_word, redirect->flags, 0666);
2858 #if defined (AFS_CREATE_BUG)
2859           if ((fd < 0) && (errno == EACCES))
2860             fd = open (redirectee_word, (redirect->flags & ~O_CREAT), 0666);
2861 #endif /* AFS_CREATE_BUG */
2862         }
2863       free (redirectee_word);
2864
2865       if (fd < 0)
2866         return (errno);
2867
2868       if (for_real)
2869         {
2870           if (remembering)
2871             /* Only setup to undo it if the thing to undo is active. */
2872             if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
2873               add_undo_redirect (redirector);
2874             else
2875               add_undo_close_redirect (redirector);
2876
2877 #if defined (BUFFERED_INPUT)
2878           check_bash_input (redirector);
2879 #endif
2880
2881           if ((fd != redirector) && (dup2 (fd, redirector) < 0))
2882             return (errno);
2883
2884 #if defined (BUFFERED_INPUT)
2885           /* Do not change the buffered stream for an implicit redirection
2886              of /dev/null to fd 0 for asynchronous commands without job
2887              control (r_inputa_direction). */
2888           if (ri == r_input_direction || ri == r_input_output)
2889             duplicate_buffered_stream (fd, redirector);
2890 #endif /* BUFFERED_INPUT */
2891
2892           /*
2893            * If we're remembering, then this is the result of a while, for
2894            * or until loop with a loop redirection, or a function/builtin
2895            * executing in the parent shell with a redirection.  In the
2896            * function/builtin case, we want to set all file descriptors > 2
2897            * to be close-on-exec to duplicate the effect of the old
2898            * for i = 3 to NOFILE close(i) loop.  In the case of the loops,
2899            * both sh and ksh leave the file descriptors open across execs.
2900            * The Posix standard mentions only the exec builtin.
2901            */
2902           if (set_clexec && (redirector > 2))
2903             SET_CLOSE_ON_EXEC (redirector);
2904         }
2905
2906       if (fd != redirector)
2907         {
2908 #if defined (BUFFERED_INPUT)
2909           if (ri == r_input_direction || ri == r_inputa_direction ||
2910               ri == r_input_output)
2911             close_buffered_fd (fd);
2912           else
2913 #endif /* !BUFFERED_INPUT */
2914             close (fd);         /* Don't close what we just opened! */
2915         }
2916
2917       /* If we are hacking both stdout and stderr, do the stderr
2918          redirection here. */
2919       if (ri == r_err_and_out)
2920         {
2921           if (for_real)
2922             {
2923               if (remembering)
2924                 add_undo_redirect (2);
2925               if (dup2 (1, 2) < 0)
2926                 return (errno);
2927             }
2928         }
2929       break;
2930
2931     case r_reading_until:
2932     case r_deblank_reading_until:
2933       /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
2934          the new input.  Place it in a temporary file. */
2935       if (redirectee)
2936         {
2937           char filename[40];
2938           pid_t pid = getpid ();
2939
2940           /* Make the filename for the temp file. */
2941           sprintf (filename, "/tmp/t%d-sh", pid);
2942
2943           fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
2944           if (fd < 0)
2945             return (errno);
2946
2947           errno = 0;            /* XXX */
2948           if (redirectee->word)
2949             {
2950               char *document;
2951               int document_len;
2952
2953               /* Expand the text if the word that was specified had
2954                  no quoting.  The text that we expand is treated
2955                  exactly as if it were surrounded by double quotes. */
2956
2957               if (redirectee->quoted)
2958                 {
2959                   document = redirectee->word;
2960                   document_len = strlen (document);
2961                   /* Set errno to something reasonable if the write fails. */
2962                   if (write (fd, document, document_len) < document_len)
2963                     {
2964                       if (errno == 0)
2965                         errno = ENOSPC;
2966                       close (fd);
2967                       return (errno);
2968                     }
2969                 }
2970               else
2971                 {
2972                   WORD_LIST *tlist;
2973                   tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
2974                   if (tlist)
2975                     {
2976                       int fd2;
2977                       FILE *fp;
2978                       register WORD_LIST *t;
2979
2980                       /* Try using buffered I/O (stdio) and writing a word
2981                          at a time, letting stdio do the work of buffering
2982                          for us rather than managing our own strings.  Most
2983                          stdios are not particularly fast, however -- this
2984                          may need to be reconsidered later. */
2985                       if ((fd2 = dup (fd)) < 0 ||
2986                           (fp = fdopen (fd2, "w")) == NULL)
2987                         {
2988                           if (fd2 >= 0)
2989                             close (fd2);
2990                           close (fd);
2991                           return (errno);
2992                         }
2993                       errno = 0;        /* XXX */
2994                       for (t = tlist; t; t = t->next)
2995                         {
2996                           /* This is essentially the body of
2997                              string_list_internal expanded inline. */
2998                           document = t->word->word;
2999                           document_len = strlen (document);
3000                           if (t != tlist)
3001                             putc (' ', fp);     /* separator */
3002                           fwrite (document, document_len, 1, fp);
3003                           if (ferror (fp))
3004                             {
3005                               if (errno == 0)
3006                                 errno = ENOSPC;
3007                               break;
3008                             }
3009                         }
3010                       fclose (fp);
3011                       dispose_words (tlist);
3012                     }
3013                 }
3014             }     
3015
3016           close (fd);
3017           if (errno)
3018             return (errno);
3019
3020           /* Make the document really temporary.  Also make it the input. */
3021           fd = open (filename, O_RDONLY, 0666);
3022
3023           if (unlink (filename) < 0 || fd < 0)
3024             {
3025               if (fd >= 0)
3026                 close (fd);
3027               return (errno);
3028             }
3029
3030           if (for_real)
3031             {
3032               if (remembering)
3033                 /* Only setup to undo it if the thing to undo is active. */
3034                 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3035                   add_undo_redirect (redirector);
3036                 else
3037                   add_undo_close_redirect (redirector);
3038
3039 #if defined (BUFFERED_INPUT)
3040               check_bash_input (redirector);
3041 #endif
3042               if (dup2 (fd, redirector) < 0)
3043                 {
3044                   close (fd);
3045                   return (errno);
3046                 }
3047
3048 #if defined (BUFFERED_INPUT)
3049               duplicate_buffered_stream (fd, redirector);
3050 #endif
3051
3052               if (set_clexec && (redirector > 2))
3053                 SET_CLOSE_ON_EXEC (redirector);
3054             }
3055
3056 #if defined (BUFFERED_INPUT)
3057           close_buffered_fd (fd);
3058 #else
3059           close (fd);
3060 #endif
3061         }
3062       break;
3063
3064     case r_duplicating_input:
3065     case r_duplicating_output:
3066       if (for_real && (redir_fd != redirector))
3067         {
3068           if (remembering)
3069             /* Only setup to undo it if the thing to undo is active. */
3070             if (fcntl (redirector, F_GETFD, 0) != -1)
3071               add_undo_redirect (redirector);
3072             else
3073               add_undo_close_redirect (redirector);
3074
3075 #if defined (BUFFERED_INPUT)
3076           check_bash_input (redirector);
3077 #endif
3078           /* This is correct.  2>&1 means dup2 (1, 2); */
3079           if (dup2 (redir_fd, redirector) < 0)
3080             return (errno);
3081
3082 #if defined (BUFFERED_INPUT)
3083           if (ri == r_duplicating_input)
3084             duplicate_buffered_stream (redir_fd, redirector);
3085 #endif /* BUFFERED_INPUT */
3086
3087           /* First duplicate the close-on-exec state of redirectee.  dup2
3088              leaves the flag unset on the new descriptor, which means it
3089              stays open.  Only set the close-on-exec bit for file descriptors
3090              greater than 2 in any case, since 0-2 should always be open
3091              unless closed by something like `exec 2<&-'. */
3092           /* if ((already_set || set_unconditionally) && (ok_to_set))
3093                 set_it () */
3094           if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
3095                (redirector > 2))
3096             SET_CLOSE_ON_EXEC (redirector);
3097         }
3098       break;
3099
3100     case r_close_this:
3101       if (for_real)
3102         {
3103           if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
3104             add_undo_redirect (redirector);
3105
3106 #if defined (BUFFERED_INPUT)
3107           check_bash_input (redirector);
3108           close_buffered_fd (redirector);
3109 #else /* !BUFFERED_INPUT */
3110           close (redirector);
3111 #endif /* !BUFFERED_INPUT */
3112         }
3113       break;
3114     }
3115   return (0);
3116 }
3117
3118 #define SHELL_FD_BASE   10
3119
3120 /* Remember the file descriptor associated with the slot FD,
3121    on REDIRECTION_UNDO_LIST.  Note that the list will be reversed
3122    before it is executed.  Any redirections that need to be undone
3123    even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3124    are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3125 static int
3126 add_undo_redirect (fd)
3127      int fd;
3128 {
3129   int new_fd, clexec_flag;
3130   REDIRECT *new_redirect, *closer;
3131
3132   new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
3133
3134   if (new_fd < 0)
3135     {
3136       file_error ("redirection error");
3137       return (-1);
3138     }
3139   else
3140     {
3141       REDIRECT *dummy_redirect;
3142
3143       clexec_flag = fcntl (fd, F_GETFD, 0);
3144
3145       rd.dest = 0L;
3146       closer = make_redirection (new_fd, r_close_this, rd);
3147       dummy_redirect = copy_redirects (closer);
3148
3149       rd.dest = (long)new_fd;
3150       new_redirect = make_redirection (fd, r_duplicating_output, rd);
3151       new_redirect->next = closer;
3152
3153       closer->next = redirection_undo_list;
3154       redirection_undo_list = new_redirect;
3155
3156       /* Save redirections that need to be undone even if the undo list
3157          is thrown away by the `exec' builtin. */
3158       add_exec_redirect (dummy_redirect);
3159
3160       /* File descriptors used only for saving others should always be
3161          marked close-on-exec.  Unfortunately, we have to preserve the
3162          close-on-exec state of the file descriptor we are saving, since
3163          fcntl (F_DUPFD) sets the new file descriptor to remain open
3164          across execs.  If, however, the file descriptor whose state we
3165          are saving is <= 2, we can just set the close-on-exec flag,
3166          because file descriptors 0-2 should always be open-on-exec,
3167          and the restore above in do_redirection() will take care of it. */
3168       if (clexec_flag || fd < 3)
3169         SET_CLOSE_ON_EXEC (new_fd);
3170     }
3171   return (0);
3172 }
3173
3174 /* Set up to close FD when we are finished with the current command
3175    and its redirections. */
3176 static void
3177 add_undo_close_redirect (fd)
3178      int fd;
3179 {
3180   REDIRECT *closer;
3181
3182   rd.dest = 0L;
3183   closer = make_redirection (fd, r_close_this, rd);
3184   closer->next = redirection_undo_list;
3185   redirection_undo_list = closer;
3186 }
3187
3188 static void
3189 add_exec_redirect (dummy_redirect)
3190      REDIRECT *dummy_redirect;
3191 {
3192   dummy_redirect->next = exec_redirection_undo_list;
3193   exec_redirection_undo_list = dummy_redirect;
3194 }
3195
3196 intern_function (name, function)
3197      WORD_DESC *name;
3198      COMMAND *function;
3199 {
3200   SHELL_VAR *var;
3201
3202   if (!check_identifier (name, posixly_correct))
3203     return (EXECUTION_FAILURE);
3204
3205   var = find_function (name->word);
3206   if (var && readonly_p (var))
3207     {
3208       report_error ("%s: readonly function", var->name);
3209       return (EXECUTION_FAILURE);
3210     }
3211
3212   bind_function (name->word, function);
3213   return (EXECUTION_SUCCESS);
3214 }
3215
3216 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3217 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3218 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3219 #define X_BIT(x) ((x) & 1)
3220
3221 /* Return some flags based on information about this file.
3222    The EXISTS bit is non-zero if the file is found.
3223    The EXECABLE bit is non-zero the file is executble.
3224    Zero is returned if the file is not found. */
3225 int
3226 file_status (name)
3227      char *name;
3228 {
3229   struct stat finfo;
3230   static int user_id = -1;
3231
3232   /* Determine whether this file exists or not. */
3233   if (stat (name, &finfo) < 0)
3234     return (0);
3235
3236   /* If the file is a directory, then it is not "executable" in the
3237      sense of the shell. */
3238   if (S_ISDIR (finfo.st_mode))
3239     return (FS_EXISTS);
3240
3241 #if defined (AFS)
3242   /* We have to use access(2) to determine access because AFS does not
3243      support Unix file system semantics.  This may produce wrong
3244      answers for non-AFS files when ruid != euid.  I hate AFS. */
3245   if (access (name, X_OK) == 0)
3246     return (FS_EXISTS | FS_EXECABLE);
3247   else
3248     return (FS_EXISTS);
3249 #else /* !AFS */
3250
3251   /* Find out if the file is actually executable.  By definition, the
3252      only other criteria is that the file has an execute bit set that
3253      we can use. */
3254   if (user_id == -1)
3255     user_id = current_user.euid;
3256
3257   /* Root only requires execute permission for any of owner, group or
3258      others to be able to exec a file. */
3259   if (user_id == 0)
3260     {
3261       int bits;
3262
3263       bits = (u_mode_bits (finfo.st_mode) |
3264               g_mode_bits (finfo.st_mode) |
3265               o_mode_bits (finfo.st_mode));
3266
3267       if (X_BIT (bits))
3268         return (FS_EXISTS | FS_EXECABLE);
3269     }
3270
3271   /* If we are the owner of the file, the owner execute bit applies. */
3272   if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
3273     return (FS_EXISTS | FS_EXECABLE);
3274
3275   /* If we are in the owning group, the group permissions apply. */
3276   if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
3277     return (FS_EXISTS | FS_EXECABLE);
3278
3279   /* If `others' have execute permission to the file, then so do we,
3280      since we are also `others'. */
3281   if (X_BIT (o_mode_bits (finfo.st_mode)))
3282     return (FS_EXISTS | FS_EXECABLE);
3283   else
3284     return (FS_EXISTS);
3285 #endif /* !AFS */
3286 }
3287
3288 /* Return non-zero if FILE exists and is executable.
3289    Note that this function is the definition of what an
3290    executable file is; do not change this unless YOU know
3291    what an executable file is. */
3292 int
3293 executable_file (file)
3294      char *file;
3295 {
3296   return (file_status (file) & FS_EXECABLE);
3297 }
3298
3299 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
3300    encounters a `.' as the directory pathname while scanning the
3301    list of possible pathnames; i.e., if `.' comes before the directory
3302    containing the file of interest. */
3303 int dot_found_in_search = 0;
3304
3305 /* Locate the executable file referenced by NAME, searching along
3306    the contents of the shell PATH variable.  Return a new string
3307    which is the full pathname to the file, or NULL if the file
3308    couldn't be found.  If a file is found that isn't executable,
3309    and that is the only match, then return that. */
3310 char *
3311 find_user_command (name)
3312      char *name;
3313 {
3314   return (find_user_command_internal (name, FS_EXEC_PREFERRED));
3315 }
3316
3317 /* Locate the file referenced by NAME, searching along the contents
3318    of the shell PATH variable.  Return a new string which is the full
3319    pathname to the file, or NULL if the file couldn't be found.  This
3320    returns the first file found. */
3321 char *
3322 find_path_file (name)
3323      char *name;
3324 {
3325   return (find_user_command_internal (name, FS_EXISTS));
3326 }
3327
3328 static char *
3329 find_user_command_internal (name, flags)
3330      char *name;
3331      int flags;
3332 {
3333   char *path_list;
3334   SHELL_VAR *var;
3335
3336   /* Search for the value of PATH in both the temporary environment, and
3337      in the regular list of variables. */
3338   if (var = find_variable_internal ("PATH", 1))
3339     path_list = value_cell (var);
3340   else
3341     path_list = (char *)NULL;
3342
3343   if (path_list == 0 || *path_list == '\0')
3344     return (savestring (name));
3345
3346   return (find_user_command_in_path (name, path_list, flags));
3347 }
3348
3349 /* Return the next element from PATH_LIST, a colon separated list of
3350    paths.  PATH_INDEX_POINTER is the address of an index into PATH_LIST;
3351    the index is modified by this function.
3352    Return the next element of PATH_LIST or NULL if there are no more. */
3353 static char *
3354 get_next_path_element (path_list, path_index_pointer)
3355      char *path_list;
3356      int *path_index_pointer;
3357 {
3358   char *path;
3359
3360   path = extract_colon_unit (path_list, path_index_pointer);
3361
3362   if (!path)
3363     return (path);
3364
3365   if (!*path)
3366     {
3367       free (path);
3368       path = savestring (".");
3369     }
3370
3371   return (path);
3372 }
3373
3374 char *
3375 user_command_matches (name, flags, state)
3376      char *name;
3377      int flags, state;
3378 {
3379   register int i;
3380   char *path_list;
3381   int  path_index;
3382   char *path_element;
3383   char *match;
3384   static char **match_list = NULL;
3385   static int match_list_size = 0;
3386   static int match_index = 0;
3387
3388   if (!state)
3389     {
3390       /* Create the list of matches. */
3391       if (!match_list)
3392         {
3393           match_list =
3394             (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
3395
3396           for (i = 0; i < match_list_size; i++)
3397             match_list[i] = 0;
3398         }
3399
3400       /* Clear out the old match list. */
3401       for (i = 0; i < match_list_size; i++)
3402         match_list[i] = NULL;
3403
3404       /* We haven't found any files yet. */
3405       match_index = 0;
3406
3407       path_list = get_string_value ("PATH");
3408       path_index = 0;
3409
3410       while (path_list && path_list[path_index])
3411         {
3412           path_element = get_next_path_element (path_list, &path_index);
3413
3414           if (!path_element)
3415             break;
3416
3417           match = find_user_command_in_path (name, path_element, flags);
3418
3419           free (path_element);
3420
3421           if (!match)
3422             continue;
3423
3424           if (match_index + 1 == match_list_size)
3425             match_list = (char **)xrealloc
3426               (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
3427           match_list[match_index++] = match;
3428           match_list[match_index] = (char *)NULL;
3429         }
3430
3431       /* We haven't returned any strings yet. */
3432       match_index = 0;
3433     }
3434
3435   match = match_list[match_index];
3436
3437   if (match)
3438     match_index++;
3439
3440   return (match);
3441 }
3442
3443 /* Return 1 if PATH1 and PATH2 are the same file.  This is kind of
3444    expensive.  If non-NULL STP1 and STP2 point to stat structures
3445    corresponding to PATH1 and PATH2, respectively. */
3446 int
3447 same_file (path1, path2, stp1, stp2)
3448      char *path1, *path2;
3449      struct stat *stp1, *stp2;
3450 {
3451   struct stat st1, st2;
3452
3453   if (stp1 == NULL)
3454     {
3455       if (stat (path1, &st1) != 0)
3456         return (0);
3457       stp1 = &st1;
3458     }
3459
3460   if (stp2 == NULL)
3461     {
3462       if (stat (path2, &st2) != 0)
3463         return (0);
3464       stp2 = &st2;
3465     }
3466
3467   return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
3468 }
3469
3470 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
3471    This allocates new memory and returns it. */
3472 static char *
3473 make_full_pathname (path, name, name_len)
3474      char *path, *name;
3475      int name_len;
3476 {
3477   char *full_path;
3478   int path_len;
3479
3480   path_len = strlen (path);
3481   full_path = xmalloc (2 + path_len + name_len);
3482   strcpy (full_path, path);
3483   full_path[path_len] = '/';
3484   strcpy (full_path + path_len + 1, name);
3485   return (full_path);
3486 }
3487   
3488 /* This does the dirty work for find_path_file () and find_user_command ().
3489    NAME is the name of the file to search for.
3490    PATH_LIST is a colon separated list of directories to search.
3491    FLAGS contains bit fields which control the files which are eligible.
3492    Some values are:
3493       FS_EXEC_ONLY:             The file must be an executable to be found.
3494       FS_EXEC_PREFERRED:        If we can't find an executable, then the
3495                                 the first file matching NAME will do.
3496       FS_EXISTS:                The first file found will do.
3497 */
3498 static char *
3499 find_user_command_in_path (name, path_list, flags)
3500      char *name;
3501      char *path_list;
3502      int flags;
3503 {
3504   char *full_path, *path, *file_to_lose_on;
3505   int status, path_index, name_len;
3506   struct stat finfo;
3507
3508   name_len = strlen (name);
3509
3510   /* The file name which we would try to execute, except that it isn't
3511      possible to execute it.  This is the first file that matches the
3512      name that we are looking for while we are searching $PATH for a
3513      suitable one to execute.  If we cannot find a suitable executable
3514      file, then we use this one. */
3515   file_to_lose_on = (char *)NULL;
3516
3517   /* We haven't started looking, so we certainly haven't seen
3518      a `.' as the directory path yet. */
3519   dot_found_in_search = 0;
3520
3521   if (absolute_program (name))
3522     {
3523       full_path = xmalloc (1 + name_len);
3524       strcpy (full_path, name);
3525
3526       status = file_status (full_path);
3527
3528       /* If the file doesn't exist, quit now. */
3529       if (!(status & FS_EXISTS))
3530         {
3531           free (full_path);
3532           return ((char *)NULL);
3533         }
3534
3535       /* If we only care about whether the file exists or not, return
3536          this filename. */
3537       if (flags & FS_EXISTS)
3538         return (full_path);
3539
3540       /* Otherwise, maybe we care about whether this file is executable.
3541          If it is, and that is what we want, return it. */
3542       if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
3543         return (full_path);
3544       else
3545         {
3546           free (full_path);
3547           return ((char *)NULL);
3548         }
3549     }
3550
3551   /* Find out the location of the current working directory. */
3552   stat (".", &finfo);
3553
3554   path_index = 0;
3555   while (path_list && path_list[path_index])
3556     {
3557       /* Allow the user to interrupt out of a lengthy path search. */
3558       QUIT;
3559
3560       path = get_next_path_element (path_list, &path_index);
3561
3562       if (!path)
3563         break;
3564
3565       if (*path == '~')
3566         {
3567           char *t = tilde_expand (path);
3568           free (path);
3569           path = t;
3570         }
3571
3572       /* Remember the location of "." in the path, in all its forms
3573          (as long as they begin with a `.', e.g. `./.') */
3574       if (!dot_found_in_search && (*path == '.') &&
3575           same_file (".", path, &finfo, (struct stat *)NULL))
3576         dot_found_in_search = 1;
3577
3578       full_path = make_full_pathname (path, name, name_len);
3579       free (path);
3580
3581       status = file_status (full_path);
3582
3583       if (!(status & FS_EXISTS))
3584         goto next_file;
3585
3586       /* The file exists.  If the caller simply wants the first file,
3587          here it is. */
3588       if (flags & FS_EXISTS)
3589         return (full_path);
3590
3591        /* If the file is executable, then it satisfies the cases of
3592           EXEC_ONLY and EXEC_PREFERRED.  Return this file unconditionally. */
3593       if (status & FS_EXECABLE)
3594         {
3595           FREE (file_to_lose_on);
3596
3597           return (full_path);
3598         }
3599
3600       /* The file is not executable, but it does exist.  If we prefer
3601          an executable, then remember this one if it is the first one
3602          we have found. */
3603       if (flags & FS_EXEC_PREFERRED)
3604         {
3605           if (!file_to_lose_on)
3606             file_to_lose_on = savestring (full_path);
3607         }
3608
3609     next_file:
3610       free (full_path);
3611     }
3612
3613   /* We didn't find exactly what the user was looking for.  Return
3614      the contents of FILE_TO_LOSE_ON which is NULL when the search
3615      required an executable, or non-NULL if a file was found and the
3616      search would accept a non-executable as a last resort. */
3617   return (file_to_lose_on);
3618 }
3619
3620 /* Given a string containing units of information separated by colons,
3621    return the next one pointed to by (P_INDEX), or NULL if there are no more.
3622    Advance (P_INDEX) to the character after the colon. */
3623 char *
3624 extract_colon_unit (string, p_index)
3625      char *string;
3626      int *p_index;
3627 {
3628   int i, start;
3629
3630   i = *p_index;
3631
3632   if (!string || (i >= (int)strlen (string)))
3633     return ((char *)NULL);
3634
3635   /* Each call to this routine leaves the index pointing at a colon if
3636      there is more to the path.  If I is > 0, then increment past the
3637      `:'.  If I is 0, then the path has a leading colon.  Trailing colons
3638      are handled OK by the `else' part of the if statement; an empty
3639      string is returned in that case. */
3640   if (i && string[i] == ':')
3641     i++;
3642
3643   start = i;
3644
3645   while (string[i] && string[i] != ':') i++;
3646
3647   *p_index = i;
3648
3649   if (i == start)
3650     {
3651       if (string[i])
3652         (*p_index)++;
3653
3654       /* Return "" in the case of a trailing `:'. */
3655       return (savestring (""));
3656     }
3657   else
3658     {
3659       char *value;
3660
3661       value = xmalloc (1 + i - start);
3662       strncpy (value, string + start, i - start);
3663       value [i - start] = '\0';
3664
3665       return (value);
3666     }
3667 }
3668
3669 /* Return non-zero if the characters from SAMPLE are not all valid
3670    characters to be found in the first line of a shell script.  We
3671    check up to the first newline, or SAMPLE_LEN, whichever comes first.
3672    All of the characters must be printable or whitespace. */
3673
3674 #if !defined (isspace)
3675 #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
3676 #endif
3677
3678 #if !defined (isprint)
3679 #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
3680 #endif
3681
3682 int
3683 check_binary_file (sample, sample_len)
3684      unsigned char *sample;
3685      int sample_len;
3686 {
3687   register int i;
3688
3689   for (i = 0; i < sample_len; i++)
3690     {
3691       if (sample[i] == '\n')
3692         break;
3693
3694       if (!isspace (sample[i]) && !isprint (sample[i]))
3695         return (1);
3696     }
3697   return (0);
3698 }