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