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