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