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