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