1 /* execute_cmd.c -- Execute a COMMAND structure. */
2 
3 /* Copyright (C) 1987-2020 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
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation, either version 3 of the License, or
10    (at your option) any later version.
11 
12    Bash is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
19 */
20 
21 #include "config.h"
22 
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24   #pragma alloca
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
26 
27 #include <stdio.h>
28 #include "chartypes.h"
29 #include "bashtypes.h"
30 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
31 #  include <sys/file.h>
32 #endif
33 #include "filecntl.h"
34 #include "posixstat.h"
35 #include <signal.h>
36 #if defined (HAVE_SYS_PARAM_H)
37 #  include <sys/param.h>
38 #endif
39 
40 #if defined (HAVE_UNISTD_H)
41 #  include <unistd.h>
42 #endif
43 
44 #include "posixtime.h"
45 
46 #if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
47 #  include <sys/resource.h>
48 #endif
49 
50 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
51 #  include <sys/times.h>
52 #endif
53 
54 #include <errno.h>
55 
56 #if !defined (errno)
57 extern int errno;
58 #endif
59 
60 #define NEED_FPURGE_DECL
61 #define NEED_SH_SETLINEBUF_DECL
62 
63 #include "bashansi.h"
64 #include "bashintl.h"
65 
66 #include "memalloc.h"
67 #include "shell.h"
68 #include <y.tab.h>	/* use <...> so we pick it up from the build directory */
69 #include "parser.h"
70 #include "flags.h"
71 #include "builtins.h"
72 #include "hashlib.h"
73 #include "jobs.h"
74 #include "execute_cmd.h"
75 #include "findcmd.h"
76 #include "redir.h"
77 #include "trap.h"
78 #include "pathexp.h"
79 #include "hashcmd.h"
80 
81 #if defined (COND_COMMAND)
82 #  include "test.h"
83 #endif
84 
85 #include "builtins/common.h"
86 #include "builtins/builtext.h"	/* list of builtins */
87 
88 #include "builtins/getopt.h"
89 
90 #include <glob/strmatch.h>
91 #include <tilde/tilde.h>
92 
93 #if defined (BUFFERED_INPUT)
94 #  include "input.h"
95 #endif
96 
97 #if defined (ALIAS)
98 #  include "alias.h"
99 #endif
100 
101 #if defined (HISTORY)
102 #  include "bashhist.h"
103 #endif
104 
105 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
106 #  include <mbstr.h>		/* mbschr */
107 #endif
108 
109 extern int command_string_index;
110 extern char *the_printed_command;
111 extern time_t shell_start_time;
112 #if defined (HAVE_GETTIMEOFDAY)
113 extern struct timeval shellstart;
114 #endif
115 #if 0
116 extern char *glob_argv_flags;
117 #endif
118 
119 extern int close PARAMS((int));
120 
121 /* Static functions defined and used in this file. */
122 static void close_pipes PARAMS((int, int));
123 static void do_piping PARAMS((int, int));
124 static void bind_lastarg PARAMS((char *));
125 static int shell_control_structure PARAMS((enum command_type));
126 static void cleanup_redirects PARAMS((REDIRECT *));
127 
128 #if defined (JOB_CONTROL)
129 static int restore_signal_mask PARAMS((sigset_t *));
130 #endif
131 
132 static int builtin_status PARAMS((int));
133 
134 static int execute_for_command PARAMS((FOR_COM *));
135 #if defined (SELECT_COMMAND)
136 static int displen PARAMS((const char *));
137 static int print_index_and_element PARAMS((int, int, WORD_LIST *));
138 static void indent PARAMS((int, int));
139 static void print_select_list PARAMS((WORD_LIST *, int, int, int));
140 static char *select_query PARAMS((WORD_LIST *, int, char *, int));
141 static int execute_select_command PARAMS((SELECT_COM *));
142 #endif
143 #if defined (DPAREN_ARITHMETIC)
144 static int execute_arith_command PARAMS((ARITH_COM *));
145 #endif
146 #if defined (COND_COMMAND)
147 static int execute_cond_node PARAMS((COND_COM *));
148 static int execute_cond_command PARAMS((COND_COM *));
149 #endif
150 #if defined (COMMAND_TIMING)
151 static int mkfmt PARAMS((char *, int, int, time_t, int));
152 static void print_formatted_time PARAMS((FILE *, char *,
153 				      time_t, int, time_t, int,
154 				      time_t, int, int));
155 static int time_command PARAMS((COMMAND *, int, int, int, struct fd_bitmap *));
156 #endif
157 #if defined (ARITH_FOR_COMMAND)
158 static intmax_t eval_arith_for_expr PARAMS((WORD_LIST *, int *));
159 static int execute_arith_for_command PARAMS((ARITH_FOR_COM *));
160 #endif
161 static int execute_case_command PARAMS((CASE_COM *));
162 static int execute_while_command PARAMS((WHILE_COM *));
163 static int execute_until_command PARAMS((WHILE_COM *));
164 static int execute_while_or_until PARAMS((WHILE_COM *, int));
165 static int execute_if_command PARAMS((IF_COM *));
166 static int execute_null_command PARAMS((REDIRECT *, int, int, int));
167 static void fix_assignment_words PARAMS((WORD_LIST *));
168 static int execute_simple_command PARAMS((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
169 static int execute_builtin PARAMS((sh_builtin_func_t *, WORD_LIST *, int, int));
170 static int execute_function PARAMS((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
171 static int execute_builtin_or_function PARAMS((WORD_LIST *, sh_builtin_func_t *,
172 					    SHELL_VAR *,
173 					    REDIRECT *, struct fd_bitmap *, int));
174 static void execute_subshell_builtin_or_function PARAMS((WORD_LIST *, REDIRECT *,
175 						      sh_builtin_func_t *,
176 						      SHELL_VAR *,
177 						      int, int, int,
178 						      struct fd_bitmap *,
179 						      int));
180 static int execute_disk_command PARAMS((WORD_LIST *, REDIRECT *, char *,
181 				      int, int, int, struct fd_bitmap *, int));
182 
183 static char *getinterp PARAMS((char *, int, int *));
184 static void initialize_subshell PARAMS((void));
185 static int execute_in_subshell PARAMS((COMMAND *, int, int, int, struct fd_bitmap *));
186 #if defined (COPROCESS_SUPPORT)
187 static void coproc_setstatus PARAMS((struct coproc *, int));
188 static int execute_coproc PARAMS((COMMAND *, int, int, struct fd_bitmap *));
189 #endif
190 
191 static int execute_pipeline PARAMS((COMMAND *, int, int, int, struct fd_bitmap *));
192 
193 static int execute_connection PARAMS((COMMAND *, int, int, int, struct fd_bitmap *));
194 
195 static int execute_intern_function PARAMS((WORD_DESC *, FUNCTION_DEF *));
196 
197 /* Set to 1 if fd 0 was the subject of redirection to a subshell.  Global
198    so that reader_loop can set it to zero before executing a command. */
199 int stdin_redir;
200 
201 /* The name of the command that is currently being executed.
202    `test' needs this, for example. */
203 char *this_command_name;
204 
205 /* The printed representation of the currently-executing command (same as
206    the_printed_command), except when a trap is being executed.  Useful for
207    a debugger to know where exactly the program is currently executing. */
208 char *the_printed_command_except_trap;
209 
210 /* For catching RETURN in a function. */
211 int return_catch_flag;
212 int return_catch_value;
213 procenv_t return_catch;
214 
215 /* The value returned by the last synchronous command. */
216 volatile int last_command_exit_value;
217 
218 /* Whether or not the last command (corresponding to last_command_exit_value)
219    was terminated by a signal, and, if so, which one. */
220 int last_command_exit_signal;
221 
222 /* Are we currently ignoring the -e option for the duration of a builtin's
223    execution? */
224 int builtin_ignoring_errexit = 0;
225 
226 /* The list of redirections to perform which will undo the redirections
227    that I made in the shell. */
228 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
229 
230 /* The list of redirections to perform which will undo the internal
231    redirections performed by the `exec' builtin.  These are redirections
232    that must be undone even when exec discards redirection_undo_list. */
233 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
234 
235 /* When greater than zero, value is the `level' of builtins we are
236    currently executing (e.g. `eval echo a' would have it set to 2). */
237 int executing_builtin = 0;
238 
239 /* Non-zero if we are executing a command list (a;b;c, etc.) */
240 int executing_list = 0;
241 
242 /* Non-zero if failing commands in a command substitution should not exit the
243    shell even if -e is set.  Used to pass the CMD_IGNORE_RETURN flag down to
244    commands run in command substitutions by parse_and_execute. */
245 int comsub_ignore_return = 0;
246 
247 /* Non-zero if we have just forked and are currently running in a subshell
248    environment. */
249 int subshell_environment;
250 
251 /* Count of nested subshells, like SHLVL.  Available via $BASH_SUBSHELL */
252 int subshell_level = 0;
253 
254 /* Currently-executing shell function. */
255 SHELL_VAR *this_shell_function;
256 
257 /* If non-zero, matches in case and [[ ... ]] are case-insensitive */
258 int match_ignore_case = 0;
259 
260 int executing_command_builtin = 0;
261 
262 struct stat SB;		/* used for debugging */
263 
264 static int special_builtin_failed;
265 
266 static COMMAND *currently_executing_command;
267 
268 /* The line number that the currently executing function starts on. */
269 static int function_line_number;
270 
271 /* XXX - set to 1 if we're running the DEBUG trap and we want to show the line
272    number containing the function name.  Used by executing_line_number to
273    report the correct line number.  Kind of a hack. */
274 static int showing_function_line;
275 
276 static int connection_count;
277 
278 /* $LINENO ($BASH_LINENO) for use by an ERR trap.  Global so parse_and_execute
279    can save and restore it. */
280 int line_number_for_err_trap;
281 
282 /* A sort of function nesting level counter */
283 int funcnest = 0;
284 int funcnest_max = 0;
285 
286 int evalnest = 0;
287 int evalnest_max = EVALNEST_MAX;
288 
289 int sourcenest = 0;
290 int sourcenest_max = SOURCENEST_MAX;
291 
292 volatile int from_return_trap = 0;
293 
294 int lastpipe_opt = 0;
295 
296 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
297 
298 #define FD_BITMAP_DEFAULT_SIZE 32
299 
300 /* Functions to allocate and deallocate the structures used to pass
301    information from the shell to its children about file descriptors
302    to close. */
303 struct fd_bitmap *
new_fd_bitmap(size)304 new_fd_bitmap (size)
305      int size;
306 {
307   struct fd_bitmap *ret;
308 
309   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
310 
311   ret->size = size;
312 
313   if (size)
314     {
315       ret->bitmap = (char *)xmalloc (size);
316       memset (ret->bitmap, '\0', size);
317     }
318   else
319     ret->bitmap = (char *)NULL;
320   return (ret);
321 }
322 
323 void
dispose_fd_bitmap(fdbp)324 dispose_fd_bitmap (fdbp)
325      struct fd_bitmap *fdbp;
326 {
327   FREE (fdbp->bitmap);
328   free (fdbp);
329 }
330 
331 void
close_fd_bitmap(fdbp)332 close_fd_bitmap (fdbp)
333      struct fd_bitmap *fdbp;
334 {
335   register int i;
336 
337   if (fdbp)
338     {
339       for (i = 0; i < fdbp->size; i++)
340 	if (fdbp->bitmap[i])
341 	  {
342 	    close (i);
343 	    fdbp->bitmap[i] = 0;
344 	  }
345     }
346 }
347 
348 /* Return the line number of the currently executing command. */
349 int
executing_line_number()350 executing_line_number ()
351 {
352   if (executing && showing_function_line == 0 &&
353       (variable_context == 0 || interactive_shell == 0) &&
354       currently_executing_command)
355     {
356 #if defined (COND_COMMAND)
357       if (currently_executing_command->type == cm_cond)
358 	return currently_executing_command->value.Cond->line;
359 #endif
360 #if defined (DPAREN_ARITHMETIC)
361       if (currently_executing_command->type == cm_arith)
362 	return currently_executing_command->value.Arith->line;
363 #endif
364 #if defined (ARITH_FOR_COMMAND)
365       if (currently_executing_command->type == cm_arith_for)
366 	return currently_executing_command->value.ArithFor->line;
367 #endif
368 
369 	return line_number;
370     }
371   else
372     return line_number;
373 }
374 
375 /* Execute the command passed in COMMAND.  COMMAND is exactly what
376    read_command () places into GLOBAL_COMMAND.  See "command.h" for the
377    details of the command structure.
378 
379    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
380    return values.  Executing a command with nothing in it returns
381    EXECUTION_SUCCESS. */
382 int
execute_command(command)383 execute_command (command)
384      COMMAND *command;
385 {
386   struct fd_bitmap *bitmap;
387   int result;
388 
389   current_fds_to_close = (struct fd_bitmap *)NULL;
390   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
391   begin_unwind_frame ("execute-command");
392   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
393 
394   /* Just do the command, but not asynchronously. */
395   result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
396 
397   dispose_fd_bitmap (bitmap);
398   discard_unwind_frame ("execute-command");
399 
400 #if defined (PROCESS_SUBSTITUTION)
401   /* don't unlink fifos if we're in a shell function; wait until the function
402      returns. */
403   if (variable_context == 0 && executing_list == 0)
404     unlink_fifo_list ();
405 #endif /* PROCESS_SUBSTITUTION */
406 
407   QUIT;
408   return (result);
409 }
410 
411 /* Return 1 if TYPE is a shell control structure type. */
412 static int
shell_control_structure(type)413 shell_control_structure (type)
414      enum command_type type;
415 {
416   switch (type)
417     {
418 #if defined (ARITH_FOR_COMMAND)
419     case cm_arith_for:
420 #endif
421 #if defined (SELECT_COMMAND)
422     case cm_select:
423 #endif
424 #if defined (DPAREN_ARITHMETIC)
425     case cm_arith:
426 #endif
427 #if defined (COND_COMMAND)
428     case cm_cond:
429 #endif
430     case cm_case:
431     case cm_while:
432     case cm_until:
433     case cm_if:
434     case cm_for:
435     case cm_group:
436     case cm_function_def:
437       return (1);
438 
439     default:
440       return (0);
441     }
442 }
443 
444 /* A function to use to unwind_protect the redirection undo list
445    for loops. */
446 static void
cleanup_redirects(list)447 cleanup_redirects (list)
448      REDIRECT *list;
449 {
450   do_redirections (list, RX_ACTIVE);
451   dispose_redirects (list);
452 }
453 
454 void
undo_partial_redirects()455 undo_partial_redirects ()
456 {
457   if (redirection_undo_list)
458     {
459       cleanup_redirects (redirection_undo_list);
460       redirection_undo_list = (REDIRECT *)NULL;
461     }
462 }
463 
464 #if 0
465 /* Function to unwind_protect the redirections for functions and builtins. */
466 static void
467 cleanup_func_redirects (list)
468      REDIRECT *list;
469 {
470   do_redirections (list, RX_ACTIVE);
471 }
472 #endif
473 
474 void
dispose_exec_redirects()475 dispose_exec_redirects ()
476 {
477   if (exec_redirection_undo_list)
478     {
479       dispose_redirects (exec_redirection_undo_list);
480       exec_redirection_undo_list = (REDIRECT *)NULL;
481     }
482 }
483 
484 void
dispose_partial_redirects()485 dispose_partial_redirects ()
486 {
487   if (redirection_undo_list)
488     {
489       dispose_redirects (redirection_undo_list);
490       redirection_undo_list = (REDIRECT *)NULL;
491     }
492 }
493 
494 #if defined (JOB_CONTROL)
495 /* A function to restore the signal mask to its proper value when the shell
496    is interrupted or errors occur while creating a pipeline. */
497 static int
restore_signal_mask(set)498 restore_signal_mask (set)
499      sigset_t *set;
500 {
501   return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
502 }
503 #endif /* JOB_CONTROL */
504 
505 #ifdef DEBUG
506 /* A debugging function that can be called from gdb, for instance. */
507 void
open_files()508 open_files ()
509 {
510   register int i;
511   int f, fd_table_size;
512 
513   fd_table_size = getdtablesize ();
514 
515   fprintf (stderr, "pid %ld open files:", (long)getpid ());
516   for (i = 3; i < fd_table_size; i++)
517     {
518       if ((f = fcntl (i, F_GETFD, 0)) != -1)
519 	fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
520     }
521   fprintf (stderr, "\n");
522 }
523 #endif
524 
525 void
async_redirect_stdin()526 async_redirect_stdin ()
527 {
528   int fd;
529 
530   fd = open ("/dev/null", O_RDONLY);
531   if (fd > 0)
532     {
533       dup2 (fd, 0);
534       close (fd);
535     }
536   else if (fd < 0)
537     internal_error (_("cannot redirect standard input from /dev/null: %s"), strerror (errno));
538 }
539 
540 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
541 
542 /* Execute the command passed in COMMAND, perhaps doing it asynchronously.
543    COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
544    ASYNCHRONOUS, if non-zero, says to do this command in the background.
545    PIPE_IN and PIPE_OUT are file descriptors saying where input comes
546    from and where it goes.  They can have the value of NO_PIPE, which means
547    I/O is stdin/stdout.
548    FDS_TO_CLOSE is a list of file descriptors to close once the child has
549    been forked.  This list often contains the unusable sides of pipes, etc.
550 
551    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
552    return values.  Executing a command with nothing in it returns
553    EXECUTION_SUCCESS. */
554 int
execute_command_internal(command,asynchronous,pipe_in,pipe_out,fds_to_close)555 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
556 			  fds_to_close)
557      COMMAND *command;
558      int asynchronous;
559      int pipe_in, pipe_out;
560      struct fd_bitmap *fds_to_close;
561 {
562   int exec_result, user_subshell, invert, ignore_return, was_error_trap, fork_flags;
563   REDIRECT *my_undo_list, *exec_undo_list;
564   char *tcmd;
565   volatile int save_line_number;
566 #if defined (PROCESS_SUBSTITUTION)
567   volatile int ofifo, nfifo, osize, saved_fifo;
568   volatile void *ofifo_list;
569 #endif
570 
571   if (breaking || continuing)
572     return (last_command_exit_value);
573   if (command == 0 || read_but_dont_execute)
574     return (EXECUTION_SUCCESS);
575 
576   QUIT;
577   run_pending_traps ();
578 
579 #if 0
580   if (running_trap == 0)
581 #endif
582     currently_executing_command = command;
583 
584   invert = (command->flags & CMD_INVERT_RETURN) != 0;
585 
586   /* If we're inverting the return value and `set -e' has been executed,
587      we don't want a failing command to inadvertently cause the shell
588      to exit. */
589   if (exit_immediately_on_error && invert)	/* XXX */
590     command->flags |= CMD_IGNORE_RETURN;	/* XXX */
591 
592   exec_result = EXECUTION_SUCCESS;
593 
594   /* If a command was being explicitly run in a subshell, or if it is
595      a shell control-structure, and it has a pipe, then we do the command
596      in a subshell. */
597   if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
598     return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
599 
600 #if defined (COPROCESS_SUPPORT)
601   if (command->type == cm_coproc)
602     return (last_command_exit_value = execute_coproc (command, pipe_in, pipe_out, fds_to_close));
603 #endif
604 
605   user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
606 
607 #if defined (TIME_BEFORE_SUBSHELL)
608   if ((command->flags & CMD_TIME_PIPELINE) && user_subshell && asynchronous == 0)
609     {
610       command->flags |= CMD_FORCE_SUBSHELL;
611       exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
612       currently_executing_command = (COMMAND *)NULL;
613       return (exec_result);
614     }
615 #endif
616 
617   if (command->type == cm_subshell ||
618       (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
619       (shell_control_structure (command->type) &&
620        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
621     {
622       pid_t paren_pid;
623       int s;
624       char *p;
625 
626       /* Fork a subshell, turn off the subshell bit, turn off job
627 	 control and call execute_command () on the command again. */
628       save_line_number = line_number;
629       if (command->type == cm_subshell)
630 	line_number_for_err_trap = line_number = command->value.Subshell->line;	/* XXX - save value? */
631 	/* Otherwise we defer setting line_number */
632       tcmd = make_command_string (command);
633       fork_flags = asynchronous ? FORK_ASYNC : 0;
634       paren_pid = make_child (p = savestring (tcmd), fork_flags);
635 
636       if (user_subshell && signal_is_trapped (ERROR_TRAP) &&
637 	  signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
638 	{
639 	  FREE (the_printed_command_except_trap);
640 	  the_printed_command_except_trap = savestring (the_printed_command);
641 	}
642 
643       if (paren_pid == 0)
644         {
645 #if defined (JOB_CONTROL)
646 	  FREE (p);		/* child doesn't use pointer */
647 #endif
648 	  /* We want to run the exit trap for forced {} subshells, and we
649 	     want to note this before execute_in_subshell modifies the
650 	     COMMAND struct.  Need to keep in mind that execute_in_subshell
651 	     runs the exit trap for () subshells itself. */
652 	  /* This handles { command; } & */
653 	  s = user_subshell == 0 && command->type == cm_group && pipe_in == NO_PIPE && pipe_out == NO_PIPE && asynchronous;
654 	  /* run exit trap for : | { ...; } and { ...; } | : */
655 	  /* run exit trap for : | ( ...; ) and ( ...; ) | : */
656 	  s += user_subshell == 0 && command->type == cm_group && (pipe_in != NO_PIPE || pipe_out != NO_PIPE) && asynchronous == 0;
657 
658 	  last_command_exit_value = execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close);
659 	  if (s)
660 	    subshell_exit (last_command_exit_value);
661 	  else
662 	    sh_exit (last_command_exit_value);
663 	  /* NOTREACHED */
664         }
665       else
666 	{
667 	  close_pipes (pipe_in, pipe_out);
668 
669 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
670 	  if (variable_context == 0)	/* wait until shell function completes */
671 	    unlink_fifo_list ();
672 #endif
673 	  /* If we are part of a pipeline, and not the end of the pipeline,
674 	     then we should simply return and let the last command in the
675 	     pipe be waited for.  If we are not in a pipeline, or are the
676 	     last command in the pipeline, then we wait for the subshell
677 	     and return its exit status as usual. */
678 	  if (pipe_out != NO_PIPE)
679 	    return (EXECUTION_SUCCESS);
680 
681 	  stop_pipeline (asynchronous, (COMMAND *)NULL);
682 
683 	  line_number = save_line_number;
684 
685 	  if (asynchronous == 0)
686 	    {
687 	      was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
688 	      invert = (command->flags & CMD_INVERT_RETURN) != 0;
689 	      ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
690 
691 	      exec_result = wait_for (paren_pid, 0);
692 
693 	      /* If we have to, invert the return value. */
694 	      if (invert)
695 		exec_result = ((exec_result == EXECUTION_SUCCESS)
696 				? EXECUTION_FAILURE
697 				: EXECUTION_SUCCESS);
698 
699 	      last_command_exit_value = exec_result;
700 	      if (user_subshell && was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
701 		{
702 		  save_line_number = line_number;
703 		  line_number = line_number_for_err_trap;
704 		  run_error_trap ();
705 		  line_number = save_line_number;
706 		}
707 
708 	      if (user_subshell && ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
709 		{
710 		  run_pending_traps ();
711 		  jump_to_top_level (ERREXIT);
712 		}
713 
714 	      return (last_command_exit_value);
715 	    }
716 	  else
717 	    {
718 	      DESCRIBE_PID (paren_pid);
719 
720 	      run_pending_traps ();
721 
722 	      /* Posix 2013 2.9.3.1: "the exit status of an asynchronous list
723 		 shall be zero." */
724 	      last_command_exit_value = 0;
725 	      return (EXECUTION_SUCCESS);
726 	    }
727 	}
728     }
729 
730 #if defined (COMMAND_TIMING)
731   if (command->flags & CMD_TIME_PIPELINE)
732     {
733       if (asynchronous)
734 	{
735 	  command->flags |= CMD_FORCE_SUBSHELL;
736 	  exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
737 	}
738       else
739 	{
740 	  exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
741 #if 0
742 	  if (running_trap == 0)
743 #endif
744 	    currently_executing_command = (COMMAND *)NULL;
745 	}
746       return (exec_result);
747     }
748 #endif /* COMMAND_TIMING */
749 
750   if (shell_control_structure (command->type) && command->redirects)
751     stdin_redir = stdin_redirects (command->redirects);
752 
753 #if defined (PROCESS_SUBSTITUTION)
754 #  if !defined (HAVE_DEV_FD)
755   reap_procsubs ();
756 #  endif
757 
758   /* XXX - also if sourcelevel != 0? */
759   if (variable_context != 0 || executing_list)
760     {
761       ofifo = num_fifos ();
762       ofifo_list = copy_fifo_list ((int *)&osize);
763       begin_unwind_frame ("internal_fifos");
764       if (ofifo_list)
765 	add_unwind_protect (xfree, ofifo_list);
766       saved_fifo = 1;
767     }
768   else
769     saved_fifo = 0;
770 #endif
771 
772   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
773      redirection.)  */
774   was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
775   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
776 
777   if (do_redirections (command->redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
778     {
779       undo_partial_redirects ();
780       dispose_exec_redirects ();
781 #if defined (PROCESS_SUBSTITUTION)
782       if (saved_fifo)
783 	{
784 	  free ((void *)ofifo_list);
785           discard_unwind_frame ("internal_fifos");
786 	}
787 #endif
788 
789       /* Handle redirection error as command failure if errexit set. */
790       last_command_exit_value = EXECUTION_FAILURE;
791       if (ignore_return == 0 && invert == 0 && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
792 	{
793 	  if (was_error_trap)
794 	    {
795 	      save_line_number = line_number;
796 	      line_number = line_number_for_err_trap;
797 	      run_error_trap ();
798 	      line_number = save_line_number;
799 	    }
800 	  if (exit_immediately_on_error)
801 	    {
802 	      run_pending_traps ();
803 	      jump_to_top_level (ERREXIT);
804 	    }
805 	}
806       return (last_command_exit_value);
807     }
808 
809   my_undo_list = redirection_undo_list;
810   redirection_undo_list = (REDIRECT *)NULL;
811 
812   exec_undo_list = exec_redirection_undo_list;
813   exec_redirection_undo_list = (REDIRECT *)NULL;
814 
815   if (my_undo_list || exec_undo_list)
816     begin_unwind_frame ("loop_redirections");
817 
818   if (my_undo_list)
819     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
820 
821   if (exec_undo_list)
822     add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
823 
824   QUIT;
825 
826   switch (command->type)
827     {
828     case cm_simple:
829       {
830 	save_line_number = line_number;
831 	/* We can't rely on variables retaining their values across a
832 	   call to execute_simple_command if a longjmp occurs as the
833 	   result of a `return' builtin.  This is true for sure with gcc. */
834 #if defined (RECYCLES_PIDS)
835 	last_made_pid = NO_PID;
836 #endif
837 	was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
838 
839 	if (ignore_return && command->value.Simple)
840 	  command->value.Simple->flags |= CMD_IGNORE_RETURN;
841 	if (command->flags & CMD_STDIN_REDIR)
842 	  command->value.Simple->flags |= CMD_STDIN_REDIR;
843 
844 	line_number_for_err_trap = line_number = command->value.Simple->line;
845 	exec_result =
846 	  execute_simple_command (command->value.Simple, pipe_in, pipe_out,
847 				  asynchronous, fds_to_close);
848 	line_number = save_line_number;
849 
850 	/* The temporary environment should be used for only the simple
851 	   command immediately following its definition. */
852 	dispose_used_env_vars ();
853 
854 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
855 	/* Reclaim memory allocated with alloca () on machines which
856 	   may be using the alloca emulation code. */
857 	(void) alloca (0);
858 #endif /* (ultrix && mips) || C_ALLOCA */
859 
860 	/* If we forked to do the command, then we must wait_for ()
861 	   the child. */
862 
863 	/* XXX - this is something to watch out for if there are problems
864 	   when the shell is compiled without job control.  Don't worry about
865 	   whether or not last_made_pid == last_pid; already_making_children
866 	   tells us whether or not there are unwaited-for children to wait
867 	   for and reap. */
868 	if (already_making_children && pipe_out == NO_PIPE)
869 	  {
870 	    stop_pipeline (asynchronous, (COMMAND *)NULL);
871 
872 	    if (asynchronous)
873 	      {
874 		DESCRIBE_PID (last_made_pid);
875 		exec_result = EXECUTION_SUCCESS;
876 		invert = 0;		/* async commands always succeed */
877 	      }
878 	    else
879 #if !defined (JOB_CONTROL)
880 	      /* Do not wait for asynchronous processes started from
881 		 startup files. */
882 	    if (last_made_pid != NO_PID && last_made_pid != last_asynchronous_pid)
883 #else
884 	    if (last_made_pid != NO_PID)
885 #endif
886 	    /* When executing a shell function that executes other
887 	       commands, this causes the last simple command in
888 	       the function to be waited for twice.  This also causes
889 	       subshells forked to execute builtin commands (e.g., in
890 	       pipelines) to be waited for twice. */
891 	      exec_result = wait_for (last_made_pid, 0);
892 	  }
893       }
894 
895       /* 2009/02/13 -- pipeline failure is processed elsewhere.  This handles
896 	 only the failure of a simple command. We don't want to run the error
897 	 trap if the command run by the `command' builtin fails; we want to
898 	 defer that until the command builtin itself returns failure. */
899       /* 2020/07/14 -- this changes with how the command builtin is handled */
900       if (was_error_trap && ignore_return == 0 && invert == 0 &&
901 	    pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
902 	    (command->value.Simple->flags & CMD_COMMAND_BUILTIN) == 0 &&
903 	    exec_result != EXECUTION_SUCCESS)
904 	{
905 	  last_command_exit_value = exec_result;
906 	  line_number = line_number_for_err_trap;
907 	  run_error_trap ();
908 	  line_number = save_line_number;
909 	}
910 
911       if (ignore_return == 0 && invert == 0 &&
912 	  ((posixly_correct && interactive == 0 && special_builtin_failed) ||
913 	   (exit_immediately_on_error && pipe_in == NO_PIPE && pipe_out == NO_PIPE && exec_result != EXECUTION_SUCCESS)))
914 	{
915 	  last_command_exit_value = exec_result;
916 	  run_pending_traps ();
917 
918 	  /* Undo redirections before running exit trap on the way out of
919 	     set -e. Report by Mark Farrell 5/19/2014 */
920 	  if (exit_immediately_on_error && signal_is_trapped (0) &&
921 		unwind_protect_tag_on_stack ("saved-redirects"))
922 	    run_unwind_frame ("saved-redirects");
923 
924 	  jump_to_top_level (ERREXIT);
925 	}
926 
927       break;
928 
929     case cm_for:
930       if (ignore_return)
931 	command->value.For->flags |= CMD_IGNORE_RETURN;
932       exec_result = execute_for_command (command->value.For);
933       break;
934 
935 #if defined (ARITH_FOR_COMMAND)
936     case cm_arith_for:
937       if (ignore_return)
938 	command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
939       exec_result = execute_arith_for_command (command->value.ArithFor);
940       break;
941 #endif
942 
943 #if defined (SELECT_COMMAND)
944     case cm_select:
945       if (ignore_return)
946 	command->value.Select->flags |= CMD_IGNORE_RETURN;
947       exec_result = execute_select_command (command->value.Select);
948       break;
949 #endif
950 
951     case cm_case:
952       if (ignore_return)
953 	command->value.Case->flags |= CMD_IGNORE_RETURN;
954       exec_result = execute_case_command (command->value.Case);
955       break;
956 
957     case cm_while:
958       if (ignore_return)
959 	command->value.While->flags |= CMD_IGNORE_RETURN;
960       exec_result = execute_while_command (command->value.While);
961       break;
962 
963     case cm_until:
964       if (ignore_return)
965 	command->value.While->flags |= CMD_IGNORE_RETURN;
966       exec_result = execute_until_command (command->value.While);
967       break;
968 
969     case cm_if:
970       if (ignore_return)
971 	command->value.If->flags |= CMD_IGNORE_RETURN;
972       exec_result = execute_if_command (command->value.If);
973       break;
974 
975     case cm_group:
976 
977       /* This code can be executed from either of two paths: an explicit
978 	 '{}' command, or via a function call.  If we are executed via a
979 	 function call, we have already taken care of the function being
980 	 executed in the background (down there in execute_simple_command ()),
981 	 and this command should *not* be marked as asynchronous.  If we
982 	 are executing a regular '{}' group command, and asynchronous == 1,
983 	 we must want to execute the whole command in the background, so we
984 	 need a subshell, and we want the stuff executed in that subshell
985 	 (this group command) to be executed in the foreground of that
986 	 subshell (i.e. there will not be *another* subshell forked).
987 
988 	 What we do is to force a subshell if asynchronous, and then call
989 	 execute_command_internal again with asynchronous still set to 1,
990 	 but with the original group command, so the printed command will
991 	 look right.
992 
993 	 The code above that handles forking off subshells will note that
994 	 both subshell and async are on, and turn off async in the child
995 	 after forking the subshell (but leave async set in the parent, so
996 	 the normal call to describe_pid is made).  This turning off
997 	 async is *crucial*; if it is not done, this will fall into an
998 	 infinite loop of executions through this spot in subshell after
999 	 subshell until the process limit is exhausted. */
1000 
1001       if (asynchronous)
1002 	{
1003 	  command->flags |= CMD_FORCE_SUBSHELL;
1004 	  exec_result =
1005 	    execute_command_internal (command, 1, pipe_in, pipe_out,
1006 				      fds_to_close);
1007 	}
1008       else
1009 	{
1010 	  if (ignore_return && command->value.Group->command)
1011 	    command->value.Group->command->flags |= CMD_IGNORE_RETURN;
1012 	  exec_result =
1013 	    execute_command_internal (command->value.Group->command,
1014 				      asynchronous, pipe_in, pipe_out,
1015 				      fds_to_close);
1016 	}
1017       break;
1018 
1019     case cm_connection:
1020       exec_result = execute_connection (command, asynchronous,
1021 					pipe_in, pipe_out, fds_to_close);
1022       if (asynchronous)
1023 	invert = 0;		/* XXX */
1024 
1025       break;
1026 
1027 #if defined (DPAREN_ARITHMETIC)
1028     case cm_arith:
1029 #endif
1030 #if defined (COND_COMMAND)
1031     case cm_cond:
1032 #endif
1033     case cm_function_def:
1034       was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
1035 #if defined (DPAREN_ARITHMETIC)
1036       if (ignore_return && command->type == cm_arith)
1037 	command->value.Arith->flags |= CMD_IGNORE_RETURN;
1038 #endif
1039 #if defined (COND_COMMAND)
1040       if (ignore_return && command->type == cm_cond)
1041 	command->value.Cond->flags |= CMD_IGNORE_RETURN;
1042 #endif
1043 
1044       line_number_for_err_trap = save_line_number = line_number;
1045 #if defined (DPAREN_ARITHMETIC)
1046       if (command->type == cm_arith)
1047 	exec_result = execute_arith_command (command->value.Arith);
1048       else
1049 #endif
1050 #if defined (COND_COMMAND)
1051       if (command->type == cm_cond)
1052 	exec_result = execute_cond_command (command->value.Cond);
1053       else
1054 #endif
1055       if (command->type == cm_function_def)
1056 	exec_result = execute_intern_function (command->value.Function_def->name,
1057 					       command->value.Function_def);
1058       line_number = save_line_number;
1059 
1060       if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
1061 	{
1062 	  last_command_exit_value = exec_result;
1063 	  save_line_number = line_number;
1064 	  line_number = line_number_for_err_trap;
1065 	  run_error_trap ();
1066 	  line_number = save_line_number;
1067 	}
1068 
1069       if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
1070 	{
1071 	  last_command_exit_value = exec_result;
1072 	  run_pending_traps ();
1073 	  jump_to_top_level (ERREXIT);
1074 	}
1075 
1076       break;
1077 
1078     default:
1079       command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
1080     }
1081 
1082   if (my_undo_list)
1083     cleanup_redirects (my_undo_list);
1084 
1085   if (exec_undo_list)
1086     dispose_redirects (exec_undo_list);
1087 
1088   if (my_undo_list || exec_undo_list)
1089     discard_unwind_frame ("loop_redirections");
1090 
1091 #if defined (PROCESS_SUBSTITUTION)
1092   if (saved_fifo)
1093     {
1094       nfifo = num_fifos ();
1095       if (nfifo > ofifo)
1096 	close_new_fifos ((void *)ofifo_list, osize);
1097       free ((void *)ofifo_list);
1098       discard_unwind_frame ("internal_fifos");
1099     }
1100 #endif
1101 
1102   /* Invert the return value if we have to */
1103   if (invert)
1104     exec_result = (exec_result == EXECUTION_SUCCESS)
1105 		    ? EXECUTION_FAILURE
1106 		    : EXECUTION_SUCCESS;
1107 
1108 #if defined (DPAREN_ARITHMETIC) || defined (COND_COMMAND)
1109   /* This is where we set PIPESTATUS from the exit status of the appropriate
1110      compound commands (the ones that look enough like simple commands to
1111      cause confusion).  We might be able to optimize by not doing this if
1112      subshell_environment != 0. */
1113   switch (command->type)
1114     {
1115 #  if defined (DPAREN_ARITHMETIC)
1116     case cm_arith:
1117 #  endif
1118 #  if defined (COND_COMMAND)
1119     case cm_cond:
1120 #  endif
1121       set_pipestatus_from_exit (exec_result);
1122       break;
1123     default:
1124       break;
1125     }
1126 #endif
1127 
1128   last_command_exit_value = exec_result;
1129   run_pending_traps ();
1130   currently_executing_command = (COMMAND *)NULL;
1131 
1132   return (last_command_exit_value);
1133 }
1134 
1135 #if defined (COMMAND_TIMING)
1136 
1137 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1138 extern struct timeval *difftimeval PARAMS((struct timeval *, struct timeval *, struct timeval *));
1139 extern struct timeval *addtimeval PARAMS((struct timeval *, struct timeval *, struct timeval *));
1140 extern int timeval_to_cpu PARAMS((struct timeval *, struct timeval *, struct timeval *));
1141 #endif
1142 
1143 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
1144 #define BASH_TIMEFORMAT  "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
1145 
1146 static const int precs[] = { 0, 100, 10, 1 };
1147 
1148 /* Expand one `%'-prefixed escape sequence from a time format string. */
1149 static int
mkfmt(buf,prec,lng,sec,sec_fraction)1150 mkfmt (buf, prec, lng, sec, sec_fraction)
1151      char *buf;
1152      int prec, lng;
1153      time_t sec;
1154      int sec_fraction;
1155 {
1156   time_t min;
1157   char abuf[INT_STRLEN_BOUND(time_t) + 1];
1158   int ind, aind;
1159 
1160   ind = 0;
1161   abuf[sizeof(abuf) - 1] = '\0';
1162 
1163   /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1164   if (lng)
1165     {
1166       min = sec / 60;
1167       sec %= 60;
1168       aind = sizeof(abuf) - 2;
1169       do
1170 	abuf[aind--] = (min % 10) + '0';
1171       while (min /= 10);
1172       aind++;
1173       while (abuf[aind])
1174 	buf[ind++] = abuf[aind++];
1175       buf[ind++] = 'm';
1176     }
1177 
1178   /* Now add the seconds. */
1179   aind = sizeof (abuf) - 2;
1180   do
1181     abuf[aind--] = (sec % 10) + '0';
1182   while (sec /= 10);
1183   aind++;
1184   while (abuf[aind])
1185     buf[ind++] = abuf[aind++];
1186 
1187   /* We want to add a decimal point and PREC places after it if PREC is
1188      nonzero.  PREC is not greater than 3.  SEC_FRACTION is between 0
1189      and 999. */
1190   if (prec != 0)
1191     {
1192       buf[ind++] = locale_decpoint ();
1193       for (aind = 1; aind <= prec; aind++)
1194 	{
1195 	  buf[ind++] = (sec_fraction / precs[aind]) + '0';
1196 	  sec_fraction %= precs[aind];
1197 	}
1198     }
1199 
1200   if (lng)
1201     buf[ind++] = 's';
1202   buf[ind] = '\0';
1203 
1204   return (ind);
1205 }
1206 
1207 /* Interpret the format string FORMAT, interpolating the following escape
1208    sequences:
1209 		%[prec][l][RUS]
1210 
1211    where the optional `prec' is a precision, meaning the number of
1212    characters after the decimal point, the optional `l' means to format
1213    using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1214    and the last character is one of
1215 
1216 		R	number of seconds of `real' time
1217 		U	number of seconds of `user' time
1218 		S	number of seconds of `system' time
1219 
1220    An occurrence of `%%' in the format string is translated to a `%'.  The
1221    result is printed to FP, a pointer to a FILE.  The other variables are
1222    the seconds and thousandths of a second of real, user, and system time,
1223    resectively. */
1224 static void
print_formatted_time(fp,format,rs,rsf,us,usf,ss,ssf,cpu)1225 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1226      FILE *fp;
1227      char *format;
1228      time_t rs;
1229      int rsf;
1230      time_t us;
1231      int usf;
1232      time_t ss;
1233      int ssf, cpu;
1234 {
1235   int prec, lng, len;
1236   char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
1237   time_t sum;
1238   int sum_frac;
1239   int sindex, ssize;
1240 
1241   len = strlen (format);
1242   ssize = (len + 64) - (len % 64);
1243   str = (char *)xmalloc (ssize);
1244   sindex = 0;
1245 
1246   for (s = format; *s; s++)
1247     {
1248       if (*s != '%' || s[1] == '\0')
1249 	{
1250 	  RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1251 	  str[sindex++] = *s;
1252 	}
1253       else if (s[1] == '%')
1254 	{
1255 	  s++;
1256 	  RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1257 	  str[sindex++] = *s;
1258 	}
1259       else if (s[1] == 'P')
1260 	{
1261 	  s++;
1262 #if 0
1263 	  /* clamp CPU usage at 100% */
1264 	  if (cpu > 10000)
1265 	    cpu = 10000;
1266 #endif
1267 	  sum = cpu / 100;
1268 	  sum_frac = (cpu % 100) * 10;
1269 	  len = mkfmt (ts, 2, 0, sum, sum_frac);
1270 	  RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1271 	  strcpy (str + sindex, ts);
1272 	  sindex += len;
1273 	}
1274       else
1275 	{
1276 	  prec = 3;	/* default is three places past the decimal point. */
1277 	  lng = 0;	/* default is to not use minutes or append `s' */
1278 	  s++;
1279 	  if (DIGIT (*s))		/* `precision' */
1280 	    {
1281 	      prec = *s++ - '0';
1282 	      if (prec > 3) prec = 3;
1283 	    }
1284 	  if (*s == 'l')		/* `length extender' */
1285 	    {
1286 	      lng = 1;
1287 	      s++;
1288 	    }
1289 	  if (*s == 'R' || *s == 'E')
1290 	    len = mkfmt (ts, prec, lng, rs, rsf);
1291 	  else if (*s == 'U')
1292 	    len = mkfmt (ts, prec, lng, us, usf);
1293 	  else if (*s == 'S')
1294 	    len = mkfmt (ts, prec, lng, ss, ssf);
1295 	  else
1296 	    {
1297 	      internal_error (_("TIMEFORMAT: `%c': invalid format character"), *s);
1298 	      free (str);
1299 	      return;
1300 	    }
1301 	  RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1302 	  strcpy (str + sindex, ts);
1303 	  sindex += len;
1304 	}
1305     }
1306 
1307   str[sindex] = '\0';
1308   fprintf (fp, "%s\n", str);
1309   fflush (fp);
1310 
1311   free (str);
1312 }
1313 
1314 static int
time_command(command,asynchronous,pipe_in,pipe_out,fds_to_close)1315 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1316      COMMAND *command;
1317      int asynchronous, pipe_in, pipe_out;
1318      struct fd_bitmap *fds_to_close;
1319 {
1320   int rv, posix_time, old_flags, nullcmd, code;
1321   time_t rs, us, ss;
1322   int rsf, usf, ssf;
1323   int cpu;
1324   char *time_format;
1325   volatile procenv_t save_top_level;
1326 
1327 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1328   struct timeval real, user, sys;
1329   struct timeval before, after;
1330 #  if defined (HAVE_STRUCT_TIMEZONE)
1331   struct timezone dtz;				/* posix doesn't define this */
1332 #  endif
1333   struct rusage selfb, selfa, kidsb, kidsa;	/* a = after, b = before */
1334 #else
1335 #  if defined (HAVE_TIMES)
1336   clock_t tbefore, tafter, real, user, sys;
1337   struct tms before, after;
1338 #  endif
1339 #endif
1340 
1341 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1342 #  if defined (HAVE_STRUCT_TIMEZONE)
1343   gettimeofday (&before, &dtz);
1344 #  else
1345   gettimeofday (&before, (void *)NULL);
1346 #  endif /* !HAVE_STRUCT_TIMEZONE */
1347   getrusage (RUSAGE_SELF, &selfb);
1348   getrusage (RUSAGE_CHILDREN, &kidsb);
1349 #else
1350 #  if defined (HAVE_TIMES)
1351   tbefore = times (&before);
1352 #  endif
1353 #endif
1354 
1355   posix_time = command && (command->flags & CMD_TIME_POSIX);
1356 
1357   nullcmd = (command == 0) || (command->type == cm_simple && command->value.Simple->words == 0 && command->value.Simple->redirects == 0);
1358   if (posixly_correct && nullcmd)
1359     {
1360 #if defined (HAVE_GETRUSAGE)
1361       selfb.ru_utime.tv_sec = kidsb.ru_utime.tv_sec = selfb.ru_stime.tv_sec = kidsb.ru_stime.tv_sec = 0;
1362       selfb.ru_utime.tv_usec = kidsb.ru_utime.tv_usec = selfb.ru_stime.tv_usec = kidsb.ru_stime.tv_usec = 0;
1363       before = shellstart;
1364 #else
1365       before.tms_utime = before.tms_stime = before.tms_cutime = before.tms_cstime = 0;
1366       tbefore = shell_start_time;
1367 #endif
1368     }
1369 
1370   old_flags = command->flags;
1371   COPY_PROCENV (top_level, save_top_level);
1372   command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1373   code = setjmp_nosigs (top_level);
1374   if (code == NOT_JUMPED)
1375     {
1376       rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1377       command->flags = old_flags;
1378     }
1379   COPY_PROCENV (save_top_level, top_level);
1380 
1381   rs = us = ss = 0;
1382   rsf = usf = ssf = cpu = 0;
1383 
1384 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1385 #  if defined (HAVE_STRUCT_TIMEZONE)
1386   gettimeofday (&after, &dtz);
1387 #  else
1388   gettimeofday (&after, (void *)NULL);
1389 #  endif /* !HAVE_STRUCT_TIMEZONE */
1390   getrusage (RUSAGE_SELF, &selfa);
1391   getrusage (RUSAGE_CHILDREN, &kidsa);
1392 
1393   difftimeval (&real, &before, &after);
1394   timeval_to_secs (&real, &rs, &rsf);
1395 
1396   addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1397 		     difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1398   timeval_to_secs (&user, &us, &usf);
1399 
1400   addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1401 		    difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1402   timeval_to_secs (&sys, &ss, &ssf);
1403 
1404   cpu = timeval_to_cpu (&real, &user, &sys);
1405 #else
1406 #  if defined (HAVE_TIMES)
1407   tafter = times (&after);
1408 
1409   real = tafter - tbefore;
1410   clock_t_to_secs (real, &rs, &rsf);
1411 
1412   user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1413   clock_t_to_secs (user, &us, &usf);
1414 
1415   sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1416   clock_t_to_secs (sys, &ss, &ssf);
1417 
1418   cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1419 
1420 #  else
1421   rs = us = ss = 0;
1422   rsf = usf = ssf = cpu = 0;
1423 #  endif
1424 #endif
1425 
1426   if (posix_time)
1427     time_format = POSIX_TIMEFORMAT;
1428   else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1429     {
1430       if (posixly_correct && nullcmd)
1431 	time_format = "user\t%2lU\nsys\t%2lS";
1432       else
1433 	time_format = BASH_TIMEFORMAT;
1434     }
1435 
1436   if (time_format && *time_format)
1437     print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1438 
1439   if (code)
1440     sh_longjmp (top_level, code);
1441 
1442   return rv;
1443 }
1444 #endif /* COMMAND_TIMING */
1445 
1446 /* Execute a command that's supposed to be in a subshell.  This must be
1447    called after make_child and we must be running in the child process.
1448    The caller will return or exit() immediately with the value this returns. */
1449 static int
execute_in_subshell(command,asynchronous,pipe_in,pipe_out,fds_to_close)1450 execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1451      COMMAND *command;
1452      int asynchronous;
1453      int pipe_in, pipe_out;
1454      struct fd_bitmap *fds_to_close;
1455 {
1456   volatile int user_subshell, user_coproc, invert;
1457   int return_code, function_value, should_redir_stdin, ois, result;
1458   volatile COMMAND *tcom;
1459 
1460   USE_VAR(user_subshell);
1461   USE_VAR(user_coproc);
1462   USE_VAR(invert);
1463   USE_VAR(tcom);
1464   USE_VAR(asynchronous);
1465 
1466   subshell_level++;
1467   should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1468 			  pipe_in == NO_PIPE &&
1469 			  stdin_redirects (command->redirects) == 0);
1470 
1471   invert = (command->flags & CMD_INVERT_RETURN) != 0;
1472   user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
1473   user_coproc = command->type == cm_coproc;
1474 
1475   command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1476 
1477   /* If a command is asynchronous in a subshell (like ( foo ) & or
1478      the special case of an asynchronous GROUP command where the
1479      the subshell bit is turned on down in case cm_group: below),
1480      turn off `asynchronous', so that two subshells aren't spawned.
1481      XXX - asynchronous used to be set to 0 in this block, but that
1482      means that setup_async_signals was never run.  Now it's set to
1483      0 after subshell_environment is set appropriately and setup_async_signals
1484      is run.
1485 
1486      This seems semantically correct to me.  For example,
1487      ( foo ) & seems to say ``do the command `foo' in a subshell
1488      environment, but don't wait for that subshell to finish'',
1489      and "{ foo ; bar ; } &" seems to me to be like functions or
1490      builtins in the background, which executed in a subshell
1491      environment.  I just don't see the need to fork two subshells. */
1492 
1493   /* Don't fork again, we are already in a subshell.  A `doubly
1494      async' shell is not interactive, however. */
1495   if (asynchronous)
1496     {
1497 #if defined (JOB_CONTROL)
1498       /* If a construct like ( exec xxx yyy ) & is given while job
1499 	 control is active, we want to prevent exec from putting the
1500 	 subshell back into the original process group, carefully
1501 	 undoing all the work we just did in make_child. */
1502       original_pgrp = -1;
1503 #endif /* JOB_CONTROL */
1504       ois = interactive_shell;
1505       interactive_shell = 0;
1506       /* This test is to prevent alias expansion by interactive shells that
1507 	 run `(command) &' but to allow scripts that have enabled alias
1508 	 expansion with `shopt -s expand_alias' to continue to expand
1509 	 aliases. */
1510       if (ois != interactive_shell)
1511 	expand_aliases = 0;
1512     }
1513 
1514   /* Subshells are neither login nor interactive. */
1515   login_shell = interactive = 0;
1516 
1517   /* And we're no longer in a loop. See Posix interp 842 (we are not in the
1518      "same execution environment"). */
1519   if (shell_compatibility_level > 44)
1520     loop_level = 0;
1521 
1522   if (user_subshell)
1523     {
1524       subshell_environment = SUBSHELL_PAREN;	/* XXX */
1525       if (asynchronous)
1526 	subshell_environment |= SUBSHELL_ASYNC;
1527     }
1528   else
1529     {
1530       subshell_environment = 0;			/* XXX */
1531       if (asynchronous)
1532 	subshell_environment |= SUBSHELL_ASYNC;
1533       if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
1534 	subshell_environment |= SUBSHELL_PIPE;
1535       if (user_coproc)
1536 	subshell_environment |= SUBSHELL_COPROC;
1537     }
1538 
1539   QUIT;
1540   CHECK_TERMSIG;
1541 
1542   reset_terminating_signals ();		/* in sig.c */
1543   /* Cancel traps, in trap.c. */
1544   /* Reset the signal handlers in the child, but don't free the
1545      trap strings.  Set a flag noting that we have to free the
1546      trap strings if we run trap to change a signal disposition. */
1547   clear_pending_traps ();
1548   reset_signal_handlers ();
1549   subshell_environment |= SUBSHELL_RESETTRAP;
1550   /* Note that signal handlers have been reset, so we should no longer
1551     reset the handler and resend trapped signals to ourselves. */
1552   subshell_environment &= ~SUBSHELL_IGNTRAP;
1553 
1554   /* We are in a subshell, so forget that we are running a trap handler or
1555      that the signal handler has changed (we haven't changed it!) */
1556   if (running_trap > 0)
1557     {
1558       run_trap_cleanup (running_trap - 1);
1559       running_trap = 0;		/* XXX - maybe leave this */
1560     }
1561 
1562   /* Make sure restore_original_signals doesn't undo the work done by
1563      make_child to ensure that asynchronous children are immune to SIGINT
1564      and SIGQUIT.  Turn off asynchronous to make sure more subshells are
1565      not spawned. */
1566   if (asynchronous)
1567     {
1568       setup_async_signals ();
1569       asynchronous = 0;
1570     }
1571   else
1572     set_sigint_handler ();
1573 
1574 #if defined (JOB_CONTROL)
1575   set_sigchld_handler ();
1576 #endif /* JOB_CONTROL */
1577 
1578   /* Delete all traces that there were any jobs running.  This is
1579      only for subshells. */
1580   without_job_control ();
1581 
1582   if (fds_to_close)
1583     close_fd_bitmap (fds_to_close);
1584 
1585   do_piping (pipe_in, pipe_out);
1586 
1587 #if defined (COPROCESS_SUPPORT)
1588   coproc_closeall ();
1589 #endif
1590 
1591 #if defined (PROCESS_SUBSTITUTION)
1592   clear_fifo_list ();		/* XXX- we haven't created any FIFOs */
1593 #endif
1594 
1595   /* If this is a user subshell, set a flag if stdin was redirected.
1596      This is used later to decide whether to redirect fd 0 to
1597      /dev/null for async commands in the subshell.  This adds more
1598      sh compatibility, but I'm not sure it's the right thing to do.
1599      Note that an input pipe to a compound command suffices to inhibit
1600      the implicit /dev/null redirection for asynchronous commands
1601      executed as part of that compound command. */
1602   if (user_subshell)
1603     {
1604       stdin_redir = stdin_redirects (command->redirects) || pipe_in != NO_PIPE;
1605 #if 0
1606       restore_default_signal (EXIT_TRAP);	/* XXX - reset_signal_handlers above */
1607 #endif
1608     }
1609   else if (shell_control_structure (command->type) && pipe_in != NO_PIPE)
1610     stdin_redir = 1;
1611 
1612   /* If this is an asynchronous command (command &), we want to
1613      redirect the standard input from /dev/null in the absence of
1614      any specific redirection involving stdin. */
1615   if (should_redir_stdin && stdin_redir == 0)
1616     async_redirect_stdin ();
1617 
1618 #if defined (BUFFERED_INPUT)
1619   /* In any case, we are not reading our command input from stdin. */
1620   default_buffered_input = -1;
1621 #endif
1622 
1623 #if 0 /* TAG: bash-5.2 */
1624   if (user_subshell && command->type == cm_subshell)
1625     optimize_subshell_command (command->value.Subshell->command);
1626 #endif
1627 
1628   /* Do redirections, then dispose of them before recursive call. */
1629   if (command->redirects)
1630     {
1631       if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1632 	exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1633 
1634       dispose_redirects (command->redirects);
1635       command->redirects = (REDIRECT *)NULL;
1636     }
1637 
1638   if (command->type == cm_subshell)
1639     tcom = command->value.Subshell->command;
1640   else if (user_coproc)
1641     tcom = command->value.Coproc->command;
1642   else
1643     tcom = command;
1644 
1645   if (command->flags & CMD_TIME_PIPELINE)
1646     tcom->flags |= CMD_TIME_PIPELINE;
1647   if (command->flags & CMD_TIME_POSIX)
1648     tcom->flags |= CMD_TIME_POSIX;
1649 
1650   /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1651   if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1652     tcom->flags |= CMD_IGNORE_RETURN;
1653 
1654   /* If this is a simple command, tell execute_disk_command that it
1655      might be able to get away without forking and simply exec.
1656      This means things like ( sleep 10 ) will only cause one fork.
1657      If we're timing the command or inverting its return value, however,
1658      we cannot do this optimization. */
1659   if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1660       ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1661       ((tcom->flags & CMD_INVERT_RETURN) == 0))
1662     {
1663       tcom->flags |= CMD_NO_FORK;
1664       if (tcom->type == cm_simple)
1665 	tcom->value.Simple->flags |= CMD_NO_FORK;
1666     }
1667 
1668   invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1669   tcom->flags &= ~CMD_INVERT_RETURN;
1670 
1671   result = setjmp_nosigs (top_level);
1672 
1673   /* If we're inside a function while executing this subshell, we
1674      need to handle a possible `return'. */
1675   function_value = 0;
1676   if (return_catch_flag)
1677     function_value = setjmp_nosigs (return_catch);
1678 
1679   /* If we're going to exit the shell, we don't want to invert the return
1680      status. */
1681   if (result == EXITPROG)
1682     invert = 0, return_code = last_command_exit_value;
1683   else if (result)
1684     return_code = (last_command_exit_value == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : last_command_exit_value;
1685   else if (function_value)
1686     return_code = return_catch_value;
1687   else
1688     return_code = execute_command_internal ((COMMAND *)tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1689 
1690   /* If we are asked to, invert the return value. */
1691   if (invert)
1692     return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1693 						     : EXECUTION_SUCCESS;
1694 
1695 
1696   /* If we were explicitly placed in a subshell with (), we need
1697      to do the `shell cleanup' things, such as running traps[0]. */
1698   if (user_subshell && signal_is_trapped (0))
1699     {
1700       last_command_exit_value = return_code;
1701       return_code = run_exit_trap ();
1702     }
1703 
1704 #if 0
1705   subshell_level--;		/* don't bother, caller will just exit */
1706 #endif
1707   return (return_code);
1708   /* NOTREACHED */
1709 }
1710 
1711 #if defined (COPROCESS_SUPPORT)
1712 #define COPROC_MAX	16
1713 
1714 typedef struct cpelement
1715   {
1716     struct cpelement *next;
1717     struct coproc *coproc;
1718   }
1719 cpelement_t;
1720 
1721 typedef struct cplist
1722   {
1723     struct cpelement *head;
1724     struct cpelement *tail;
1725     int ncoproc;
1726     int lock;
1727   }
1728 cplist_t;
1729 
1730 static struct cpelement *cpe_alloc PARAMS((struct coproc *));
1731 static void cpe_dispose PARAMS((struct cpelement *));
1732 static struct cpelement *cpl_add PARAMS((struct coproc *));
1733 static struct cpelement *cpl_delete PARAMS((pid_t));
1734 static void cpl_reap PARAMS((void));
1735 static void cpl_flush PARAMS((void));
1736 static void cpl_closeall PARAMS((void));
1737 static struct cpelement *cpl_search PARAMS((pid_t));
1738 static struct cpelement *cpl_searchbyname PARAMS((const char *));
1739 static void cpl_prune PARAMS((void));
1740 
1741 static void coproc_free PARAMS((struct coproc *));
1742 
1743 /* Will go away when there is fully-implemented support for multiple coprocs. */
1744 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0, 0, 0, 0 };
1745 
1746 cplist_t coproc_list = {0, 0, 0};
1747 
1748 /* Functions to manage the list of coprocs */
1749 
1750 static struct cpelement *
cpe_alloc(cp)1751 cpe_alloc (cp)
1752      Coproc *cp;
1753 {
1754   struct cpelement *cpe;
1755 
1756   cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1757   cpe->coproc = cp;
1758   cpe->next = (struct cpelement *)0;
1759   return cpe;
1760 }
1761 
1762 static void
cpe_dispose(cpe)1763 cpe_dispose (cpe)
1764       struct cpelement *cpe;
1765 {
1766   free (cpe);
1767 }
1768 
1769 static struct cpelement *
cpl_add(cp)1770 cpl_add (cp)
1771      Coproc *cp;
1772 {
1773   struct cpelement *cpe;
1774 
1775   cpe = cpe_alloc (cp);
1776 
1777   if (coproc_list.head == 0)
1778     {
1779       coproc_list.head = coproc_list.tail = cpe;
1780       coproc_list.ncoproc = 0;			/* just to make sure */
1781     }
1782   else
1783     {
1784       coproc_list.tail->next = cpe;
1785       coproc_list.tail = cpe;
1786     }
1787   coproc_list.ncoproc++;
1788 
1789   return cpe;
1790 }
1791 
1792 static struct cpelement *
cpl_delete(pid)1793 cpl_delete (pid)
1794      pid_t pid;
1795 {
1796   struct cpelement *prev, *p;
1797 
1798   for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1799     if (p->coproc->c_pid == pid)
1800       {
1801         prev->next = p->next;	/* remove from list */
1802         break;
1803       }
1804 
1805   if (p == 0)
1806     return 0;		/* not found */
1807 
1808 #if defined (DEBUG)
1809   itrace("cpl_delete: deleting %d", pid);
1810 #endif
1811 
1812   /* Housekeeping in the border cases. */
1813   if (p == coproc_list.head)
1814     coproc_list.head = coproc_list.head->next;
1815   else if (p == coproc_list.tail)
1816     coproc_list.tail = prev;
1817 
1818   coproc_list.ncoproc--;
1819   if (coproc_list.ncoproc == 0)
1820     coproc_list.head = coproc_list.tail = 0;
1821   else if (coproc_list.ncoproc == 1)
1822     coproc_list.tail = coproc_list.head;		/* just to make sure */
1823 
1824   return (p);
1825 }
1826 
1827 static void
cpl_reap()1828 cpl_reap ()
1829 {
1830   struct cpelement *p, *next, *nh, *nt;
1831 
1832   /* Build a new list by removing dead coprocs and fix up the coproc_list
1833      pointers when done. */
1834   nh = nt = next = (struct cpelement *)0;
1835   for (p = coproc_list.head; p; p = next)
1836     {
1837       next = p->next;
1838       if (p->coproc->c_flags & COPROC_DEAD)
1839 	{
1840 	  coproc_list.ncoproc--;	/* keep running count, fix up pointers later */
1841 
1842 #if defined (DEBUG)
1843 	  itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1844 #endif
1845 
1846 	  coproc_dispose (p->coproc);
1847 	  cpe_dispose (p);
1848 	}
1849       else if (nh == 0)
1850 	nh = nt = p;
1851       else
1852 	{
1853 	  nt->next = p;
1854 	  nt = nt->next;
1855 	}
1856     }
1857 
1858   if (coproc_list.ncoproc == 0)
1859     coproc_list.head = coproc_list.tail = 0;
1860   else
1861     {
1862       if (nt)
1863         nt->next = 0;
1864       coproc_list.head = nh;
1865       coproc_list.tail = nt;
1866       if (coproc_list.ncoproc == 1)
1867 	coproc_list.tail = coproc_list.head;		/* just to make sure */
1868     }
1869 }
1870 
1871 /* Clear out the list of saved statuses */
1872 static void
cpl_flush()1873 cpl_flush ()
1874 {
1875   struct cpelement *cpe, *p;
1876 
1877   for (cpe = coproc_list.head; cpe; )
1878     {
1879       p = cpe;
1880       cpe = cpe->next;
1881 
1882       coproc_dispose (p->coproc);
1883       cpe_dispose (p);
1884     }
1885 
1886   coproc_list.head = coproc_list.tail = 0;
1887   coproc_list.ncoproc = 0;
1888 }
1889 
1890 static void
cpl_closeall()1891 cpl_closeall ()
1892 {
1893   struct cpelement *cpe;
1894 
1895   for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1896     coproc_close (cpe->coproc);
1897 }
1898 
1899 static void
cpl_fdchk(fd)1900 cpl_fdchk (fd)
1901      int fd;
1902 {
1903   struct cpelement *cpe;
1904 
1905   for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1906     coproc_checkfd (cpe->coproc, fd);
1907 }
1908 
1909 /* Search for PID in the list of coprocs; return the cpelement struct if
1910    found.  If not found, return NULL. */
1911 static struct cpelement *
cpl_search(pid)1912 cpl_search (pid)
1913      pid_t pid;
1914 {
1915   struct cpelement *cpe;
1916 
1917   for (cpe = coproc_list.head ; cpe; cpe = cpe->next)
1918     if (cpe->coproc->c_pid == pid)
1919       return cpe;
1920   return (struct cpelement *)NULL;
1921 }
1922 
1923 /* Search for the coproc named NAME in the list of coprocs; return the
1924    cpelement struct if found.  If not found, return NULL. */
1925 static struct cpelement *
cpl_searchbyname(name)1926 cpl_searchbyname (name)
1927      const char *name;
1928 {
1929   struct cpelement *cp;
1930 
1931   for (cp = coproc_list.head ; cp; cp = cp->next)
1932     if (STREQ (cp->coproc->c_name, name))
1933       return cp;
1934   return (struct cpelement *)NULL;
1935 }
1936 
1937 static pid_t
cpl_firstactive()1938 cpl_firstactive ()
1939 {
1940   struct cpelement *cpe;
1941 
1942   for (cpe = coproc_list.head ; cpe; cpe = cpe->next)
1943     if ((cpe->coproc->c_flags & COPROC_DEAD) == 0)
1944       return cpe->coproc->c_pid;
1945   return (pid_t)NO_PID;
1946 }
1947 
1948 #if 0
1949 static void
1950 cpl_prune ()
1951 {
1952   struct cpelement *cp;
1953 
1954   while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1955     {
1956       cp = coproc_list.head;
1957       coproc_list.head = coproc_list.head->next;
1958       coproc_dispose (cp->coproc);
1959       cpe_dispose (cp);
1960       coproc_list.ncoproc--;
1961     }
1962 }
1963 #endif
1964 
1965 /* These currently use a single global "shell coproc" but are written in a
1966    way to not preclude additional coprocs later (using the list management
1967    package above). */
1968 
1969 struct coproc *
getcoprocbypid(pid)1970 getcoprocbypid (pid)
1971      pid_t pid;
1972 {
1973 #if MULTIPLE_COPROCS
1974   struct cpelement *p;
1975 
1976   p = cpl_search (pid);
1977   return (p ? p->coproc : 0);
1978 #else
1979   return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1980 #endif
1981 }
1982 
1983 struct coproc *
getcoprocbyname(name)1984 getcoprocbyname (name)
1985      const char *name;
1986 {
1987 #if MULTIPLE_COPROCS
1988   struct cpelement *p;
1989 
1990   p = cpl_searchbyname (name);
1991   return (p ? p->coproc : 0);
1992 #else
1993   return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1994 #endif
1995 }
1996 
1997 void
coproc_init(cp)1998 coproc_init (cp)
1999      struct coproc *cp;
2000 {
2001   cp->c_name = 0;
2002   cp->c_pid = NO_PID;
2003   cp->c_rfd = cp->c_wfd = -1;
2004   cp->c_rsave = cp->c_wsave = -1;
2005   cp->c_flags = cp->c_status = cp->c_lock = 0;
2006 }
2007 
2008 struct coproc *
coproc_alloc(name,pid)2009 coproc_alloc (name, pid)
2010      char *name;
2011      pid_t pid;
2012 {
2013   struct coproc *cp;
2014 
2015 #if MULTIPLE_COPROCS
2016   cp = (struct coproc *)xmalloc (sizeof (struct coproc));
2017 #else
2018   cp = &sh_coproc;
2019 #endif
2020   coproc_init (cp);
2021   cp->c_lock = 2;
2022 
2023   cp->c_pid = pid;
2024   cp->c_name = savestring (name);
2025 #if MULTIPLE_COPROCS
2026   cpl_add (cp);
2027 #endif
2028   cp->c_lock = 0;
2029   return (cp);
2030 }
2031 
2032 static void
coproc_free(cp)2033 coproc_free (cp)
2034      struct coproc *cp;
2035 {
2036   free (cp);
2037 }
2038 
2039 void
coproc_dispose(cp)2040 coproc_dispose (cp)
2041      struct coproc *cp;
2042 {
2043   sigset_t set, oset;
2044 
2045   if (cp == 0)
2046     return;
2047 
2048   BLOCK_SIGNAL (SIGCHLD, set, oset);
2049   cp->c_lock = 3;
2050   coproc_unsetvars (cp);
2051   FREE (cp->c_name);
2052   coproc_close (cp);
2053 #if MULTIPLE_COPROCS
2054   coproc_free (cp);
2055 #else
2056   coproc_init (cp);
2057   cp->c_lock = 0;
2058 #endif
2059   UNBLOCK_SIGNAL (oset);
2060 }
2061 
2062 /* Placeholder for now.  Will require changes for multiple coprocs */
2063 void
coproc_flush()2064 coproc_flush ()
2065 {
2066 #if MULTIPLE_COPROCS
2067   cpl_flush ();
2068 #else
2069   coproc_dispose (&sh_coproc);
2070 #endif
2071 }
2072 
2073 void
coproc_close(cp)2074 coproc_close (cp)
2075      struct coproc *cp;
2076 {
2077   if (cp->c_rfd >= 0)
2078     {
2079       close (cp->c_rfd);
2080       cp->c_rfd = -1;
2081     }
2082   if (cp->c_wfd >= 0)
2083     {
2084       close (cp->c_wfd);
2085       cp->c_wfd = -1;
2086     }
2087   cp->c_rsave = cp->c_wsave = -1;
2088 }
2089 
2090 void
coproc_closeall()2091 coproc_closeall ()
2092 {
2093 #if MULTIPLE_COPROCS
2094   cpl_closeall ();
2095 #else
2096   coproc_close (&sh_coproc);	/* XXX - will require changes for multiple coprocs */
2097 #endif
2098 }
2099 
2100 void
coproc_reap()2101 coproc_reap ()
2102 {
2103 #if MULTIPLE_COPROCS
2104   cpl_reap ();
2105 #else
2106   struct coproc *cp;
2107 
2108   cp = &sh_coproc;		/* XXX - will require changes for multiple coprocs */
2109   if (cp && (cp->c_flags & COPROC_DEAD))
2110     coproc_dispose (cp);
2111 #endif
2112 }
2113 
2114 void
coproc_rclose(cp,fd)2115 coproc_rclose (cp, fd)
2116      struct coproc *cp;
2117      int fd;
2118 {
2119   if (cp->c_rfd >= 0 && cp->c_rfd == fd)
2120     {
2121       close (cp->c_rfd);
2122       cp->c_rfd = -1;
2123     }
2124 }
2125 
2126 void
coproc_wclose(cp,fd)2127 coproc_wclose (cp, fd)
2128      struct coproc *cp;
2129      int fd;
2130 {
2131   if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2132     {
2133       close (cp->c_wfd);
2134       cp->c_wfd = -1;
2135     }
2136 }
2137 
2138 void
coproc_checkfd(cp,fd)2139 coproc_checkfd (cp, fd)
2140      struct coproc *cp;
2141      int fd;
2142 {
2143   int update;
2144 
2145   update = 0;
2146   if (cp->c_rfd >= 0 && cp->c_rfd == fd)
2147     update = cp->c_rfd = -1;
2148   if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2149     update = cp->c_wfd = -1;
2150   if (update)
2151     coproc_setvars (cp);
2152 }
2153 
2154 void
coproc_fdchk(fd)2155 coproc_fdchk (fd)
2156      int fd;
2157 {
2158 #if MULTIPLE_COPROCS
2159   cpl_fdchk (fd);
2160 #else
2161   coproc_checkfd (&sh_coproc, fd);
2162 #endif
2163 }
2164 
2165 void
coproc_fdclose(cp,fd)2166 coproc_fdclose (cp, fd)
2167      struct coproc *cp;
2168      int fd;
2169 {
2170   coproc_rclose (cp, fd);
2171   coproc_wclose (cp, fd);
2172   coproc_setvars (cp);
2173 }
2174 
2175 void
coproc_fdsave(cp)2176 coproc_fdsave (cp)
2177      struct coproc *cp;
2178 {
2179   cp->c_rsave = cp->c_rfd;
2180   cp->c_wsave = cp->c_wfd;
2181 }
2182 
2183 void
coproc_fdrestore(cp)2184 coproc_fdrestore (cp)
2185      struct coproc *cp;
2186 {
2187   cp->c_rfd = cp->c_rsave;
2188   cp->c_wfd = cp->c_wsave;
2189 }
2190 
2191 static void
coproc_setstatus(cp,status)2192 coproc_setstatus (cp, status)
2193      struct coproc *cp;
2194      int status;
2195 {
2196   cp->c_lock = 4;
2197   cp->c_status = status;
2198   cp->c_flags |= COPROC_DEAD;
2199   cp->c_flags &= ~COPROC_RUNNING;
2200   /* Don't dispose the coproc or unset the COPROC_XXX variables because
2201      this is executed in a signal handler context.  Wait until coproc_reap
2202      takes care of it. */
2203   cp->c_lock = 0;
2204 }
2205 
2206 void
coproc_pidchk(pid,status)2207 coproc_pidchk (pid, status)
2208      pid_t pid;
2209      int status;
2210 {
2211   struct coproc *cp;
2212 
2213 #if MULTIPLE_COPROCS
2214   struct cpelement *cpe;
2215 
2216   /* We're not disposing the coproc because this is executed in a signal
2217      handler context */
2218   cpe = cpl_search (pid);
2219   cp = cpe ? cpe->coproc : 0;
2220 #else
2221   cp = getcoprocbypid (pid);
2222 #endif
2223   if (cp)
2224     coproc_setstatus (cp, status);
2225 }
2226 
2227 pid_t
coproc_active()2228 coproc_active ()
2229 {
2230 #if MULTIPLE_COPROCS
2231   return (cpl_firstactive ());
2232 #else
2233   return ((sh_coproc.c_flags & COPROC_DEAD) ? NO_PID : sh_coproc.c_pid);
2234 #endif
2235 }
2236 void
coproc_setvars(cp)2237 coproc_setvars (cp)
2238      struct coproc *cp;
2239 {
2240   SHELL_VAR *v;
2241   char *namevar, *t;
2242   int l;
2243   WORD_DESC w;
2244 #if defined (ARRAY_VARS)
2245   arrayind_t ind;
2246 #endif
2247 
2248   if (cp->c_name == 0)
2249     return;
2250 
2251   /* We could do more here but right now we only check the name, warn if it's
2252      not a valid identifier, and refuse to create variables with invalid names
2253      if a coproc with such a name is supplied. */
2254   w.word = cp->c_name;
2255   w.flags = 0;
2256   if (check_identifier (&w, 1) == 0)
2257     return;
2258 
2259   l = strlen (cp->c_name);
2260   namevar = xmalloc (l + 16);
2261 
2262 #if defined (ARRAY_VARS)
2263   v = find_variable (cp->c_name);
2264 
2265   /* This is the same code as in find_or_make_array_variable */
2266   if (v == 0)
2267     {
2268       v = find_variable_nameref_for_create (cp->c_name, 1);
2269       if (v == INVALID_NAMEREF_VALUE)
2270 	{
2271 	  free (namevar);
2272 	  return;
2273 	}
2274       if (v && nameref_p (v))
2275 	{
2276 	  free (cp->c_name);
2277 	  cp->c_name = savestring (nameref_cell (v));
2278 	  v = make_new_array_variable (cp->c_name);
2279 	}
2280     }
2281 
2282   if (v && (readonly_p (v) || noassign_p (v)))
2283     {
2284       if (readonly_p (v))
2285 	err_readonly (cp->c_name);
2286       free (namevar);
2287       return;
2288     }
2289   if (v == 0)
2290     v = make_new_array_variable (cp->c_name);
2291   if (array_p (v) == 0)
2292     v = convert_var_to_array (v);
2293 
2294   t = itos (cp->c_rfd);
2295   ind = 0;
2296   v = bind_array_variable (cp->c_name, ind, t, 0);
2297   free (t);
2298 
2299   t = itos (cp->c_wfd);
2300   ind = 1;
2301   v = bind_array_variable (cp->c_name, ind, t, 0);
2302   free (t);
2303 #else
2304   sprintf (namevar, "%s_READ", cp->c_name);
2305   t = itos (cp->c_rfd);
2306   bind_variable (namevar, t, 0);
2307   free (t);
2308   sprintf (namevar, "%s_WRITE", cp->c_name);
2309   t = itos (cp->c_wfd);
2310   bind_variable (namevar, t, 0);
2311   free (t);
2312 #endif
2313 
2314   sprintf (namevar, "%s_PID", cp->c_name);
2315   t = itos (cp->c_pid);
2316   v = bind_variable (namevar, t, 0);
2317   free (t);
2318 
2319   free (namevar);
2320 }
2321 
2322 void
coproc_unsetvars(cp)2323 coproc_unsetvars (cp)
2324      struct coproc *cp;
2325 {
2326   int l;
2327   char *namevar;
2328 
2329   if (cp->c_name == 0)
2330     return;
2331 
2332   l = strlen (cp->c_name);
2333   namevar = xmalloc (l + 16);
2334 
2335   sprintf (namevar, "%s_PID", cp->c_name);
2336   unbind_variable_noref (namevar);
2337 
2338 #if defined (ARRAY_VARS)
2339   check_unbind_variable (cp->c_name);
2340 #else
2341   sprintf (namevar, "%s_READ", cp->c_name);
2342   unbind_variable (namevar);
2343   sprintf (namevar, "%s_WRITE", cp->c_name);
2344   unbind_variable (namevar);
2345 #endif
2346 
2347   free (namevar);
2348 }
2349 
2350 static int
execute_coproc(command,pipe_in,pipe_out,fds_to_close)2351 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
2352      COMMAND *command;
2353      int pipe_in, pipe_out;
2354      struct fd_bitmap *fds_to_close;
2355 {
2356   int rpipe[2], wpipe[2], estat, invert;
2357   pid_t coproc_pid;
2358   Coproc *cp;
2359   char *tcmd, *p, *name;
2360   sigset_t set, oset;
2361 
2362   /* XXX -- can be removed after changes to handle multiple coprocs */
2363 #if !MULTIPLE_COPROCS
2364   if (sh_coproc.c_pid != NO_PID && (sh_coproc.c_rfd >= 0 || sh_coproc.c_wfd >= 0))
2365     internal_warning (_("execute_coproc: coproc [%d:%s] still exists"), sh_coproc.c_pid, sh_coproc.c_name);
2366   coproc_init (&sh_coproc);
2367 #endif
2368 
2369   invert = (command->flags & CMD_INVERT_RETURN) != 0;
2370 
2371   /* expand name without splitting - could make this dependent on a shopt option */
2372   name = expand_string_unsplit_to_string (command->value.Coproc->name, 0);
2373   /* Optional check -- could be relaxed */
2374   if (legal_identifier (name) == 0)
2375     {
2376       internal_error (_("`%s': not a valid identifier"), name);
2377       return (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
2378     }
2379   else
2380     {
2381       free (command->value.Coproc->name);
2382       command->value.Coproc->name = name;
2383     }
2384 
2385   command_string_index = 0;
2386   tcmd = make_command_string (command);
2387 
2388   sh_openpipe ((int *)&rpipe);	/* 0 = parent read, 1 = child write */
2389   sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2390 
2391   BLOCK_SIGNAL (SIGCHLD, set, oset);
2392 
2393   coproc_pid = make_child (p = savestring (tcmd), FORK_ASYNC);
2394 
2395   if (coproc_pid == 0)
2396     {
2397       close (rpipe[0]);
2398       close (wpipe[1]);
2399 
2400 #if defined (JOB_CONTROL)
2401       FREE (p);
2402 #endif
2403 
2404       UNBLOCK_SIGNAL (oset);
2405       estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2406 
2407       fflush (stdout);
2408       fflush (stderr);
2409 
2410       exit (estat);
2411     }
2412 
2413   close (rpipe[1]);
2414   close (wpipe[0]);
2415 
2416   cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2417   cp->c_rfd = rpipe[0];
2418   cp->c_wfd = wpipe[1];
2419 
2420   cp->c_flags |= COPROC_RUNNING;
2421 
2422   SET_CLOSE_ON_EXEC (cp->c_rfd);
2423   SET_CLOSE_ON_EXEC (cp->c_wfd);
2424 
2425   coproc_setvars (cp);
2426 
2427   UNBLOCK_SIGNAL (oset);
2428 
2429 #if 0
2430   itrace ("execute_coproc (%s): [%d] %s", command->value.Coproc->name, coproc_pid, the_printed_command);
2431 #endif
2432 
2433   close_pipes (pipe_in, pipe_out);
2434 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2435   unlink_fifo_list ();
2436 #endif
2437   stop_pipeline (1, (COMMAND *)NULL);
2438   DESCRIBE_PID (coproc_pid);
2439   run_pending_traps ();
2440 
2441   return (invert ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2442 }
2443 #endif
2444 
2445 static void
restore_stdin(s)2446 restore_stdin (s)
2447      int s;
2448 {
2449   dup2 (s, 0);
2450   close (s);
2451 }
2452 
2453 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2454 static void
lastpipe_cleanup(s)2455 lastpipe_cleanup (s)
2456      int s;
2457 {
2458   set_jobs_list_frozen (s);
2459 }
2460 
2461 static int
execute_pipeline(command,asynchronous,pipe_in,pipe_out,fds_to_close)2462 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2463      COMMAND *command;
2464      int asynchronous, pipe_in, pipe_out;
2465      struct fd_bitmap *fds_to_close;
2466 {
2467   int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2468   int lstdin, lastpipe_flag, lastpipe_jid, old_frozen;
2469   COMMAND *cmd;
2470   struct fd_bitmap *fd_bitmap;
2471   pid_t lastpid;
2472 
2473 #if defined (JOB_CONTROL)
2474   sigset_t set, oset;
2475   BLOCK_CHILD (set, oset);
2476 #endif /* JOB_CONTROL */
2477 
2478   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2479 
2480   prev = pipe_in;
2481   cmd = command;
2482 
2483   while (cmd && cmd->type == cm_connection &&
2484 	 cmd->value.Connection && cmd->value.Connection->connector == '|')
2485     {
2486       /* Make a pipeline between the two commands. */
2487       if (pipe (fildes) < 0)
2488 	{
2489 	  sys_error (_("pipe error"));
2490 #if defined (JOB_CONTROL)
2491 	  terminate_current_pipeline ();
2492 	  kill_current_pipeline ();
2493 	  UNBLOCK_CHILD (oset);
2494 #endif /* JOB_CONTROL */
2495 	  last_command_exit_value = EXECUTION_FAILURE;
2496 	  /* The unwind-protects installed below will take care
2497 	     of closing all of the open file descriptors. */
2498 	  throw_to_top_level ();
2499 	  return (EXECUTION_FAILURE);	/* XXX */
2500 	}
2501 
2502       /* Here is a problem: with the new file close-on-exec
2503 	 code, the read end of the pipe (fildes[0]) stays open
2504 	 in the first process, so that process will never get a
2505 	 SIGPIPE.  There is no way to signal the first process
2506 	 that it should close fildes[0] after forking, so it
2507 	 remains open.  No SIGPIPE is ever sent because there
2508 	 is still a file descriptor open for reading connected
2509 	 to the pipe.  We take care of that here.  This passes
2510 	 around a bitmap of file descriptors that must be
2511 	 closed after making a child process in execute_simple_command. */
2512 
2513       /* We need fd_bitmap to be at least as big as fildes[0].
2514 	 If fildes[0] is less than fds_to_close->size, then
2515 	 use fds_to_close->size. */
2516       new_bitmap_size = (fildes[0] < fds_to_close->size)
2517 				? fds_to_close->size
2518 				: fildes[0] + 8;
2519 
2520       fd_bitmap = new_fd_bitmap (new_bitmap_size);
2521 
2522       /* Now copy the old information into the new bitmap. */
2523       xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2524 
2525       /* And mark the pipe file descriptors to be closed. */
2526       fd_bitmap->bitmap[fildes[0]] = 1;
2527 
2528       /* In case there are pipe or out-of-processes errors, we
2529 	 want all these file descriptors to be closed when
2530 	 unwind-protects are run, and the storage used for the
2531 	 bitmaps freed up. */
2532       begin_unwind_frame ("pipe-file-descriptors");
2533       add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2534       add_unwind_protect (close_fd_bitmap, fd_bitmap);
2535       if (prev >= 0)
2536 	add_unwind_protect (close, prev);
2537       dummyfd = fildes[1];
2538       add_unwind_protect (close, dummyfd);
2539 
2540 #if defined (JOB_CONTROL)
2541       add_unwind_protect (restore_signal_mask, &oset);
2542 #endif /* JOB_CONTROL */
2543 
2544       if (ignore_return && cmd->value.Connection->first)
2545 	cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2546       execute_command_internal (cmd->value.Connection->first, asynchronous,
2547 				prev, fildes[1], fd_bitmap);
2548 
2549       if (prev >= 0)
2550 	close (prev);
2551 
2552       prev = fildes[0];
2553       close (fildes[1]);
2554 
2555       dispose_fd_bitmap (fd_bitmap);
2556       discard_unwind_frame ("pipe-file-descriptors");
2557 
2558       cmd = cmd->value.Connection->second;
2559     }
2560 
2561   lastpid = last_made_pid;
2562 
2563   /* Now execute the rightmost command in the pipeline.  */
2564   if (ignore_return && cmd)
2565     cmd->flags |= CMD_IGNORE_RETURN;
2566 
2567   lastpipe_flag = 0;
2568 
2569   begin_unwind_frame ("lastpipe-exec");
2570   lstdin = -1;
2571   /* If the `lastpipe' option is set with shopt, and job control is not
2572      enabled, execute the last element of non-async pipelines in the
2573      current shell environment. */
2574   if (lastpipe_opt && job_control == 0 && asynchronous == 0 && pipe_out == NO_PIPE && prev > 0)
2575     {
2576       lstdin = move_to_high_fd (0, 1, -1);
2577       if (lstdin > 0)
2578 	{
2579 	  do_piping (prev, pipe_out);
2580 	  prev = NO_PIPE;
2581 	  add_unwind_protect (restore_stdin, lstdin);
2582 	  lastpipe_flag = 1;
2583 	  old_frozen = freeze_jobs_list ();
2584 	  lastpipe_jid = stop_pipeline (0, (COMMAND *)NULL);	/* XXX */
2585 	  add_unwind_protect (lastpipe_cleanup, old_frozen);
2586 #if defined (JOB_CONTROL)
2587 	  UNBLOCK_CHILD (oset);		/* XXX */
2588 #endif
2589 	}
2590       if (cmd)
2591 	cmd->flags |= CMD_LASTPIPE;
2592     }
2593   if (prev >= 0)
2594     add_unwind_protect (close, prev);
2595 
2596   exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2597 
2598   if (lstdin > 0)
2599     restore_stdin (lstdin);
2600 
2601   if (prev >= 0)
2602     close (prev);
2603 
2604 #if defined (JOB_CONTROL)
2605   UNBLOCK_CHILD (oset);
2606 #endif
2607 
2608   QUIT;
2609 
2610   if (lastpipe_flag)
2611     {
2612 #if defined (JOB_CONTROL)
2613       if (INVALID_JOB (lastpipe_jid) == 0)
2614         {
2615           append_process (savestring (the_printed_command_except_trap), dollar_dollar_pid, exec_result, lastpipe_jid);
2616           lstdin = wait_for (lastpid, 0);
2617         }
2618       else
2619         lstdin = wait_for_single_pid (lastpid, 0);		/* checks bgpids list */
2620 #else
2621       lstdin = wait_for (lastpid, 0);
2622 #endif
2623 
2624 #if defined (JOB_CONTROL)
2625       /* If wait_for removes the job from the jobs table, use result of last
2626 	 command as pipeline's exit status as usual.  The jobs list can get
2627 	 frozen and unfrozen at inconvenient times if there are multiple pipelines
2628 	 running simultaneously. */
2629       if (INVALID_JOB (lastpipe_jid) == 0)
2630 	exec_result = job_exit_status (lastpipe_jid);
2631       else if (pipefail_opt)
2632 	exec_result = exec_result | lstdin;	/* XXX */
2633       /* otherwise we use exec_result */
2634 #endif
2635 
2636       set_jobs_list_frozen (old_frozen);
2637     }
2638 
2639   discard_unwind_frame ("lastpipe-exec");
2640 
2641   return (exec_result);
2642 }
2643 
2644 static int
execute_connection(command,asynchronous,pipe_in,pipe_out,fds_to_close)2645 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2646      COMMAND *command;
2647      int asynchronous, pipe_in, pipe_out;
2648      struct fd_bitmap *fds_to_close;
2649 {
2650   COMMAND *tc, *second;
2651   int ignore_return, exec_result, was_error_trap, invert;
2652   volatile int save_line_number;
2653 
2654   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2655 
2656   switch (command->value.Connection->connector)
2657     {
2658     /* Do the first command asynchronously. */
2659     case '&':
2660       tc = command->value.Connection->first;
2661       if (tc == 0)
2662 	return (EXECUTION_SUCCESS);
2663 
2664       if (ignore_return)
2665 	tc->flags |= CMD_IGNORE_RETURN;
2666       tc->flags |= CMD_AMPERSAND;
2667 
2668       /* If this shell was compiled without job control support,
2669 	 if we are currently in a subshell via `( xxx )', or if job
2670 	 control is not active then the standard input for an
2671 	 asynchronous command is forced to /dev/null. */
2672 #if defined (JOB_CONTROL)
2673       if ((subshell_environment || !job_control) && !stdin_redir)
2674 #else
2675       if (!stdin_redir)
2676 #endif /* JOB_CONTROL */
2677 	tc->flags |= CMD_STDIN_REDIR;
2678 
2679       exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2680       QUIT;
2681 
2682       if (tc->flags & CMD_STDIN_REDIR)
2683 	tc->flags &= ~CMD_STDIN_REDIR;
2684 
2685       second = command->value.Connection->second;
2686       if (second)
2687 	{
2688 	  if (ignore_return)
2689 	    second->flags |= CMD_IGNORE_RETURN;
2690 
2691 	  exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2692 	}
2693 
2694       break;
2695 
2696     /* Just call execute command on both sides. */
2697     case ';':
2698       if (ignore_return)
2699 	{
2700 	  if (command->value.Connection->first)
2701 	    command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2702 	  if (command->value.Connection->second)
2703 	    command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2704 	}
2705       executing_list++;
2706       QUIT;
2707 
2708 #if 1
2709       execute_command (command->value.Connection->first);
2710 #else
2711       execute_command_internal (command->value.Connection->first,
2712 				  asynchronous, pipe_in, pipe_out,
2713 				  fds_to_close);
2714 #endif
2715 
2716       QUIT;
2717       optimize_fork (command);			/* XXX */
2718       exec_result = execute_command_internal (command->value.Connection->second,
2719 				      asynchronous, pipe_in, pipe_out,
2720 				      fds_to_close);
2721       executing_list--;
2722       break;
2723 
2724     case '|':
2725       was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2726       invert = (command->flags & CMD_INVERT_RETURN) != 0;
2727       ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2728 
2729       line_number_for_err_trap = line_number;	/* XXX - save value? */
2730       exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2731 
2732       if (asynchronous)
2733 	{
2734 	  exec_result = EXECUTION_SUCCESS;
2735 	  invert = 0;
2736 	}
2737 
2738       if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2739 	{
2740 	  last_command_exit_value = exec_result;
2741 	  save_line_number = line_number;
2742 	  line_number = line_number_for_err_trap;
2743 	  run_error_trap ();
2744 	  line_number = save_line_number;
2745 	}
2746 
2747       if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2748 	{
2749 	  last_command_exit_value = exec_result;
2750 	  run_pending_traps ();
2751 	  jump_to_top_level (ERREXIT);
2752 	}
2753 
2754       break;
2755 
2756     case AND_AND:
2757     case OR_OR:
2758       if (asynchronous)
2759 	{
2760 	  /* If we have something like `a && b &' or `a || b &', run the
2761 	     && or || stuff in a subshell.  Force a subshell and just call
2762 	     execute_command_internal again.  Leave asynchronous on
2763 	     so that we get a report from the parent shell about the
2764 	     background job. */
2765 	  command->flags |= CMD_FORCE_SUBSHELL;
2766 	  exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2767 	  break;
2768 	}
2769 
2770       /* Execute the first command.  If the result of that is successful
2771 	 and the connector is AND_AND, or the result is not successful
2772 	 and the connector is OR_OR, then execute the second command,
2773 	 otherwise return. */
2774 
2775       executing_list++;
2776       if (command->value.Connection->first)
2777 	command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2778 
2779 #if 1
2780       exec_result = execute_command (command->value.Connection->first);
2781 #else
2782       exec_result = execute_command_internal (command->value.Connection->first, 0, NO_PIPE, NO_PIPE, fds_to_close);
2783 #endif
2784       QUIT;
2785       if (((command->value.Connection->connector == AND_AND) &&
2786 	   (exec_result == EXECUTION_SUCCESS)) ||
2787 	  ((command->value.Connection->connector == OR_OR) &&
2788 	   (exec_result != EXECUTION_SUCCESS)))
2789 	{
2790 	  optimize_fork (command);
2791 
2792 	  second = command->value.Connection->second;
2793 	  if (ignore_return && second)
2794 	    second->flags |= CMD_IGNORE_RETURN;
2795 
2796 	  exec_result = execute_command (second);
2797 	}
2798       executing_list--;
2799       break;
2800 
2801     default:
2802       command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2803       jump_to_top_level (DISCARD);
2804       exec_result = EXECUTION_FAILURE;
2805     }
2806 
2807   return exec_result;
2808 }
2809 
2810 /* The test used to be only for interactive_shell, but we don't want to report
2811    job status when the shell is not interactive or when job control isn't
2812    enabled. */
2813 #define REAP() \
2814   do \
2815     { \
2816       if (job_control == 0 || interactive_shell == 0) \
2817 	reap_dead_jobs (); \
2818     } \
2819   while (0)
2820 
2821 /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
2822    DO command; DONE */
2823 static int
execute_for_command(for_command)2824 execute_for_command (for_command)
2825      FOR_COM *for_command;
2826 {
2827   register WORD_LIST *releaser, *list;
2828   SHELL_VAR *v;
2829   char *identifier;
2830   int retval, save_line_number;
2831 #if 0
2832   SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2833 #endif
2834 
2835   save_line_number = line_number;
2836   if (check_identifier (for_command->name, 1) == 0)
2837     {
2838       if (posixly_correct && interactive_shell == 0)
2839 	{
2840 	  last_command_exit_value = EX_BADUSAGE;
2841 	  jump_to_top_level (ERREXIT);
2842 	}
2843       return (EXECUTION_FAILURE);
2844     }
2845 
2846   loop_level++;
2847   identifier = for_command->name->word;
2848 
2849   line_number = for_command->line;	/* for expansion error messages */
2850   list = releaser = expand_words_no_vars (for_command->map_list);
2851 
2852   begin_unwind_frame ("for");
2853   add_unwind_protect (dispose_words, releaser);
2854 
2855 #if 0
2856   if (lexical_scoping)
2857     {
2858       old_value = copy_variable (find_variable (identifier));
2859       if (old_value)
2860 	add_unwind_protect (dispose_variable, old_value);
2861     }
2862 #endif
2863 
2864   if (for_command->flags & CMD_IGNORE_RETURN)
2865     for_command->action->flags |= CMD_IGNORE_RETURN;
2866 
2867   for (retval = EXECUTION_SUCCESS; list; list = list->next)
2868     {
2869       QUIT;
2870 
2871       line_number = for_command->line;
2872 
2873       /* Remember what this command looks like, for debugger. */
2874       command_string_index = 0;
2875       print_for_command_head (for_command);
2876 
2877       if (echo_command_at_execute)
2878 	xtrace_print_for_command_head (for_command);
2879 
2880       /* Save this command unless it's a trap command and we're not running
2881 	 a debug trap. */
2882       if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2883 	{
2884 	  FREE (the_printed_command_except_trap);
2885 	  the_printed_command_except_trap = savestring (the_printed_command);
2886 	}
2887 
2888       retval = run_debug_trap ();
2889 #if defined (DEBUGGER)
2890       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2891 	 skip the command. */
2892       if (debugging_mode && retval != EXECUTION_SUCCESS)
2893         continue;
2894 #endif
2895 
2896       this_command_name = (char *)NULL;
2897       /* XXX - special ksh93 for command index variable handling */
2898       v = find_variable_last_nameref (identifier, 1);
2899       if (v && nameref_p (v))
2900 	{
2901 	  if (valid_nameref_value (list->word->word, 1) == 0)
2902 	    {
2903 	      sh_invalidid (list->word->word);
2904 	      v = 0;
2905 	    }
2906 	  else if (readonly_p (v))
2907 	    err_readonly (name_cell (v));
2908 	  else
2909 	    v = bind_variable_value (v, list->word->word, ASS_NAMEREF);
2910 	}
2911       else
2912 	v = bind_variable (identifier, list->word->word, 0);
2913 
2914       if (v == 0 || readonly_p (v) || noassign_p (v))
2915 	{
2916 	  line_number = save_line_number;
2917 	  if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
2918 	    {
2919 	      last_command_exit_value = EXECUTION_FAILURE;
2920 	      jump_to_top_level (FORCE_EOF);
2921 	    }
2922 	  else
2923 	    {
2924 	      dispose_words (releaser);
2925 	      discard_unwind_frame ("for");
2926 	      loop_level--;
2927 	      return (EXECUTION_FAILURE);
2928 	    }
2929 	}
2930 
2931       if (ifsname (identifier))
2932 	setifs (v);
2933       else
2934 	stupidly_hack_special_variables (identifier);
2935 
2936       retval = execute_command (for_command->action);
2937       REAP ();
2938       QUIT;
2939 
2940       if (breaking)
2941 	{
2942 	  breaking--;
2943 	  break;
2944 	}
2945 
2946       if (continuing)
2947 	{
2948 	  continuing--;
2949 	  if (continuing)
2950 	    break;
2951 	}
2952     }
2953 
2954   loop_level--;
2955   line_number = save_line_number;
2956 
2957 #if 0
2958   if (lexical_scoping)
2959     {
2960       if (!old_value)
2961         unbind_variable (identifier);
2962       else
2963 	{
2964 	  SHELL_VAR *new_value;
2965 
2966 	  new_value = bind_variable (identifier, value_cell (old_value), 0);
2967 	  new_value->attributes = old_value->attributes;
2968 	  dispose_variable (old_value);
2969 	}
2970     }
2971 #endif
2972 
2973   dispose_words (releaser);
2974   discard_unwind_frame ("for");
2975   return (retval);
2976 }
2977 
2978 #if defined (ARITH_FOR_COMMAND)
2979 /* Execute an arithmetic for command.  The syntax is
2980 
2981 	for (( init ; step ; test ))
2982 	do
2983 		body
2984 	done
2985 
2986    The execution should be exactly equivalent to
2987 
2988 	eval \(\( init \)\)
2989 	while eval \(\( test \)\) ; do
2990 		body;
2991 		eval \(\( step \)\)
2992 	done
2993 */
2994 static intmax_t
eval_arith_for_expr(l,okp)2995 eval_arith_for_expr (l, okp)
2996      WORD_LIST *l;
2997      int *okp;
2998 {
2999   WORD_LIST *new;
3000   intmax_t expresult;
3001   int r;
3002 
3003   new = expand_words_no_vars (l);
3004   if (new)
3005     {
3006       if (echo_command_at_execute)
3007 	xtrace_print_arith_cmd (new);
3008       this_command_name = "((";		/* )) for expression error messages */
3009 
3010       command_string_index = 0;
3011       print_arith_command (new);
3012       if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3013 	{
3014 	  FREE (the_printed_command_except_trap);
3015 	  the_printed_command_except_trap = savestring (the_printed_command);
3016 	}
3017 
3018       r = run_debug_trap ();
3019       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3020 	 skip the command. */
3021 #if defined (DEBUGGER)
3022       if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
3023 	expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
3024       else
3025 	{
3026 	  expresult = 0;
3027 	  if (okp)
3028 	    *okp = 1;
3029 	}
3030 #else
3031       expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
3032 #endif
3033       dispose_words (new);
3034     }
3035   else
3036     {
3037       expresult = 0;
3038       if (okp)
3039 	*okp = 1;
3040     }
3041   return (expresult);
3042 }
3043 
3044 static int
execute_arith_for_command(arith_for_command)3045 execute_arith_for_command (arith_for_command)
3046      ARITH_FOR_COM *arith_for_command;
3047 {
3048   intmax_t expresult;
3049   int expok, body_status, arith_lineno, save_lineno;
3050 
3051   body_status = EXECUTION_SUCCESS;
3052   loop_level++;
3053   save_lineno = line_number;
3054 
3055   if (arith_for_command->flags & CMD_IGNORE_RETURN)
3056     arith_for_command->action->flags |= CMD_IGNORE_RETURN;
3057 
3058   this_command_name = "((";	/* )) for expression error messages */
3059 
3060   /* save the starting line number of the command so we can reset
3061      line_number before executing each expression -- for $LINENO
3062      and the DEBUG trap. */
3063   line_number = arith_lineno = arith_for_command->line;
3064   if (variable_context && interactive_shell && sourcelevel == 0)
3065     {
3066       /* line numbers in a function start at 1 */
3067       line_number -= function_line_number - 1;
3068       if (line_number <= 0)
3069 	line_number = 1;
3070     }
3071 
3072   /* Evaluate the initialization expression. */
3073   expresult = eval_arith_for_expr (arith_for_command->init, &expok);
3074   if (expok == 0)
3075     {
3076       line_number = save_lineno;
3077       return (EXECUTION_FAILURE);
3078     }
3079 
3080   while (1)
3081     {
3082       /* Evaluate the test expression. */
3083       line_number = arith_lineno;
3084       expresult = eval_arith_for_expr (arith_for_command->test, &expok);
3085       line_number = save_lineno;
3086 
3087       if (expok == 0)
3088 	{
3089 	  body_status = EXECUTION_FAILURE;
3090 	  break;
3091 	}
3092       REAP ();
3093       if (expresult == 0)
3094 	break;
3095 
3096       /* Execute the body of the arithmetic for command. */
3097       QUIT;
3098       body_status = execute_command (arith_for_command->action);
3099       QUIT;
3100 
3101       /* Handle any `break' or `continue' commands executed by the body. */
3102       if (breaking)
3103 	{
3104 	  breaking--;
3105 	  break;
3106 	}
3107 
3108       if (continuing)
3109 	{
3110 	  continuing--;
3111 	  if (continuing)
3112 	    break;
3113 	}
3114 
3115       /* Evaluate the step expression. */
3116       line_number = arith_lineno;
3117       expresult = eval_arith_for_expr (arith_for_command->step, &expok);
3118       line_number = save_lineno;
3119 
3120       if (expok == 0)
3121 	{
3122 	  body_status = EXECUTION_FAILURE;
3123 	  break;
3124 	}
3125     }
3126 
3127   loop_level--;
3128   line_number = save_lineno;
3129 
3130   return (body_status);
3131 }
3132 #endif
3133 
3134 #if defined (SELECT_COMMAND)
3135 static int LINES, COLS, tabsize;
3136 
3137 #define RP_SPACE ") "
3138 #define RP_SPACE_LEN 2
3139 
3140 /* XXX - does not handle numbers > 1000000 at all. */
3141 #define NUMBER_LEN(s) \
3142 ((s < 10) ? 1 \
3143 	  : ((s < 100) ? 2 \
3144 		      : ((s < 1000) ? 3 \
3145 				   : ((s < 10000) ? 4 \
3146 						 : ((s < 100000) ? 5 \
3147 								: 6)))))
3148 
3149 static int
displen(s)3150 displen (s)
3151      const char *s;
3152 {
3153 #if defined (HANDLE_MULTIBYTE)
3154   wchar_t *wcstr;
3155   size_t slen;
3156   int wclen;
3157 
3158   wcstr = 0;
3159   slen = mbstowcs (wcstr, s, 0);
3160   if (slen == -1)
3161     slen = 0;
3162   wcstr = (wchar_t *)xmalloc (sizeof (wchar_t) * (slen + 1));
3163   mbstowcs (wcstr, s, slen + 1);
3164   wclen = wcswidth (wcstr, slen);
3165   free (wcstr);
3166   return (wclen < 0 ? STRLEN(s) : wclen);
3167 #else
3168   return (STRLEN (s));
3169 #endif
3170 }
3171 
3172 static int
print_index_and_element(len,ind,list)3173 print_index_and_element (len, ind, list)
3174       int len, ind;
3175       WORD_LIST *list;
3176 {
3177   register WORD_LIST *l;
3178   register int i;
3179 
3180   if (list == 0)
3181     return (0);
3182   for (i = ind, l = list; l && --i; l = l->next)
3183     ;
3184   if (l == 0)		/* don't think this can happen */
3185     return (0);
3186   fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
3187   return (displen (l->word->word));
3188 }
3189 
3190 static void
indent(from,to)3191 indent (from, to)
3192      int from, to;
3193 {
3194   while (from < to)
3195     {
3196       if ((to / tabsize) > (from / tabsize))
3197 	{
3198 	  putc ('\t', stderr);
3199 	  from += tabsize - from % tabsize;
3200 	}
3201       else
3202 	{
3203 	  putc (' ', stderr);
3204 	  from++;
3205 	}
3206     }
3207 }
3208 
3209 static void
print_select_list(list,list_len,max_elem_len,indices_len)3210 print_select_list (list, list_len, max_elem_len, indices_len)
3211      WORD_LIST *list;
3212      int list_len, max_elem_len, indices_len;
3213 {
3214   int ind, row, elem_len, pos, cols, rows;
3215   int first_column_indices_len, other_indices_len;
3216 
3217   if (list == 0)
3218     {
3219       putc ('\n', stderr);
3220       return;
3221     }
3222 
3223   cols = max_elem_len ? COLS / max_elem_len : 1;
3224   if (cols == 0)
3225     cols = 1;
3226   rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
3227   cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
3228 
3229   if (rows == 1)
3230     {
3231       rows = cols;
3232       cols = 1;
3233     }
3234 
3235   first_column_indices_len = NUMBER_LEN (rows);
3236   other_indices_len = indices_len;
3237 
3238   for (row = 0; row < rows; row++)
3239     {
3240       ind = row;
3241       pos = 0;
3242       while (1)
3243 	{
3244 	  indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
3245 	  elem_len = print_index_and_element (indices_len, ind + 1, list);
3246 	  elem_len += indices_len + RP_SPACE_LEN;
3247 	  ind += rows;
3248 	  if (ind >= list_len)
3249 	    break;
3250 	  indent (pos + elem_len, pos + max_elem_len);
3251 	  pos += max_elem_len;
3252 	}
3253       putc ('\n', stderr);
3254     }
3255 }
3256 
3257 /* Print the elements of LIST, one per line, preceded by an index from 1 to
3258    LIST_LEN.  Then display PROMPT and wait for the user to enter a number.
3259    If the number is between 1 and LIST_LEN, return that selection.  If EOF
3260    is read, return a null string.  If a blank line is entered, or an invalid
3261    number is entered, the loop is executed again. */
3262 static char *
select_query(list,list_len,prompt,print_menu)3263 select_query (list, list_len, prompt, print_menu)
3264      WORD_LIST *list;
3265      int list_len;
3266      char *prompt;
3267      int print_menu;
3268 {
3269   int max_elem_len, indices_len, len, r, oe;
3270   intmax_t reply;
3271   WORD_LIST *l;
3272   char *repl_string, *t;
3273 
3274   COLS = default_columns ();
3275 
3276 #if 0
3277   t = get_string_value ("TABSIZE");
3278   tabsize = (t && *t) ? atoi (t) : 8;
3279   if (tabsize <= 0)
3280     tabsize = 8;
3281 #else
3282   tabsize = 8;
3283 #endif
3284 
3285   max_elem_len = 0;
3286   for (l = list; l; l = l->next)
3287     {
3288       len = displen (l->word->word);
3289       if (len > max_elem_len)
3290 	max_elem_len = len;
3291     }
3292   indices_len = NUMBER_LEN (list_len);
3293   max_elem_len += indices_len + RP_SPACE_LEN + 2;
3294 
3295   while (1)
3296     {
3297       if (print_menu)
3298 	print_select_list (list, list_len, max_elem_len, indices_len);
3299       fprintf (stderr, "%s", prompt);
3300       fflush (stderr);
3301       QUIT;
3302 
3303       oe = executing_builtin;
3304       executing_builtin = 1;
3305       r = read_builtin ((WORD_LIST *)NULL);
3306       executing_builtin = oe;
3307       if (r != EXECUTION_SUCCESS)
3308 	{
3309 	  putchar ('\n');
3310 	  return ((char *)NULL);
3311 	}
3312       repl_string = get_string_value ("REPLY");
3313       if (repl_string == 0)
3314 	return ((char *)NULL);
3315       if (*repl_string == 0)
3316 	{
3317 	  print_menu = 1;
3318 	  continue;
3319 	}
3320       if (legal_number (repl_string, &reply) == 0)
3321 	return "";
3322       if (reply < 1 || reply > list_len)
3323 	return "";
3324 
3325       for (l = list; l && --reply; l = l->next)
3326 	;
3327       return (l->word->word);		/* XXX - can't be null? */
3328     }
3329 }
3330 
3331 /* Execute a SELECT command.  The syntax is:
3332    SELECT word IN list DO command_list DONE
3333    Only `break' or `return' in command_list will terminate
3334    the command. */
3335 static int
execute_select_command(select_command)3336 execute_select_command (select_command)
3337      SELECT_COM *select_command;
3338 {
3339   WORD_LIST *releaser, *list;
3340   SHELL_VAR *v;
3341   char *identifier, *ps3_prompt, *selection;
3342   int retval, list_len, show_menu, save_line_number;
3343 
3344   if (check_identifier (select_command->name, 1) == 0)
3345     return (EXECUTION_FAILURE);
3346 
3347   save_line_number = line_number;
3348   line_number = select_command->line;
3349 
3350   command_string_index = 0;
3351   print_select_command_head (select_command);
3352 
3353   if (echo_command_at_execute)
3354     xtrace_print_select_command_head (select_command);
3355 
3356 #if 0
3357   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3358 #else
3359   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3360 #endif
3361     {
3362       FREE (the_printed_command_except_trap);
3363       the_printed_command_except_trap = savestring (the_printed_command);
3364     }
3365 
3366   retval = run_debug_trap ();
3367 #if defined (DEBUGGER)
3368   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3369      skip the command. */
3370   if (debugging_mode && retval != EXECUTION_SUCCESS)
3371     return (EXECUTION_SUCCESS);
3372 #endif
3373 
3374   loop_level++;
3375   identifier = select_command->name->word;
3376 
3377   /* command and arithmetic substitution, parameter and variable expansion,
3378      word splitting, pathname expansion, and quote removal. */
3379   list = releaser = expand_words_no_vars (select_command->map_list);
3380   list_len = list_length (list);
3381   if (list == 0 || list_len == 0)
3382     {
3383       if (list)
3384 	dispose_words (list);
3385       line_number = save_line_number;
3386       return (EXECUTION_SUCCESS);
3387     }
3388 
3389   begin_unwind_frame ("select");
3390   add_unwind_protect (dispose_words, releaser);
3391 
3392   if (select_command->flags & CMD_IGNORE_RETURN)
3393     select_command->action->flags |= CMD_IGNORE_RETURN;
3394 
3395   retval = EXECUTION_SUCCESS;
3396   show_menu = 1;
3397 
3398   while (1)
3399     {
3400       line_number = select_command->line;
3401       ps3_prompt = get_string_value ("PS3");
3402       if (ps3_prompt == 0)
3403 	ps3_prompt = "#? ";
3404 
3405       QUIT;
3406       selection = select_query (list, list_len, ps3_prompt, show_menu);
3407       QUIT;
3408       if (selection == 0)
3409 	{
3410 	  /* select_query returns EXECUTION_FAILURE if the read builtin
3411 	     fails, so we want to return failure in this case. */
3412 	  retval = EXECUTION_FAILURE;
3413 	  break;
3414 	}
3415 
3416       v = bind_variable (identifier, selection, 0);
3417       if (v == 0 || readonly_p (v) || noassign_p (v))
3418 	{
3419 	  if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
3420 	    {
3421 	      last_command_exit_value = EXECUTION_FAILURE;
3422 	      jump_to_top_level (FORCE_EOF);
3423 	    }
3424 	  else
3425 	    {
3426 	      dispose_words (releaser);
3427 	      discard_unwind_frame ("select");
3428 	      loop_level--;
3429 	      line_number = save_line_number;
3430 	      return (EXECUTION_FAILURE);
3431 	    }
3432 	}
3433 
3434       stupidly_hack_special_variables (identifier);
3435 
3436       retval = execute_command (select_command->action);
3437 
3438       REAP ();
3439       QUIT;
3440 
3441       if (breaking)
3442 	{
3443 	  breaking--;
3444 	  break;
3445 	}
3446 
3447       if (continuing)
3448 	{
3449 	  continuing--;
3450 	  if (continuing)
3451 	    break;
3452 	}
3453 
3454 #if defined (KSH_COMPATIBLE_SELECT)
3455       show_menu = 0;
3456       selection = get_string_value ("REPLY");
3457       if (selection && *selection == '\0')
3458         show_menu = 1;
3459 #endif
3460     }
3461 
3462   loop_level--;
3463   line_number = save_line_number;
3464 
3465   dispose_words (releaser);
3466   discard_unwind_frame ("select");
3467   return (retval);
3468 }
3469 #endif /* SELECT_COMMAND */
3470 
3471 /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
3472    The pattern_list is a linked list of pattern clauses; each clause contains
3473    some patterns to compare word_desc against, and an associated command to
3474    execute. */
3475 static int
execute_case_command(case_command)3476 execute_case_command (case_command)
3477      CASE_COM *case_command;
3478 {
3479   register WORD_LIST *list;
3480   WORD_LIST *wlist, *es;
3481   PATTERN_LIST *clauses;
3482   char *word, *pattern;
3483   int retval, match, ignore_return, save_line_number, qflags;
3484 
3485   save_line_number = line_number;
3486   line_number = case_command->line;
3487 
3488   command_string_index = 0;
3489   print_case_command_head (case_command);
3490 
3491   if (echo_command_at_execute)
3492     xtrace_print_case_command_head (case_command);
3493 
3494 #if 0
3495   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3496 #else
3497   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3498 #endif
3499     {
3500       FREE (the_printed_command_except_trap);
3501       the_printed_command_except_trap = savestring (the_printed_command);
3502     }
3503 
3504   retval = run_debug_trap();
3505 #if defined (DEBUGGER)
3506   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3507      skip the command. */
3508   if (debugging_mode && retval != EXECUTION_SUCCESS)
3509     {
3510       line_number = save_line_number;
3511       return (EXECUTION_SUCCESS);
3512     }
3513 #endif
3514 
3515   /* Use the same expansions (the ones POSIX specifies) as the patterns;
3516      dequote the resulting string (as POSIX specifies) since the quotes in
3517      patterns are handled specially below. We have to do it in this order
3518      because we're not supposed to perform word splitting. */
3519   wlist = expand_word_leave_quoted (case_command->word, 0);
3520   if (wlist)
3521     {
3522       char *t;
3523       t = string_list (wlist);
3524       word = dequote_string (t);
3525       free (t);
3526     }
3527   else
3528     word = savestring ("");
3529   dispose_words (wlist);
3530 
3531   retval = EXECUTION_SUCCESS;
3532   ignore_return = case_command->flags & CMD_IGNORE_RETURN;
3533 
3534   begin_unwind_frame ("case");
3535   add_unwind_protect (xfree, word);
3536 
3537 #define EXIT_CASE()  goto exit_case_command
3538 
3539   for (clauses = case_command->clauses; clauses; clauses = clauses->next)
3540     {
3541       QUIT;
3542       for (list = clauses->patterns; list; list = list->next)
3543 	{
3544 	  es = expand_word_leave_quoted (list->word, 0);
3545 
3546 	  if (es && es->word && es->word->word && *(es->word->word))
3547 	    {
3548 	      /* Convert quoted null strings into empty strings. */
3549 	      qflags = QGLOB_CVTNULL;
3550 
3551 	      /* We left CTLESC in place quoting CTLESC and CTLNUL after the
3552 	      	 call to expand_word_leave_quoted; tell quote_string_for_globbing
3553 	      	 to remove those here. This works for both unquoted portions of
3554 		 the word (which call quote_escapes) and quoted portions
3555 		 (which call quote_string). */
3556 	      qflags |= QGLOB_CTLESC;
3557 	      pattern = quote_string_for_globbing (es->word->word, qflags);
3558 	    }
3559 	  else
3560 	    {
3561 	      pattern = (char *)xmalloc (1);
3562 	      pattern[0] = '\0';
3563 	    }
3564 
3565 	  /* Since the pattern does not undergo quote removal (as per
3566 	     Posix.2, section 3.9.4.3), the strmatch () call must be able
3567 	     to recognize backslashes as escape characters. */
3568 	  match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
3569 	  free (pattern);
3570 
3571 	  dispose_words (es);
3572 
3573 	  if (match)
3574 	    {
3575 	      do
3576 		{
3577 		  if (clauses->action && ignore_return)
3578 		    clauses->action->flags |= CMD_IGNORE_RETURN;
3579 		  retval = execute_command (clauses->action);
3580 		}
3581 	      while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3582 	      if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3583 		EXIT_CASE ();
3584 	      else
3585 		break;
3586 	    }
3587 
3588 	  QUIT;
3589 	}
3590     }
3591 
3592 exit_case_command:
3593   free (word);
3594   discard_unwind_frame ("case");
3595   line_number = save_line_number;
3596   return (retval);
3597 }
3598 
3599 #define CMD_WHILE 0
3600 #define CMD_UNTIL 1
3601 
3602 /* The WHILE command.  Syntax: WHILE test DO action; DONE.
3603    Repeatedly execute action while executing test produces
3604    EXECUTION_SUCCESS. */
3605 static int
execute_while_command(while_command)3606 execute_while_command (while_command)
3607      WHILE_COM *while_command;
3608 {
3609   return (execute_while_or_until (while_command, CMD_WHILE));
3610 }
3611 
3612 /* UNTIL is just like WHILE except that the test result is negated. */
3613 static int
execute_until_command(while_command)3614 execute_until_command (while_command)
3615      WHILE_COM *while_command;
3616 {
3617   return (execute_while_or_until (while_command, CMD_UNTIL));
3618 }
3619 
3620 /* The body for both while and until.  The only difference between the
3621    two is that the test value is treated differently.  TYPE is
3622    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
3623    be EXECUTION_SUCCESS if no commands in the body are executed, and
3624    the status of the last command executed in the body otherwise. */
3625 static int
execute_while_or_until(while_command,type)3626 execute_while_or_until (while_command, type)
3627      WHILE_COM *while_command;
3628      int type;
3629 {
3630   int return_value, body_status;
3631 
3632   body_status = EXECUTION_SUCCESS;
3633   loop_level++;
3634 
3635   while_command->test->flags |= CMD_IGNORE_RETURN;
3636   if (while_command->flags & CMD_IGNORE_RETURN)
3637     while_command->action->flags |= CMD_IGNORE_RETURN;
3638 
3639   while (1)
3640     {
3641       return_value = execute_command (while_command->test);
3642       REAP ();
3643 
3644       /* Need to handle `break' in the test when we would break out of the
3645          loop.  The job control code will set `breaking' to loop_level
3646          when a job in a loop is stopped with SIGTSTP.  If the stopped job
3647          is in the loop test, `breaking' will not be reset unless we do
3648          this, and the shell will cease to execute commands.  The same holds
3649          true for `continue'. */
3650       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3651 	{
3652 	  if (breaking)
3653 	    breaking--;
3654 	  if (continuing)
3655 	    continuing--;
3656 	  break;
3657 	}
3658       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3659 	{
3660 	  if (breaking)
3661 	    breaking--;
3662 	  if (continuing)
3663 	    continuing--;
3664 	  break;
3665 	}
3666 
3667       QUIT;
3668       body_status = execute_command (while_command->action);
3669       QUIT;
3670 
3671       if (breaking)
3672 	{
3673 	  breaking--;
3674 	  break;
3675 	}
3676 
3677       if (continuing)
3678 	{
3679 	  continuing--;
3680 	  if (continuing)
3681 	    break;
3682 	}
3683     }
3684   loop_level--;
3685 
3686   return (body_status);
3687 }
3688 
3689 /* IF test THEN command [ELSE command].
3690    IF also allows ELIF in the place of ELSE IF, but
3691    the parser makes *that* stupidity transparent. */
3692 static int
execute_if_command(if_command)3693 execute_if_command (if_command)
3694      IF_COM *if_command;
3695 {
3696   int return_value, save_line_number;
3697 
3698   save_line_number = line_number;
3699   if_command->test->flags |= CMD_IGNORE_RETURN;
3700   return_value = execute_command (if_command->test);
3701   line_number = save_line_number;
3702 
3703   if (return_value == EXECUTION_SUCCESS)
3704     {
3705       QUIT;
3706 
3707       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3708 	if_command->true_case->flags |= CMD_IGNORE_RETURN;
3709 
3710       return (execute_command (if_command->true_case));
3711     }
3712   else
3713     {
3714       QUIT;
3715 
3716       if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3717 	if_command->false_case->flags |= CMD_IGNORE_RETURN;
3718 
3719       return (execute_command (if_command->false_case));
3720     }
3721 }
3722 
3723 #if defined (DPAREN_ARITHMETIC)
3724 static int
execute_arith_command(arith_command)3725 execute_arith_command (arith_command)
3726      ARITH_COM *arith_command;
3727 {
3728   int expok, save_line_number, retval;
3729   intmax_t expresult;
3730   WORD_LIST *new;
3731   char *exp, *t;
3732 
3733   expresult = 0;
3734 
3735   save_line_number = line_number;
3736   this_command_name = "((";	/* )) */
3737   line_number_for_err_trap = line_number = arith_command->line;
3738   /* If we're in a function, update the line number information. */
3739   if (variable_context && interactive_shell && sourcelevel == 0)
3740     {
3741       /* line numbers in a function start at 1 */
3742       line_number -= function_line_number - 1;
3743       if (line_number <= 0)
3744 	line_number = 1;
3745     }
3746 
3747   command_string_index = 0;
3748   print_arith_command (arith_command->exp);
3749 
3750   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3751     {
3752       FREE (the_printed_command_except_trap);
3753       the_printed_command_except_trap = savestring (the_printed_command);
3754     }
3755 
3756   /* Run the debug trap before each arithmetic command, but do it after we
3757      update the line number information and before we expand the various
3758      words in the expression. */
3759   retval = run_debug_trap ();
3760 #if defined (DEBUGGER)
3761   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3762      skip the command. */
3763   if (debugging_mode && retval != EXECUTION_SUCCESS)
3764     {
3765       line_number = save_line_number;
3766       return (EXECUTION_SUCCESS);
3767     }
3768 #endif
3769 
3770   t = (char *)NULL;
3771   new = arith_command->exp;
3772   if (new->next)
3773     exp = t = string_list (new);	/* just in case */
3774   else
3775     exp = new->word->word;
3776 
3777   exp = expand_arith_string (exp, Q_DOUBLE_QUOTES|Q_ARITH);
3778 
3779   /* If we're tracing, make a new word list with `((' at the front and `))'
3780      at the back and print it. Change xtrace_print_arith_cmd to take a string
3781      when I change eval_arith_for_expr to use expand_arith_string(). */
3782   if (echo_command_at_execute)
3783     {
3784       new = make_word_list (make_word (exp ? exp : ""), (WORD_LIST *)NULL);
3785       xtrace_print_arith_cmd (new);
3786       dispose_words (new);
3787     }
3788 
3789   if (exp)
3790     {
3791       expresult = evalexp (exp, EXP_EXPANDED, &expok);
3792       line_number = save_line_number;
3793       free (exp);
3794     }
3795   else
3796     {
3797       expresult = 0;
3798       expok = 1;
3799     }
3800   FREE (t);
3801 
3802   if (expok == 0)
3803     return (EXECUTION_FAILURE);
3804 
3805   return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3806 }
3807 #endif /* DPAREN_ARITHMETIC */
3808 
3809 #if defined (COND_COMMAND)
3810 
3811 static char * const nullstr = "";
3812 
3813 /* XXX - can COND ever be NULL when this is called? */
3814 static int
execute_cond_node(cond)3815 execute_cond_node (cond)
3816      COND_COM *cond;
3817 {
3818   int result, invert, patmatch, rmatch, mflags, ignore;
3819   char *arg1, *arg2;
3820 #if 0
3821   char *t1, *t2;
3822 #endif
3823 
3824   invert = (cond->flags & CMD_INVERT_RETURN);
3825   ignore = (cond->flags & CMD_IGNORE_RETURN);
3826   if (ignore)
3827     {
3828       if (cond->left)
3829 	cond->left->flags |= CMD_IGNORE_RETURN;
3830       if (cond->right)
3831 	cond->right->flags |= CMD_IGNORE_RETURN;
3832     }
3833 
3834   if (cond->type == COND_EXPR)
3835     result = execute_cond_node (cond->left);
3836   else if (cond->type == COND_OR)
3837     {
3838       result = execute_cond_node (cond->left);
3839       if (result != EXECUTION_SUCCESS)
3840 	result = execute_cond_node (cond->right);
3841     }
3842   else if (cond->type == COND_AND)
3843     {
3844       result = execute_cond_node (cond->left);
3845       if (result == EXECUTION_SUCCESS)
3846 	result = execute_cond_node (cond->right);
3847     }
3848   else if (cond->type == COND_UNARY)
3849     {
3850       if (ignore)
3851 	comsub_ignore_return++;
3852       arg1 = cond_expand_word (cond->left->op, 0);
3853       if (ignore)
3854 	comsub_ignore_return--;
3855       if (arg1 == 0)
3856 	arg1 = nullstr;
3857       if (echo_command_at_execute)
3858 	xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3859       result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3860       if (arg1 != nullstr)
3861 	free (arg1);
3862     }
3863   else if (cond->type == COND_BINARY)
3864     {
3865       rmatch = 0;
3866       patmatch = (((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3867 		   (cond->op->word[0] == '!' || cond->op->word[0] == '=')) ||
3868 		  (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3869 #if defined (COND_REGEXP)
3870       rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3871 		cond->op->word[2] == '\0');
3872 #endif
3873 
3874       if (ignore)
3875 	comsub_ignore_return++;
3876       arg1 = cond_expand_word (cond->left->op, 0);
3877       if (ignore)
3878 	comsub_ignore_return--;
3879       if (arg1 == 0)
3880 	arg1 = nullstr;
3881       if (ignore)
3882 	comsub_ignore_return++;
3883       arg2 = cond_expand_word (cond->right->op,
3884 			       (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3885       if (ignore)
3886 	comsub_ignore_return--;
3887       if (arg2 == 0)
3888 	arg2 = nullstr;
3889 
3890       if (echo_command_at_execute)
3891 	xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3892 
3893 #if defined (COND_REGEXP)
3894       if (rmatch)
3895 	{
3896 	  mflags = SHMAT_PWARN;
3897 #if defined (ARRAY_VARS)
3898 	  mflags |= SHMAT_SUBEXP;
3899 #endif
3900 
3901 #if 0
3902 	  t1 = strescape(arg1);
3903 	  t2 = strescape(arg2);
3904 	  itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1, t2);
3905 	  free(t1);
3906 	  free(t2);
3907 #endif
3908 
3909 	  result = sh_regmatch (arg1, arg2, mflags);
3910 	}
3911       else
3912 #endif /* COND_REGEXP */
3913 	{
3914 	  int oe;
3915 	  oe = extended_glob;
3916 	  extended_glob = 1;
3917 	  result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3918 				  ? EXECUTION_SUCCESS
3919 				  : EXECUTION_FAILURE;
3920 	  extended_glob = oe;
3921 	}
3922       if (arg1 != nullstr)
3923 	free (arg1);
3924       if (arg2 != nullstr)
3925 	free (arg2);
3926     }
3927   else
3928     {
3929       command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3930       jump_to_top_level (DISCARD);
3931       result = EXECUTION_FAILURE;
3932     }
3933 
3934   if (invert)
3935     result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3936 
3937   return result;
3938 }
3939 
3940 static int
execute_cond_command(cond_command)3941 execute_cond_command (cond_command)
3942      COND_COM *cond_command;
3943 {
3944   int retval, save_line_number;
3945 
3946   save_line_number = line_number;
3947 
3948   this_command_name = "[[";
3949   line_number_for_err_trap = line_number = cond_command->line;
3950   /* If we're in a function, update the line number information. */
3951   if (variable_context && interactive_shell && sourcelevel == 0)
3952     {
3953       /* line numbers in a function start at 1 */
3954       line_number -= function_line_number - 1;
3955       if (line_number <= 0)
3956 	line_number = 1;
3957     }
3958   command_string_index = 0;
3959   print_cond_command (cond_command);
3960 
3961   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3962     {
3963       FREE (the_printed_command_except_trap);
3964       the_printed_command_except_trap = savestring (the_printed_command);
3965     }
3966 
3967   /* Run the debug trap before each conditional command, but do it after we
3968      update the line number information. */
3969   retval = run_debug_trap ();
3970 #if defined (DEBUGGER)
3971   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3972      skip the command. */
3973   if (debugging_mode && retval != EXECUTION_SUCCESS)
3974     {
3975       line_number = save_line_number;
3976       return (EXECUTION_SUCCESS);
3977     }
3978 #endif
3979 
3980 #if 0
3981   debug_print_cond_command (cond_command);
3982 #endif
3983 
3984   last_command_exit_value = retval = execute_cond_node (cond_command);
3985   line_number = save_line_number;
3986   return (retval);
3987 }
3988 #endif /* COND_COMMAND */
3989 
3990 static void
bind_lastarg(arg)3991 bind_lastarg (arg)
3992      char *arg;
3993 {
3994   SHELL_VAR *var;
3995 
3996   if (arg == 0)
3997     arg = "";
3998   var = bind_variable ("_", arg, 0);
3999   if (var)
4000     VUNSETATTR (var, att_exported);
4001 }
4002 
4003 /* Execute a null command.  Fork a subshell if the command uses pipes or is
4004    to be run asynchronously.  This handles all the side effects that are
4005    supposed to take place. */
4006 static int
execute_null_command(redirects,pipe_in,pipe_out,async)4007 execute_null_command (redirects, pipe_in, pipe_out, async)
4008      REDIRECT *redirects;
4009      int pipe_in, pipe_out, async;
4010 {
4011   int r;
4012   int forcefork, fork_flags;
4013   REDIRECT *rd;
4014 
4015   for (forcefork = 0, rd = redirects; rd; rd = rd->next)
4016     {
4017       forcefork += rd->rflags & REDIR_VARASSIGN;
4018       /* Safety */
4019       forcefork += (rd->redirector.dest == 0 || fd_is_bash_input (rd->redirector.dest)) && (INPUT_REDIRECT (rd->instruction) || TRANSLATE_REDIRECT (rd->instruction) || rd->instruction == r_close_this);
4020     }
4021 
4022   if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
4023     {
4024       /* We have a null command, but we really want a subshell to take
4025 	 care of it.  Just fork, do piping and redirections, and exit. */
4026       fork_flags = async ? FORK_ASYNC : 0;
4027       if (make_child ((char *)NULL, fork_flags) == 0)
4028 	{
4029 	  /* Cancel traps, in trap.c. */
4030 	  restore_original_signals ();		/* XXX */
4031 
4032 	  do_piping (pipe_in, pipe_out);
4033 
4034 #if defined (COPROCESS_SUPPORT)
4035 	  coproc_closeall ();
4036 #endif
4037 
4038 	  interactive = 0;			/* XXX */
4039 
4040 	  subshell_environment = 0;
4041 	  if (async)
4042 	    subshell_environment |= SUBSHELL_ASYNC;
4043 	  if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4044 	    subshell_environment |= SUBSHELL_PIPE;
4045 
4046 	  if (do_redirections (redirects, RX_ACTIVE) == 0)
4047 	    exit (EXECUTION_SUCCESS);
4048 	  else
4049 	    exit (EXECUTION_FAILURE);
4050 	}
4051       else
4052 	{
4053 	  close_pipes (pipe_in, pipe_out);
4054 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4055 	  if (pipe_out == NO_PIPE)
4056 	    unlink_fifo_list ();
4057 #endif
4058 	  return (EXECUTION_SUCCESS);
4059 	}
4060     }
4061   else
4062     {
4063       /* Even if there aren't any command names, pretend to do the
4064 	 redirections that are specified.  The user expects the side
4065 	 effects to take place.  If the redirections fail, then return
4066 	 failure.  Otherwise, if a command substitution took place while
4067 	 expanding the command or a redirection, return the value of that
4068 	 substitution.  Otherwise, return EXECUTION_SUCCESS. */
4069 
4070       r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
4071       cleanup_redirects (redirection_undo_list);
4072       redirection_undo_list = (REDIRECT *)NULL;
4073 
4074       if (r != 0)
4075 	return (EXECUTION_FAILURE);
4076       else if (last_command_subst_pid != NO_PID)
4077 	return (last_command_exit_value);
4078       else
4079 	return (EXECUTION_SUCCESS);
4080     }
4081 }
4082 
4083 /* This is a hack to suppress word splitting for assignment statements
4084    given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
4085 static void
fix_assignment_words(words)4086 fix_assignment_words (words)
4087      WORD_LIST *words;
4088 {
4089   WORD_LIST *w, *wcmd;
4090   struct builtin *b;
4091   int assoc, global, array, integer;
4092 
4093   if (words == 0)
4094     return;
4095 
4096   b = 0;
4097   assoc = global = array = integer = 0;
4098 
4099   /* Skip over assignment statements preceding a command name */
4100   wcmd = words;
4101   for (wcmd = words; wcmd; wcmd = wcmd->next)
4102     if ((wcmd->word->flags & W_ASSIGNMENT) == 0)
4103       break;
4104   /* Posix (post-2008) says that `command' doesn't change whether
4105      or not the builtin it shadows is a `declaration command', even
4106      though it removes other special builtin properties.  In Posix
4107      mode, we skip over one or more instances of `command' and
4108      deal with the next word as the assignment builtin. */
4109   while (posixly_correct && wcmd && wcmd->word && wcmd->word->word && STREQ (wcmd->word->word, "command"))
4110     wcmd = wcmd->next;
4111 
4112   for (w = wcmd; w; w = w->next)
4113     if (w->word->flags & W_ASSIGNMENT)
4114       {
4115       	/* Lazy builtin lookup, only do it if we find an assignment */
4116 	if (b == 0)
4117 	  {
4118 	    b = builtin_address_internal (wcmd->word->word, 0);
4119 	    if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4120 	      return;
4121 	    else if (b && (b->flags & ASSIGNMENT_BUILTIN))
4122 	      wcmd->word->flags |= W_ASSNBLTIN;
4123 	  }
4124 	w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
4125 #if defined (ARRAY_VARS)
4126 	if (assoc)
4127 	  w->word->flags |= W_ASSIGNASSOC;
4128 	if (array)
4129 	  w->word->flags |= W_ASSIGNARRAY;
4130 #endif
4131 	if (global)
4132 	  w->word->flags |= W_ASSNGLOBAL;
4133 
4134 	/* If we have an assignment builtin that does not create local variables,
4135 	   make sure we create global variables even if we internally call
4136 	   `declare'.  The CHKLOCAL flag means to set attributes or values on
4137 	   an existing local variable, if there is one. */
4138 	if (b && ((b->flags & (ASSIGNMENT_BUILTIN|LOCALVAR_BUILTIN)) == ASSIGNMENT_BUILTIN))
4139 	  w->word->flags |= W_ASSNGLOBAL|W_CHKLOCAL;
4140 	else if (b && (b->flags & ASSIGNMENT_BUILTIN) && (b->flags & LOCALVAR_BUILTIN) && variable_context)
4141 	  w->word->flags |= W_FORCELOCAL;
4142       }
4143 #if defined (ARRAY_VARS)
4144     /* Note that we saw an associative array option to a builtin that takes
4145        assignment statements.  This is a bit of a kludge. */
4146     else if (w->word->word[0] == '-' && (strpbrk (w->word->word+1, "Aag") != 0))
4147 #else
4148     else if (w->word->word[0] == '-' && strchr (w->word->word+1, 'g'))
4149 #endif
4150       {
4151 	if (b == 0)
4152 	  {
4153 	    b = builtin_address_internal (wcmd->word->word, 0);
4154 	    if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4155 	      return;
4156 	    else if (b && (b->flags & ASSIGNMENT_BUILTIN))
4157 	      wcmd->word->flags |= W_ASSNBLTIN;
4158 	  }
4159 	if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'A'))
4160 	  assoc = 1;
4161 	else if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'a'))
4162 	  array = 1;
4163 	if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'g'))
4164 	  global = 1;
4165       }
4166 }
4167 
4168 #ifndef ISOPTION
4169 #  define ISOPTION(s, c)  (s[0] == '-' && s[1] == c && s[2] == 0)
4170 #endif
4171 
4172 #define RETURN_NOT_COMMAND() \
4173   do { if (typep) *typep = 0; return words; } while (0)
4174 
4175 /* Make sure we have `command [-p] command_name [args]', and handle skipping
4176    over the usual `--' that ends the options.  Returns the updated WORDS with
4177    the command and options stripped and sets *TYPEP to a non-zero value. If
4178    any other options are supplied, or there is not a command_name, we punt
4179    and return a zero value in *TYPEP without updating WORDS. */
4180 static WORD_LIST *
check_command_builtin(words,typep)4181 check_command_builtin (words, typep)
4182      WORD_LIST *words;
4183      int *typep;
4184 {
4185   int type;
4186   WORD_LIST *w;
4187 
4188   w = words->next;
4189   type = 1;
4190 
4191   if (w && ISOPTION (w->word->word, 'p'))	/* command -p */
4192     {
4193 #if defined (RESTRICTED_SHELL)
4194       if (restricted)
4195         RETURN_NOT_COMMAND();
4196 #endif
4197       w = w->next;
4198       type = 2;
4199     }
4200 
4201   if (w && ISOPTION (w->word->word, '-'))	/* command [-p] -- */
4202     w = w->next;
4203   else if (w && w->word->word[0] == '-')	/* any other option */
4204     RETURN_NOT_COMMAND();
4205 
4206   if (w == 0 || w->word->word == 0)		/* must have a command_name */
4207     RETURN_NOT_COMMAND();
4208 
4209   if (typep)
4210     *typep = type;
4211   return w;
4212 }
4213 
4214 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
4215    to PATHNAME, is a directory.  Used by the autocd code below. */
4216 static int
is_dirname(pathname)4217 is_dirname (pathname)
4218      char *pathname;
4219 {
4220   char *temp;
4221   int ret;
4222 
4223   temp = search_for_command (pathname, 0);
4224   ret = temp ? file_isdir (temp) : file_isdir (pathname);
4225   free (temp);
4226   return ret;
4227 }
4228 
4229 /* The meaty part of all the executions.  We have to start hacking the
4230    real execution of commands here.  Fork a process, set things up,
4231    execute the command. */
4232 static int
execute_simple_command(simple_command,pipe_in,pipe_out,async,fds_to_close)4233 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
4234      SIMPLE_COM *simple_command;
4235      int pipe_in, pipe_out, async;
4236      struct fd_bitmap *fds_to_close;
4237 {
4238   WORD_LIST *words, *lastword;
4239   char *command_line, *lastarg, *temp;
4240   int first_word_quoted, result, builtin_is_special, already_forked, dofork;
4241   int fork_flags, cmdflags;
4242   pid_t old_last_async_pid;
4243   sh_builtin_func_t *builtin;
4244   SHELL_VAR *func;
4245   volatile int old_builtin, old_command_builtin;
4246 
4247   result = EXECUTION_SUCCESS;
4248   special_builtin_failed = builtin_is_special = 0;
4249   command_line = (char *)0;
4250 
4251   QUIT;
4252 
4253   /* If we're in a function, update the line number information. */
4254   if (variable_context && interactive_shell && sourcelevel == 0)
4255     {
4256       /* line numbers in a function start at 1 */
4257       line_number -= function_line_number - 1;
4258       if (line_number <= 0)
4259 	line_number = 1;
4260     }
4261 
4262   /* Remember what this command line looks like at invocation. */
4263   command_string_index = 0;
4264   print_simple_command (simple_command);
4265 
4266 #if 0
4267   if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
4268 #else
4269   if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
4270 #endif
4271     {
4272       FREE (the_printed_command_except_trap);
4273       the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
4274     }
4275 
4276   /* Run the debug trap before each simple command, but do it after we
4277      update the line number information. */
4278   result = run_debug_trap ();
4279 #if defined (DEBUGGER)
4280   /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4281      skip the command. */
4282   if (debugging_mode && result != EXECUTION_SUCCESS)
4283     return (EXECUTION_SUCCESS);
4284 #endif
4285 
4286   cmdflags = simple_command->flags;
4287 
4288   first_word_quoted =
4289     simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
4290 
4291   last_command_subst_pid = NO_PID;
4292   old_last_async_pid = last_asynchronous_pid;
4293 
4294   already_forked = 0;
4295 
4296   /* If we're in a pipeline or run in the background, set DOFORK so we
4297      make the child early, before word expansion.  This keeps assignment
4298      statements from affecting the parent shell's environment when they
4299      should not. */
4300   dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
4301 
4302   /* Something like `%2 &' should restart job 2 in the background, not cause
4303      the shell to fork here. */
4304   if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
4305 	simple_command->words && simple_command->words->word &&
4306 	simple_command->words->word->word &&
4307 	(simple_command->words->word->word[0] == '%'))
4308     dofork = 0;
4309 
4310   if (dofork)
4311     {
4312       char *p;
4313 
4314       /* Do this now, because execute_disk_command will do it anyway in the
4315 	 vast majority of cases. */
4316       maybe_make_export_env ();
4317 
4318       /* Don't let a DEBUG trap overwrite the command string to be saved with
4319 	 the process/job associated with this child. */
4320       fork_flags = async ? FORK_ASYNC : 0;
4321       if (make_child (p = savestring (the_printed_command_except_trap), fork_flags) == 0)
4322 	{
4323 	  already_forked = 1;
4324 	  cmdflags |= CMD_NO_FORK;
4325 
4326 	  /* We redo some of what make_child() does with SUBSHELL_IGNTRAP */
4327 	  subshell_environment = SUBSHELL_FORK|SUBSHELL_IGNTRAP;	/* XXX */
4328 	  if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4329 	    subshell_environment |= SUBSHELL_PIPE;
4330 	  if (async)
4331 	    subshell_environment |= SUBSHELL_ASYNC;
4332 
4333 	  /* We need to do this before piping to handle some really
4334 	     pathological cases where one of the pipe file descriptors
4335 	     is < 2. */
4336 	  if (fds_to_close)
4337 	    close_fd_bitmap (fds_to_close);
4338 
4339 	  /* If we fork because of an input pipe, note input pipe for later to
4340 	     inhibit async commands from redirecting stdin from /dev/null */
4341 	  stdin_redir |= pipe_in != NO_PIPE;
4342 
4343 	  do_piping (pipe_in, pipe_out);
4344 	  pipe_in = pipe_out = NO_PIPE;
4345 #if defined (COPROCESS_SUPPORT)
4346 	  coproc_closeall ();
4347 #endif
4348 
4349 	  last_asynchronous_pid = old_last_async_pid;
4350 
4351 	  if (async)
4352 	    subshell_level++;		/* not for pipes yet */
4353 
4354 #if defined (JOB_CONTROL)
4355 	  FREE (p);			/* child doesn't use pointer */
4356 #endif
4357 	}
4358       else
4359 	{
4360 	  /* Don't let simple commands that aren't the last command in a
4361 	     pipeline change $? for the rest of the pipeline (or at all). */
4362 	  if (pipe_out != NO_PIPE)
4363 	    result = last_command_exit_value;
4364 	  close_pipes (pipe_in, pipe_out);
4365 	  command_line = (char *)NULL;      /* don't free this. */
4366 	  return (result);
4367 	}
4368     }
4369 
4370   QUIT;		/* XXX */
4371 
4372   /* If we are re-running this as the result of executing the `command'
4373      builtin, do not expand the command words a second time. */
4374   if ((cmdflags & CMD_INHIBIT_EXPANSION) == 0)
4375     {
4376       current_fds_to_close = fds_to_close;
4377       fix_assignment_words (simple_command->words);
4378       /* Pass the ignore return flag down to command substitutions */
4379       if (cmdflags & CMD_IGNORE_RETURN)	/* XXX */
4380 	comsub_ignore_return++;
4381       words = expand_words (simple_command->words);
4382       if (cmdflags & CMD_IGNORE_RETURN)
4383 	comsub_ignore_return--;
4384       current_fds_to_close = (struct fd_bitmap *)NULL;
4385     }
4386   else
4387     words = copy_word_list (simple_command->words);
4388 
4389   /* It is possible for WORDS not to have anything left in it.
4390      Perhaps all the words consisted of `$foo', and there was
4391      no variable `$foo'. */
4392   if (words == 0)
4393     {
4394       this_command_name = 0;
4395       result = execute_null_command (simple_command->redirects,
4396 				     pipe_in, pipe_out,
4397 				     already_forked ? 0 : async);
4398       if (already_forked)
4399 	sh_exit (result);
4400       else
4401 	{
4402 	  bind_lastarg ((char *)NULL);
4403 	  set_pipestatus_from_exit (result);
4404 	  return (result);
4405 	}
4406     }
4407 
4408   lastarg = (char *)NULL;
4409 
4410   begin_unwind_frame ("simple-command");
4411 
4412   if (echo_command_at_execute && (cmdflags & CMD_COMMAND_BUILTIN) == 0)
4413     xtrace_print_word_list (words, 1);
4414 
4415   builtin = (sh_builtin_func_t *)NULL;
4416   func = (SHELL_VAR *)NULL;
4417 
4418   /* This test is still here in case we want to change the command builtin
4419      handler code below to recursively call execute_simple_command (after
4420      modifying the simple_command struct). */
4421   if ((cmdflags & CMD_NO_FUNCTIONS) == 0)
4422     {
4423       /* Posix.2 says special builtins are found before functions.  We
4424 	 don't set builtin_is_special anywhere other than here, because
4425 	 this path is followed only when the `command' builtin is *not*
4426 	 being used, and we don't want to exit the shell if a special
4427 	 builtin executed with `command builtin' fails.  `command' is not
4428 	 a special builtin. */
4429       if (posixly_correct)
4430 	{
4431 	  builtin = find_special_builtin (words->word->word);
4432 	  if (builtin)
4433 	    builtin_is_special = 1;
4434 	}
4435       if (builtin == 0)
4436 	func = find_function (words->word->word);
4437     }
4438 
4439   /* In POSIX mode, assignment errors in the temporary environment cause a
4440      non-interactive shell to exit. */
4441 #if 1
4442   if (posixly_correct && builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
4443 #else
4444   /* This is for strict posix conformance. */
4445   if (posixly_correct && interactive_shell == 0 && tempenv_assign_error)
4446 #endif
4447     {
4448       last_command_exit_value = EXECUTION_FAILURE;
4449       jump_to_top_level (ERREXIT);
4450     }
4451   tempenv_assign_error = 0;	/* don't care about this any more */
4452 
4453   /* This is where we handle the command builtin as a pseudo-reserved word
4454      prefix. This allows us to optimize away forks if we can. */
4455   old_command_builtin = -1;
4456   if (builtin == 0 && func == 0)
4457     {
4458       WORD_LIST *disposer, *l;
4459       int cmdtype;
4460 
4461       builtin = find_shell_builtin (words->word->word);
4462       while (builtin == command_builtin)
4463 	{
4464 	  disposer = words;
4465 	  cmdtype = 0;
4466 	  words = check_command_builtin (words, &cmdtype);
4467 	  if (cmdtype > 0)	/* command -p [--] words */
4468 	    {
4469 	      for (l = disposer; l->next != words; l = l->next)
4470 		;
4471 	      l->next = 0;
4472 	      dispose_words (disposer);
4473 	      cmdflags |= CMD_COMMAND_BUILTIN | CMD_NO_FUNCTIONS;
4474 	      if (cmdtype == 2)
4475 		cmdflags |= CMD_STDPATH;
4476 	      builtin = find_shell_builtin (words->word->word);
4477 	    }
4478 	  else
4479 	    break;
4480 	}
4481       if (cmdflags & CMD_COMMAND_BUILTIN)
4482 	{
4483 	  old_command_builtin = executing_command_builtin;
4484 	  unwind_protect_int (executing_command_builtin);
4485 	  executing_command_builtin |= 1;
4486 	}
4487       builtin = 0;
4488     }
4489 
4490   add_unwind_protect (dispose_words, words);
4491   QUIT;
4492 
4493   /* Bind the last word in this command to "$_" after execution. */
4494   for (lastword = words; lastword->next; lastword = lastword->next)
4495     ;
4496   lastarg = lastword->word->word;
4497 
4498 #if defined (JOB_CONTROL)
4499   /* Is this command a job control related thing? */
4500   if (words->word->word[0] == '%' && already_forked == 0)
4501     {
4502       this_command_name = async ? "bg" : "fg";
4503       last_shell_builtin = this_shell_builtin;
4504       this_shell_builtin = builtin_address (this_command_name);
4505       result = (*this_shell_builtin) (words);
4506       goto return_result;
4507     }
4508 
4509   /* One other possibililty.  The user may want to resume an existing job.
4510      If they do, find out whether this word is a candidate for a running
4511      job. */
4512   if (job_control && already_forked == 0 && async == 0 &&
4513 	!first_word_quoted &&
4514 	!words->next &&
4515 	words->word->word[0] &&
4516 	!simple_command->redirects &&
4517 	pipe_in == NO_PIPE &&
4518 	pipe_out == NO_PIPE &&
4519 	(temp = get_string_value ("auto_resume")))
4520     {
4521       int job, jflags, started_status;
4522 
4523       jflags = JM_STOPPED|JM_FIRSTMATCH;
4524       if (STREQ (temp, "exact"))
4525 	jflags |= JM_EXACT;
4526       else if (STREQ (temp, "substring"))
4527 	jflags |= JM_SUBSTRING;
4528       else
4529 	jflags |= JM_PREFIX;
4530       job = get_job_by_name (words->word->word, jflags);
4531       if (job != NO_JOB)
4532 	{
4533 	  run_unwind_frame ("simple-command");
4534 	  this_command_name = "fg";
4535 	  last_shell_builtin = this_shell_builtin;
4536 	  this_shell_builtin = builtin_address ("fg");
4537 
4538 	  started_status = start_job (job, 1);
4539 	  return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
4540 	}
4541     }
4542 #endif /* JOB_CONTROL */
4543 
4544 run_builtin:
4545   /* Remember the name of this command globally. */
4546   this_command_name = words->word->word;
4547 
4548   QUIT;
4549 
4550   /* This command could be a shell builtin or a user-defined function.
4551      We have already found special builtins by this time, so we do not
4552      set builtin_is_special.  If this is a function or builtin, and we
4553      have pipes, then fork a subshell in here.  Otherwise, just execute
4554      the command directly. */
4555   if (func == 0 && builtin == 0)
4556     builtin = find_shell_builtin (this_command_name);
4557 
4558   last_shell_builtin = this_shell_builtin;
4559   this_shell_builtin = builtin;
4560 
4561   if (builtin || func)
4562     {
4563       if (builtin)
4564         {
4565 	  old_builtin = executing_builtin;
4566 	  unwind_protect_int (executing_builtin);	/* modified in execute_builtin */
4567 	  if (old_command_builtin == -1)	/* sentinel, can be set above */
4568 	    {
4569 	      old_command_builtin = executing_command_builtin;
4570 	      unwind_protect_int (executing_command_builtin);	/* ditto and set above */
4571 	    }
4572         }
4573       if (already_forked)
4574 	{
4575 	  /* reset_terminating_signals (); */	/* XXX */
4576 	  /* Reset the signal handlers in the child, but don't free the
4577 	     trap strings.  Set a flag noting that we have to free the
4578 	     trap strings if we run trap to change a signal disposition. */
4579 	  reset_signal_handlers ();
4580 	  subshell_environment |= SUBSHELL_RESETTRAP;
4581 	  subshell_environment &= ~SUBSHELL_IGNTRAP;
4582 
4583 	  if (async)
4584 	    {
4585 	      if ((cmdflags & CMD_STDIN_REDIR) &&
4586 		    pipe_in == NO_PIPE &&
4587 		    (stdin_redirects (simple_command->redirects) == 0))
4588 		async_redirect_stdin ();
4589 	      setup_async_signals ();
4590 	    }
4591 
4592 	  if (async == 0)
4593 	    subshell_level++;
4594 	  execute_subshell_builtin_or_function
4595 	    (words, simple_command->redirects, builtin, func,
4596 	     pipe_in, pipe_out, async, fds_to_close,
4597 	     cmdflags);
4598 	  subshell_level--;
4599 	}
4600       else
4601 	{
4602 	  result = execute_builtin_or_function
4603 	    (words, builtin, func, simple_command->redirects, fds_to_close,
4604 	     cmdflags);
4605 	  if (builtin)
4606 	    {
4607 	      if (result > EX_SHERRBASE)
4608 		{
4609 		  switch (result)
4610 		    {
4611 		    case EX_REDIRFAIL:
4612 		    case EX_BADASSIGN:
4613 		    case EX_EXPFAIL:
4614 		      /* These errors cause non-interactive posix mode shells to exit */
4615 		      if (posixly_correct && builtin_is_special && interactive_shell == 0)
4616 			{
4617 			  last_command_exit_value = EXECUTION_FAILURE;
4618 			  jump_to_top_level (ERREXIT);
4619 			}
4620 		      break;
4621 		    case EX_DISKFALLBACK:
4622 		      /* XXX - experimental */
4623 		      executing_builtin = old_builtin;
4624 		      executing_command_builtin = old_command_builtin;
4625 		      builtin = 0;
4626 		      /* XXX - redirections will have to be performed again */
4627 		      goto execute_from_filesystem;
4628 		    }
4629 		  result = builtin_status (result);
4630 		  if (builtin_is_special)
4631 		    special_builtin_failed = 1;	/* XXX - take command builtin into account? */
4632 		}
4633 	      /* In POSIX mode, if there are assignment statements preceding
4634 		 a special builtin, they persist after the builtin
4635 		 completes. */
4636 	      if (posixly_correct && builtin_is_special && temporary_env)
4637 		merge_temporary_env ();
4638 	    }
4639 	  else		/* function */
4640 	    {
4641 	      if (result == EX_USAGE)
4642 		result = EX_BADUSAGE;
4643 	      else if (result > EX_SHERRBASE)
4644 		result = builtin_status (result);
4645 	    }
4646 
4647 	  set_pipestatus_from_exit (result);
4648 
4649 	  goto return_result;
4650 	}
4651     }
4652 
4653   if (autocd && interactive && words->word && is_dirname (words->word->word))
4654     {
4655       words = make_word_list (make_word ("--"), words);
4656       words = make_word_list (make_word ("cd"), words);
4657       xtrace_print_word_list (words, 0);
4658       func = find_function ("cd");
4659       goto run_builtin;
4660     }
4661 
4662 execute_from_filesystem:
4663   if (command_line == 0)
4664     command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
4665 
4666 #if defined (PROCESS_SUBSTITUTION)
4667   /* The old code did not test already_forked and only did this if
4668      subshell_environment&SUBSHELL_COMSUB != 0 (comsubs and procsubs). Other
4669      uses of the no-fork optimization left FIFOs in $TMPDIR */
4670   if (already_forked == 0 && (cmdflags & CMD_NO_FORK) && fifos_pending() > 0)
4671     cmdflags &= ~CMD_NO_FORK;
4672 #endif
4673   result = execute_disk_command (words, simple_command->redirects, command_line,
4674 			pipe_in, pipe_out, async, fds_to_close,
4675 			cmdflags);
4676 
4677  return_result:
4678   bind_lastarg (lastarg);
4679   FREE (command_line);
4680   dispose_words (words);
4681   if (builtin)
4682     {
4683       executing_builtin = old_builtin;
4684       executing_command_builtin = old_command_builtin;
4685     }
4686   discard_unwind_frame ("simple-command");
4687   this_command_name = (char *)NULL;	/* points to freed memory now */
4688   return (result);
4689 }
4690 
4691 /* Translate the special builtin exit statuses.  We don't really need a
4692    function for this; it's a placeholder for future work. */
4693 static int
builtin_status(result)4694 builtin_status (result)
4695      int result;
4696 {
4697   int r;
4698 
4699   switch (result)
4700     {
4701     case EX_USAGE:
4702     case EX_BADSYNTAX:
4703       r = EX_BADUSAGE;
4704       break;
4705     case EX_REDIRFAIL:
4706     case EX_BADASSIGN:
4707     case EX_EXPFAIL:
4708       r = EXECUTION_FAILURE;
4709       break;
4710     default:
4711       /* other special exit statuses not yet defined */
4712       r = (result > EX_SHERRBASE) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
4713       break;
4714     }
4715   return (r);
4716 }
4717 
4718 static int
execute_builtin(builtin,words,flags,subshell)4719 execute_builtin (builtin, words, flags, subshell)
4720      sh_builtin_func_t *builtin;
4721      WORD_LIST *words;
4722      int flags, subshell;
4723 {
4724   int result, eval_unwind, ignexit_flag;
4725   int isbltinenv, should_keep;
4726   char *error_trap;
4727 
4728   error_trap = 0;
4729   should_keep = 0;
4730 
4731   /* The eval builtin calls parse_and_execute, which does not know about
4732      the setting of flags, and always calls the execution functions with
4733      flags that will exit the shell on an error if -e is set.  If the
4734      eval builtin is being called, and we're supposed to ignore the exit
4735      value of the command, we turn the -e flag off ourselves and disable
4736      the ERR trap, then restore them when the command completes.  This is
4737      also a problem (as below) for the command and source/. builtins. */
4738   if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
4739 	(builtin == eval_builtin || (flags & CMD_COMMAND_BUILTIN) || builtin == source_builtin))
4740     {
4741       begin_unwind_frame ("eval_builtin");
4742       unwind_protect_int (exit_immediately_on_error);
4743       unwind_protect_int (builtin_ignoring_errexit);
4744       error_trap = TRAP_STRING (ERROR_TRAP);
4745       if (error_trap)
4746 	{
4747 	  error_trap = savestring (error_trap);
4748 	  add_unwind_protect (xfree, error_trap);
4749 	  add_unwind_protect (set_error_trap, error_trap);
4750 	  restore_default_signal (ERROR_TRAP);
4751 	}
4752       exit_immediately_on_error = 0;
4753       ignexit_flag = builtin_ignoring_errexit;
4754       builtin_ignoring_errexit = 1;
4755       eval_unwind = 1;
4756     }
4757   else
4758     eval_unwind = 0;
4759 
4760   /* The temporary environment for a builtin is supposed to apply to
4761      all commands executed by that builtin.  Currently, this is a
4762      problem only with the `unset', `source' and `eval' builtins.
4763      `mapfile' is a special case because it uses evalstring (same as
4764      eval or source) to run its callbacks. */
4765   /* SHOULD_KEEP is for the pop_scope call below; it only matters when
4766      posixly_correct is set, but we should propagate the temporary environment
4767      to the enclosing environment only for special builtins. */
4768   isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin || builtin == mapfile_builtin);
4769   should_keep = isbltinenv && builtin != mapfile_builtin;
4770 #if defined (HISTORY) && defined (READLINE)
4771   if (builtin == fc_builtin || builtin == read_builtin)
4772     {
4773       isbltinenv = 1;
4774       should_keep = 0;
4775     }
4776 #endif
4777 
4778   if (isbltinenv)
4779     {
4780       if (subshell == 0)
4781 	begin_unwind_frame ("builtin_env");
4782 
4783       if (temporary_env)
4784 	{
4785 	  push_scope (VC_BLTNENV, temporary_env);
4786 	  if (flags & CMD_COMMAND_BUILTIN)
4787 	    should_keep = 0;
4788 	  if (subshell == 0)
4789 	    add_unwind_protect (pop_scope, should_keep ? "1" : 0);
4790           temporary_env = (HASH_TABLE *)NULL;
4791 	}
4792     }
4793 
4794   if (subshell == 0 && builtin == eval_builtin)
4795     {
4796       if (evalnest_max > 0 && evalnest >= evalnest_max)
4797 	{
4798 	  internal_error (_("eval: maximum eval nesting level exceeded (%d)"), evalnest);
4799 	  evalnest = 0;
4800 	  jump_to_top_level (DISCARD);
4801 	}
4802       unwind_protect_int (evalnest);
4803       /* The test for subshell == 0 above doesn't make a difference */
4804       evalnest++;	/* execute_subshell_builtin_or_function sets this to 0 */
4805     }
4806   else if (subshell == 0 && builtin == source_builtin)
4807     {
4808       if (sourcenest_max > 0 && sourcenest >= sourcenest_max)
4809 	{
4810 	  internal_error (_("%s: maximum source nesting level exceeded (%d)"), this_command_name, sourcenest);
4811 	  sourcenest = 0;
4812 	  jump_to_top_level (DISCARD);
4813 	}
4814       unwind_protect_int (sourcenest);
4815       /* The test for subshell == 0 above doesn't make a difference */
4816       sourcenest++;	/* execute_subshell_builtin_or_function sets this to 0 */
4817     }
4818 
4819   /* `return' does a longjmp() back to a saved environment in execute_function.
4820      If a variable assignment list preceded the command, and the shell is
4821      running in POSIX mode, we need to merge that into the shell_variables
4822      table, since `return' is a POSIX special builtin. We don't do this if
4823      it's being run by the `command' builtin, since that's supposed to inhibit
4824      the special builtin properties. */
4825   if (posixly_correct && subshell == 0 && builtin == return_builtin && (flags & CMD_COMMAND_BUILTIN) == 0 && temporary_env)
4826     {
4827       begin_unwind_frame ("return_temp_env");
4828       add_unwind_protect (merge_temporary_env, (char *)NULL);
4829     }
4830 
4831   executing_builtin++;
4832   executing_command_builtin |= builtin == command_builtin;
4833   result = ((*builtin) (words->next));
4834 
4835   /* This shouldn't happen, but in case `return' comes back instead of
4836      longjmp'ing, we need to unwind. */
4837   if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4838     discard_unwind_frame ("return_temp_env");
4839 
4840   if (subshell == 0 && isbltinenv)
4841     run_unwind_frame ("builtin_env");
4842 
4843   if (eval_unwind)
4844     {
4845       builtin_ignoring_errexit = ignexit_flag;
4846       exit_immediately_on_error = builtin_ignoring_errexit ? 0 : errexit_flag;
4847       if (error_trap)
4848 	{
4849 	  set_error_trap (error_trap);
4850 	  free (error_trap);
4851 	}
4852       discard_unwind_frame ("eval_builtin");
4853     }
4854 
4855   return (result);
4856 }
4857 
4858 static void
maybe_restore_getopt_state(gs)4859 maybe_restore_getopt_state (gs)
4860      sh_getopt_state_t *gs;
4861 {
4862   /* If we have a local copy of OPTIND and it's at the right (current)
4863      context, then we restore getopt's internal state.  If not, we just
4864      let it go.  We know there is a local OPTIND if gs->gs_flags & 1.
4865      This is set below in execute_function() before the context is run. */
4866   if (gs->gs_flags & 1)
4867     sh_getopt_restore_istate (gs);
4868   else
4869     free (gs);
4870 }
4871 
4872 #if defined (ARRAY_VARS)
4873 void
restore_funcarray_state(fa)4874 restore_funcarray_state (fa)
4875      struct func_array_state *fa;
4876 {
4877   SHELL_VAR *nfv;
4878   ARRAY *funcname_a;
4879 
4880   array_pop (fa->source_a);
4881   array_pop (fa->lineno_a);
4882 
4883   GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4884   if (nfv == fa->funcname_v)
4885     array_pop (funcname_a);
4886 
4887   free (fa);
4888 }
4889 #endif
4890 
4891 static int
execute_function(var,words,flags,fds_to_close,async,subshell)4892 execute_function (var, words, flags, fds_to_close, async, subshell)
4893      SHELL_VAR *var;
4894      WORD_LIST *words;
4895      int flags;
4896      struct fd_bitmap *fds_to_close;
4897      int async, subshell;
4898 {
4899   int return_val, result;
4900   COMMAND *tc, *fc, *save_current;
4901   char *debug_trap, *error_trap, *return_trap;
4902 #if defined (ARRAY_VARS)
4903   SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
4904   ARRAY *funcname_a;
4905   volatile ARRAY *bash_source_a;
4906   volatile ARRAY *bash_lineno_a;
4907   struct func_array_state *fa;
4908 #endif
4909   FUNCTION_DEF *shell_fn;
4910   char *sfile, *t;
4911   sh_getopt_state_t *gs;
4912   SHELL_VAR *gv;
4913 
4914   USE_VAR(fc);
4915 
4916   if (funcnest_max > 0 && funcnest >= funcnest_max)
4917     {
4918       internal_error (_("%s: maximum function nesting level exceeded (%d)"), var->name, funcnest);
4919       funcnest = 0;	/* XXX - should we reset it somewhere else? */
4920       jump_to_top_level (DISCARD);
4921     }
4922 
4923 #if defined (ARRAY_VARS)
4924   GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4925   GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4926   GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4927 #endif
4928 
4929   tc = (COMMAND *)copy_command (function_cell (var));
4930   if (tc && (flags & CMD_IGNORE_RETURN))
4931     tc->flags |= CMD_IGNORE_RETURN;
4932 
4933   /* A limited attempt at optimization: shell functions at the end of command
4934      substitutions that are already marked NO_FORK. */
4935   if (tc && (flags & CMD_NO_FORK) && (subshell_environment & SUBSHELL_COMSUB))
4936     optimize_shell_function (tc);
4937 
4938   gs = sh_getopt_save_istate ();
4939   if (subshell == 0)
4940     {
4941       begin_unwind_frame ("function_calling");
4942       /* If the shell is in posix mode, this will push the variables in
4943 	 the temporary environment to the "current shell environment" (the
4944 	 global scope), and dispose the temporary env before setting it to
4945 	 NULL later. This behavior has disappeared from the latest edition
4946 	 of the standard, so I will eventually remove it from variables.c:
4947 	 push_var_context. */
4948       push_context (var->name, subshell, temporary_env);
4949       /* This has to be before the pop_context(), because the unwinding of
4950 	 local variables may cause the restore of a local declaration of
4951 	 OPTIND to force a getopts state reset. */
4952       add_unwind_protect (maybe_restore_getopt_state, gs);
4953       add_unwind_protect (pop_context, (char *)NULL);
4954       unwind_protect_int (line_number);
4955       unwind_protect_int (line_number_for_err_trap);
4956       unwind_protect_int (function_line_number);
4957       unwind_protect_int (return_catch_flag);
4958       unwind_protect_jmp_buf (return_catch);
4959       add_unwind_protect (dispose_command, (char *)tc);
4960       unwind_protect_pointer (this_shell_function);
4961       unwind_protect_int (funcnest);
4962       unwind_protect_int (loop_level);
4963     }
4964   else
4965     push_context (var->name, subshell, temporary_env);	/* don't unwind-protect for subshells */
4966 
4967   temporary_env = (HASH_TABLE *)NULL;
4968 
4969   this_shell_function = var;
4970   make_funcname_visible (1);
4971 
4972   debug_trap = TRAP_STRING(DEBUG_TRAP);
4973   error_trap = TRAP_STRING(ERROR_TRAP);
4974   return_trap = TRAP_STRING(RETURN_TRAP);
4975 
4976   /* The order of the unwind protects for debug_trap, error_trap and
4977      return_trap is important here!  unwind-protect commands are run
4978      in reverse order of registration.  If this causes problems, take
4979      out the xfree unwind-protect calls and live with the small memory leak. */
4980 
4981   /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4982      if the function has the trace attribute set, it inherits the DEBUG trap */
4983   if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4984     {
4985       if (subshell == 0)
4986 	{
4987 	  debug_trap = savestring (debug_trap);
4988 	  add_unwind_protect (xfree, debug_trap);
4989 	  add_unwind_protect (maybe_set_debug_trap, debug_trap);
4990 	}
4991       restore_default_signal (DEBUG_TRAP);
4992     }
4993 
4994   /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4995   if (error_trap && error_trace_mode == 0)
4996     {
4997       if (subshell == 0)
4998 	{
4999 	  error_trap = savestring (error_trap);
5000 	  add_unwind_protect (xfree, error_trap);
5001 	  add_unwind_protect (maybe_set_error_trap, error_trap);
5002 	}
5003       restore_default_signal (ERROR_TRAP);
5004     }
5005 
5006   /* Shell functions inherit the RETURN trap if function tracing is on
5007      globally or on individually for this function. */
5008   if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
5009     {
5010       if (subshell == 0)
5011 	{
5012 	  return_trap = savestring (return_trap);
5013 	  add_unwind_protect (xfree, return_trap);
5014 	  add_unwind_protect (maybe_set_return_trap, return_trap);
5015 	}
5016       restore_default_signal (RETURN_TRAP);
5017     }
5018 
5019   funcnest++;
5020 #if defined (ARRAY_VARS)
5021   /* This is quite similar to the code in shell.c and elsewhere. */
5022   shell_fn = find_function_def (this_shell_function->name);
5023   sfile = shell_fn ? shell_fn->source_file : "";
5024   array_push ((ARRAY *)funcname_a, this_shell_function->name);
5025 
5026   array_push ((ARRAY *)bash_source_a, sfile);
5027   t = itos (executing_line_number ());
5028   array_push ((ARRAY *)bash_lineno_a, t);
5029   free (t);
5030 #endif
5031 
5032 #if defined (ARRAY_VARS)
5033   fa = (struct func_array_state *)xmalloc (sizeof (struct func_array_state));
5034   fa->source_a = (ARRAY *)bash_source_a;
5035   fa->source_v = bash_source_v;
5036   fa->lineno_a = (ARRAY *)bash_lineno_a;
5037   fa->lineno_v = bash_lineno_v;
5038   fa->funcname_a = (ARRAY *)funcname_a;
5039   fa->funcname_v = funcname_v;
5040   if (subshell == 0)
5041     add_unwind_protect (restore_funcarray_state, fa);
5042 #endif
5043 
5044   /* The temporary environment for a function is supposed to apply to
5045      all commands executed within the function body. */
5046 
5047   /* Initialize BASH_ARGC and BASH_ARGV before we blow away the positional
5048      parameters */
5049   if (debugging_mode || shell_compatibility_level <= 44)
5050     init_bash_argv ();
5051 
5052   remember_args (words->next, 1);
5053 
5054   /* Update BASH_ARGV and BASH_ARGC */
5055   if (debugging_mode)
5056     {
5057       push_args (words->next);
5058       if (subshell == 0)
5059 	add_unwind_protect (pop_args, 0);
5060     }
5061 
5062   /* Number of the line on which the function body starts. */
5063   line_number = function_line_number = tc->line;
5064 
5065 #if defined (JOB_CONTROL)
5066   if (subshell)
5067     stop_pipeline (async, (COMMAND *)NULL);
5068 #endif
5069 
5070   if (shell_compatibility_level > 43)
5071     loop_level = 0;
5072 
5073   fc = tc;
5074 
5075   from_return_trap = 0;
5076 
5077   return_catch_flag++;
5078   return_val = setjmp_nosigs (return_catch);
5079 
5080   if (return_val)
5081     {
5082       result = return_catch_value;
5083       /* Run the RETURN trap in the function's context. */
5084       save_current = currently_executing_command;
5085       if (from_return_trap == 0)
5086 	run_return_trap ();
5087       currently_executing_command = save_current;
5088     }
5089   else
5090     {
5091       /* Run the debug trap here so we can trap at the start of a function's
5092 	 execution rather than the execution of the body's first command. */
5093       showing_function_line = 1;
5094       save_current = currently_executing_command;
5095       result = run_debug_trap ();
5096 #if defined (DEBUGGER)
5097       /* In debugging mode, if the DEBUG trap returns a non-zero status, we
5098 	 skip the command. */
5099       if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
5100 	{
5101 	  showing_function_line = 0;
5102 	  currently_executing_command = save_current;
5103 	  result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
5104 
5105 	  /* Run the RETURN trap in the function's context */
5106 	  save_current = currently_executing_command;
5107 	  run_return_trap ();
5108 	  currently_executing_command = save_current;
5109 	}
5110 #else
5111       result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
5112 
5113       save_current = currently_executing_command;
5114       run_return_trap ();
5115       currently_executing_command = save_current;
5116 #endif
5117       showing_function_line = 0;
5118     }
5119 
5120   /* If we have a local copy of OPTIND, note it in the saved getopts state. */
5121   gv = find_variable ("OPTIND");
5122   if (gv && gv->context == variable_context)
5123     gs->gs_flags |= 1;
5124 
5125   if (subshell == 0)
5126     run_unwind_frame ("function_calling");
5127 #if defined (ARRAY_VARS)
5128   else
5129     {
5130       restore_funcarray_state (fa);
5131       /* Restore BASH_ARGC and BASH_ARGV */
5132       if (debugging_mode)
5133 	pop_args ();
5134     }
5135 #endif
5136 
5137   if (variable_context == 0 || this_shell_function == 0)
5138     {
5139       make_funcname_visible (0);
5140 #if defined (PROCESS_SUBSTITUTION)
5141       unlink_fifo_list ();
5142 #endif
5143     }
5144 
5145   return (result);
5146 }
5147 
5148 /* A convenience routine for use by other parts of the shell to execute
5149    a particular shell function. */
5150 int
execute_shell_function(var,words)5151 execute_shell_function (var, words)
5152      SHELL_VAR *var;
5153      WORD_LIST *words;
5154 {
5155   int ret;
5156   struct fd_bitmap *bitmap;
5157 
5158   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
5159   begin_unwind_frame ("execute-shell-function");
5160   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
5161 
5162   ret = execute_function (var, words, 0, bitmap, 0, 0);
5163 
5164   dispose_fd_bitmap (bitmap);
5165   discard_unwind_frame ("execute-shell-function");
5166 
5167   return ret;
5168 }
5169 
5170 /* Execute a shell builtin or function in a subshell environment.  This
5171    routine does not return; it only calls exit().  If BUILTIN is non-null,
5172    it points to a function to call to execute a shell builtin; otherwise
5173    VAR points at the body of a function to execute.  WORDS is the arguments
5174    to the command, REDIRECTS specifies redirections to perform before the
5175    command is executed. */
5176 static void
execute_subshell_builtin_or_function(words,redirects,builtin,var,pipe_in,pipe_out,async,fds_to_close,flags)5177 execute_subshell_builtin_or_function (words, redirects, builtin, var,
5178 				      pipe_in, pipe_out, async, fds_to_close,
5179 				      flags)
5180      WORD_LIST *words;
5181      REDIRECT *redirects;
5182      sh_builtin_func_t *builtin;
5183      SHELL_VAR *var;
5184      int pipe_in, pipe_out, async;
5185      struct fd_bitmap *fds_to_close;
5186      int flags;
5187 {
5188   int result, r, funcvalue;
5189 #if defined (JOB_CONTROL)
5190   int jobs_hack;
5191 
5192   jobs_hack = (builtin == jobs_builtin) &&
5193 		((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
5194 #endif
5195 
5196   /* A subshell is neither a login shell nor interactive. */
5197   login_shell = interactive = 0;
5198   if (builtin == eval_builtin)
5199     evalnest = 0;
5200   else if (builtin == source_builtin)
5201     sourcenest = 0;
5202 
5203   if (async)
5204     subshell_environment |= SUBSHELL_ASYNC;
5205   if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
5206     subshell_environment |= SUBSHELL_PIPE;
5207 
5208   maybe_make_export_env ();	/* XXX - is this needed? */
5209 
5210 #if defined (JOB_CONTROL)
5211   /* Eradicate all traces of job control after we fork the subshell, so
5212      all jobs begun by this subshell are in the same process group as
5213      the shell itself. */
5214 
5215   /* Allow the output of `jobs' to be piped. */
5216   if (jobs_hack)
5217     kill_current_pipeline ();
5218   else
5219     without_job_control ();
5220 
5221   set_sigchld_handler ();
5222 #else
5223   without_job_control ();
5224 #endif /* JOB_CONTROL */
5225 
5226   set_sigint_handler ();
5227 
5228   if (fds_to_close)
5229     close_fd_bitmap (fds_to_close);
5230 
5231   do_piping (pipe_in, pipe_out);
5232 
5233   if (do_redirections (redirects, RX_ACTIVE) != 0)
5234     exit (EXECUTION_FAILURE);
5235 
5236   if (builtin)
5237     {
5238       /* Give builtins a place to jump back to on failure,
5239 	 so we don't go back up to main(). */
5240       result = setjmp_nosigs (top_level);
5241 
5242       /* Give the return builtin a place to jump to when executed in a subshell
5243          or pipeline */
5244       funcvalue = 0;
5245       if (return_catch_flag && builtin == return_builtin)
5246         funcvalue = setjmp_nosigs (return_catch);
5247 
5248       if (result == EXITPROG)
5249 	subshell_exit (last_command_exit_value);
5250       else if (result)
5251 	subshell_exit (EXECUTION_FAILURE);
5252       else if (funcvalue)
5253 	subshell_exit (return_catch_value);
5254       else
5255 	{
5256 	  r = execute_builtin (builtin, words, flags, 1);
5257 	  fflush (stdout);
5258 	  if (r == EX_USAGE)
5259 	    r = EX_BADUSAGE;
5260 	  /* XXX - experimental */
5261 	  else if (r == EX_DISKFALLBACK)
5262 	    {
5263 	      char *command_line;
5264 
5265 	      command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
5266 	      r = execute_disk_command (words, (REDIRECT *)0, command_line,
5267 		  -1, -1, async, (struct fd_bitmap *)0, flags|CMD_NO_FORK);
5268 	    }
5269 	  subshell_exit (r);
5270 	}
5271     }
5272   else
5273     {
5274       r = execute_function (var, words, flags, fds_to_close, async, 1);
5275       fflush (stdout);
5276       subshell_exit (r);
5277     }
5278 }
5279 
5280 /* Execute a builtin or function in the current shell context.  If BUILTIN
5281    is non-null, it is the builtin command to execute, otherwise VAR points
5282    to the body of a function.  WORDS are the command's arguments, REDIRECTS
5283    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
5284    file descriptors to close.
5285 
5286    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
5287    not undone before this function returns. */
5288 static int
execute_builtin_or_function(words,builtin,var,redirects,fds_to_close,flags)5289 execute_builtin_or_function (words, builtin, var, redirects,
5290 			     fds_to_close, flags)
5291      WORD_LIST *words;
5292      sh_builtin_func_t *builtin;
5293      SHELL_VAR *var;
5294      REDIRECT *redirects;
5295      struct fd_bitmap *fds_to_close;
5296      int flags;
5297 {
5298   int result;
5299   REDIRECT *saved_undo_list;
5300 #if defined (PROCESS_SUBSTITUTION)
5301   int ofifo, nfifo, osize;
5302   void *ofifo_list;
5303 #endif
5304 
5305 #if defined (PROCESS_SUBSTITUTION)
5306   begin_unwind_frame ("saved_fifos");
5307   /* If we return, we longjmp and don't get a chance to restore the old
5308      fifo list, so we add an unwind protect to free it */
5309   ofifo = num_fifos ();
5310   ofifo_list = copy_fifo_list (&osize);
5311   if (ofifo_list)
5312     add_unwind_protect (xfree, ofifo_list);
5313 #endif
5314 
5315   if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
5316     {
5317       undo_partial_redirects ();
5318       dispose_exec_redirects ();
5319 #if defined (PROCESS_SUBSTITUTION)
5320       free (ofifo_list);
5321 #endif
5322       return (EX_REDIRFAIL);	/* was EXECUTION_FAILURE */
5323     }
5324 
5325   saved_undo_list = redirection_undo_list;
5326 
5327   /* Calling the "exec" builtin changes redirections forever. */
5328   if (builtin == exec_builtin)
5329     {
5330       dispose_redirects (saved_undo_list);
5331       saved_undo_list = exec_redirection_undo_list;
5332       exec_redirection_undo_list = (REDIRECT *)NULL;
5333     }
5334   else
5335     dispose_exec_redirects ();
5336 
5337   if (saved_undo_list)
5338     {
5339       begin_unwind_frame ("saved-redirects");
5340       add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
5341     }
5342 
5343   redirection_undo_list = (REDIRECT *)NULL;
5344 
5345   if (builtin)
5346     result = execute_builtin (builtin, words, flags, 0);
5347   else
5348     result = execute_function (var, words, flags, fds_to_close, 0, 0);
5349 
5350   /* We do this before undoing the effects of any redirections. */
5351   fflush (stdout);
5352   fpurge (stdout);
5353   if (ferror (stdout))
5354     clearerr (stdout);
5355 
5356   /* If we are executing the `command' builtin, but this_shell_builtin is
5357      set to `exec_builtin', we know that we have something like
5358      `command exec [redirection]', since otherwise `exec' would have
5359      overwritten the shell and we wouldn't get here.  In this case, we
5360      want to behave as if the `command' builtin had not been specified
5361      and preserve the redirections. */
5362   if (builtin == command_builtin && this_shell_builtin == exec_builtin)
5363     {
5364       int discard;
5365 
5366       discard = 0;
5367       if (saved_undo_list)
5368 	{
5369 	  dispose_redirects (saved_undo_list);
5370 	  discard = 1;
5371 	}
5372       redirection_undo_list = exec_redirection_undo_list;
5373       saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
5374       if (discard)
5375 	discard_unwind_frame ("saved-redirects");
5376     }
5377 
5378   if (saved_undo_list)
5379     {
5380       redirection_undo_list = saved_undo_list;
5381       discard_unwind_frame ("saved-redirects");
5382     }
5383 
5384   undo_partial_redirects ();
5385 
5386 #if defined (PROCESS_SUBSTITUTION)
5387   /* Close any FIFOs created by this builtin or function. */
5388   nfifo = num_fifos ();
5389   if (nfifo > ofifo)
5390     close_new_fifos (ofifo_list, osize);
5391   if (ofifo_list)
5392     free (ofifo_list);
5393   discard_unwind_frame ("saved_fifos");
5394 #endif
5395 
5396   return (result);
5397 }
5398 
5399 void
setup_async_signals()5400 setup_async_signals ()
5401 {
5402 #if defined (__BEOS__)
5403   set_signal_handler (SIGHUP, SIG_IGN);	/* they want csh-like behavior */
5404 #endif
5405 
5406 #if defined (JOB_CONTROL)
5407   if (job_control == 0)
5408 #endif
5409     {
5410       /* Make sure we get the original signal dispositions now so we don't
5411 	 confuse the trap builtin later if the subshell tries to use it to
5412 	 reset SIGINT/SIGQUIT.  Don't call set_signal_ignored; that sets
5413 	 the value of original_signals to SIG_IGN. Posix interpretation 751. */
5414       get_original_signal (SIGINT);
5415       set_signal_handler (SIGINT, SIG_IGN);
5416 
5417       get_original_signal (SIGQUIT);
5418       set_signal_handler (SIGQUIT, SIG_IGN);
5419     }
5420 }
5421 
5422 /* Execute a simple command that is hopefully defined in a disk file
5423    somewhere.
5424 
5425    1) fork ()
5426    2) connect pipes
5427    3) look up the command
5428    4) do redirections
5429    5) execve ()
5430    6) If the execve failed, see if the file has executable mode set.
5431    If so, and it isn't a directory, then execute its contents as
5432    a shell script.
5433 
5434    Note that the filename hashing stuff has to take place up here,
5435    in the parent.  This is probably why the Bourne style shells
5436    don't handle it, since that would require them to go through
5437    this gnarly hair, for no good reason.
5438 
5439    NOTE: callers expect this to fork or exit(). */
5440 
5441 /* Name of a shell function to call when a command name is not found. */
5442 #ifndef NOTFOUND_HOOK
5443 #  define NOTFOUND_HOOK "command_not_found_handle"
5444 #endif
5445 
5446 static int
execute_disk_command(words,redirects,command_line,pipe_in,pipe_out,async,fds_to_close,cmdflags)5447 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
5448 		      async, fds_to_close, cmdflags)
5449      WORD_LIST *words;
5450      REDIRECT *redirects;
5451      char *command_line;
5452      int pipe_in, pipe_out, async;
5453      struct fd_bitmap *fds_to_close;
5454      int cmdflags;
5455 {
5456   char *pathname, *command, **args, *p;
5457   int nofork, stdpath, result, fork_flags;
5458   pid_t pid;
5459   SHELL_VAR *hookf;
5460   WORD_LIST *wl;
5461 
5462   stdpath = (cmdflags & CMD_STDPATH);	/* use command -p path */
5463   nofork = (cmdflags & CMD_NO_FORK);	/* Don't fork, just exec, if no pipes */
5464   pathname = words->word->word;
5465 
5466   p = 0;
5467   result = EXECUTION_SUCCESS;
5468 #if defined (RESTRICTED_SHELL)
5469   command = (char *)NULL;
5470   if (restricted && mbschr (pathname, '/'))
5471     {
5472       internal_error (_("%s: restricted: cannot specify `/' in command names"),
5473 		    pathname);
5474       result = last_command_exit_value = EXECUTION_FAILURE;
5475 
5476       /* If we're not going to fork below, we must already be in a child
5477          process or a context in which it's safe to call exit(2).  */
5478       if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5479 	exit (last_command_exit_value);
5480       else
5481 	goto parent_return;
5482     }
5483 #endif /* RESTRICTED_SHELL */
5484 
5485   command = search_for_command (pathname, CMDSRCH_HASH|(stdpath ? CMDSRCH_STDPATH : 0));
5486   QUIT;
5487 
5488   if (command)
5489     {
5490       /* If we're optimizing out the fork (implicit `exec'), decrement the
5491 	 shell level like `exec' would do. */
5492 #if 0 /* TAG: bash-5.2 psmith 10/11/2020 */
5493       if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE && (subshell_environment & SUBSHELL_PIPE) == 0)
5494 #else
5495       if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5496 #endif
5497 	adjust_shell_level (-1);
5498 
5499       maybe_make_export_env ();
5500       put_command_name_into_env (command);
5501     }
5502 
5503   /* We have to make the child before we check for the non-existence
5504      of COMMAND, since we want the error messages to be redirected. */
5505   /* If we can get away without forking and there are no pipes to deal with,
5506      don't bother to fork, just directly exec the command. */
5507   if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5508     pid = 0;
5509   else
5510     {
5511       fork_flags = async ? FORK_ASYNC : 0;
5512       pid = make_child (p = savestring (command_line), fork_flags);
5513     }
5514 
5515   if (pid == 0)
5516     {
5517       int old_interactive;
5518 
5519       reset_terminating_signals ();	/* XXX */
5520       /* Cancel traps, in trap.c. */
5521       restore_original_signals ();
5522       subshell_environment &= ~SUBSHELL_IGNTRAP;
5523 
5524 #if defined (JOB_CONTROL)
5525       FREE (p);
5526 #endif
5527 
5528       /* restore_original_signals may have undone the work done
5529 	 by make_child to ensure that SIGINT and SIGQUIT are ignored
5530 	 in asynchronous children. */
5531       if (async)
5532 	{
5533 	  if ((cmdflags & CMD_STDIN_REDIR) &&
5534 		pipe_in == NO_PIPE &&
5535 		(stdin_redirects (redirects) == 0))
5536 	    async_redirect_stdin ();
5537 	  setup_async_signals ();
5538 	}
5539 
5540       /* This functionality is now provided by close-on-exec of the
5541 	 file descriptors manipulated by redirection and piping.
5542 	 Some file descriptors still need to be closed in all children
5543 	 because of the way bash does pipes; fds_to_close is a
5544 	 bitmap of all such file descriptors. */
5545       if (fds_to_close)
5546 	close_fd_bitmap (fds_to_close);
5547 
5548       do_piping (pipe_in, pipe_out);
5549 
5550       old_interactive = interactive;
5551       if (async)
5552 	interactive = 0;
5553 
5554       subshell_environment |= SUBSHELL_FORK;	/* XXX - was just = */
5555 
5556 #if defined (PROCESS_SUBSTITUTION) && !defined (HAVE_DEV_FD)
5557       clear_fifo_list ();	/* XXX - we haven't created any FIFOs */
5558 #endif
5559 
5560       if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
5561 	{
5562 #if defined (PROCESS_SUBSTITUTION)
5563 	  /* Try to remove named pipes that may have been created as the
5564 	     result of redirections. */
5565 	  unlink_all_fifos ();
5566 #endif /* PROCESS_SUBSTITUTION */
5567 	  exit (EXECUTION_FAILURE);
5568 	}
5569 
5570 #if defined (PROCESS_SUBSTITUTION) && !defined (HAVE_DEV_FD)
5571       /* This should only contain FIFOs created as part of redirection
5572 	 expansion. */
5573       unlink_all_fifos ();
5574 #endif
5575 
5576       if (async)
5577 	interactive = old_interactive;
5578 
5579       if (command == 0)
5580 	{
5581 	  hookf = find_function (NOTFOUND_HOOK);
5582 	  if (hookf == 0)
5583 	    {
5584 	      /* Make sure filenames are displayed using printable characters */
5585 	      pathname = printable_filename (pathname, 0);
5586 	      internal_error (_("%s: command not found"), pathname);
5587 	      exit (EX_NOTFOUND);	/* Posix.2 says the exit status is 127 */
5588 	    }
5589 
5590 	  /* We don't want to manage process groups for processes we start
5591 	     from here, so we turn off job control and don't attempt to
5592 	     manipulate the terminal's process group. */
5593 	  without_job_control ();
5594 
5595 #if defined (JOB_CONTROL)
5596 	  set_sigchld_handler ();
5597 #endif
5598 
5599 	  wl = make_word_list (make_word (NOTFOUND_HOOK), words);
5600 	  exit (execute_shell_function (hookf, wl));
5601 	}
5602 
5603       /* Execve expects the command name to be in args[0].  So we
5604 	 leave it there, in the same format that the user used to
5605 	 type it in. */
5606       args = strvec_from_word_list (words, 0, 0, (int *)NULL);
5607       exit (shell_execve (command, args, export_env));
5608     }
5609   else
5610     {
5611 parent_return:
5612       QUIT;
5613 
5614       /* Make sure that the pipes are closed in the parent. */
5615       close_pipes (pipe_in, pipe_out);
5616 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5617 #if 0
5618       if (variable_context == 0)
5619         unlink_fifo_list ();
5620 #endif
5621 #endif
5622       FREE (command);
5623       return (result);
5624     }
5625 }
5626 
5627 /* CPP defines to decide whether a particular index into the #! line
5628    corresponds to a valid interpreter name or argument character, or
5629    whitespace.  The MSDOS define is to allow \r to be treated the same
5630    as \n. */
5631 
5632 #if !defined (MSDOS)
5633 #  define STRINGCHAR(ind) \
5634     (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
5635 #  define WHITECHAR(ind) \
5636     (ind < sample_len && whitespace (sample[ind]))
5637 #else	/* MSDOS */
5638 #  define STRINGCHAR(ind) \
5639     (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
5640 #  define WHITECHAR(ind) \
5641     (ind < sample_len && whitespace (sample[ind]))
5642 #endif	/* MSDOS */
5643 
5644 static char *
getinterp(sample,sample_len,endp)5645 getinterp (sample, sample_len, endp)
5646      char *sample;
5647      int sample_len, *endp;
5648 {
5649   register int i;
5650   char *execname;
5651   int start;
5652 
5653   /* Find the name of the interpreter to exec. */
5654   for (i = 2; i < sample_len && whitespace (sample[i]); i++)
5655     ;
5656 
5657   for (start = i; STRINGCHAR(i); i++)
5658     ;
5659 
5660   execname = substring (sample, start, i);
5661 
5662   if (endp)
5663     *endp = i;
5664   return execname;
5665 }
5666 
5667 #if !defined (HAVE_HASH_BANG_EXEC)
5668 /* If the operating system on which we're running does not handle
5669    the #! executable format, then help out.  SAMPLE is the text read
5670    from the file, SAMPLE_LEN characters.  COMMAND is the name of
5671    the script; it and ARGS, the arguments given by the user, will
5672    become arguments to the specified interpreter.  ENV is the environment
5673    to pass to the interpreter.
5674 
5675    The word immediately following the #! is the interpreter to execute.
5676    A single argument to the interpreter is allowed. */
5677 
5678 static int
execute_shell_script(sample,sample_len,command,args,env)5679 execute_shell_script (sample, sample_len, command, args, env)
5680      char *sample;
5681      int sample_len;
5682      char *command;
5683      char **args, **env;
5684 {
5685   char *execname, *firstarg;
5686   int i, start, size_increment, larry;
5687 
5688   /* Find the name of the interpreter to exec. */
5689   execname = getinterp (sample, sample_len, &i);
5690   size_increment = 1;
5691 
5692   /* Now the argument, if any. */
5693   for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
5694     ;
5695 
5696   /* If there is more text on the line, then it is an argument for the
5697      interpreter. */
5698 
5699   if (STRINGCHAR(i))
5700     {
5701       for (start = i; STRINGCHAR(i); i++)
5702 	;
5703       firstarg = substring ((char *)sample, start, i);
5704       size_increment = 2;
5705     }
5706 
5707   larry = strvec_len (args) + size_increment;
5708   args = strvec_resize (args, larry + 1);
5709 
5710   for (i = larry - 1; i; i--)
5711     args[i] = args[i - size_increment];
5712 
5713   args[0] = execname;
5714   if (firstarg)
5715     {
5716       args[1] = firstarg;
5717       args[2] = command;
5718     }
5719   else
5720     args[1] = command;
5721 
5722   args[larry] = (char *)NULL;
5723 
5724   return (shell_execve (execname, args, env));
5725 }
5726 #undef STRINGCHAR
5727 #undef WHITECHAR
5728 
5729 #endif /* !HAVE_HASH_BANG_EXEC */
5730 
5731 static void
initialize_subshell()5732 initialize_subshell ()
5733 {
5734 #if defined (ALIAS)
5735   /* Forget about any aliases that we knew of.  We are in a subshell. */
5736   delete_all_aliases ();
5737 #endif /* ALIAS */
5738 
5739 #if defined (HISTORY)
5740   /* Forget about the history lines we have read.  This is a non-interactive
5741      subshell. */
5742   history_lines_this_session = 0;
5743 #endif
5744 
5745   /* Forget about the way job control was working. We are in a subshell. */
5746   without_job_control ();
5747 
5748 #if defined (JOB_CONTROL)
5749   set_sigchld_handler ();
5750   init_job_stats ();
5751 #endif /* JOB_CONTROL */
5752 
5753   /* Reset the values of the shell flags and options. */
5754   reset_shell_flags ();
5755   reset_shell_options ();
5756   reset_shopt_options ();
5757 
5758   /* Zero out builtin_env, since this could be a shell script run from a
5759      sourced file with a temporary environment supplied to the `source/.'
5760      builtin.  Such variables are not supposed to be exported (empirical
5761      testing with sh and ksh).  Just throw it away; don't worry about a
5762      memory leak. */
5763   if (vc_isbltnenv (shell_variables))
5764     shell_variables = shell_variables->down;
5765 
5766   clear_unwind_protect_list (0);
5767   /* XXX -- are there other things we should be resetting here? */
5768   parse_and_execute_level = 0;		/* nothing left to restore it */
5769 
5770   /* We're no longer inside a shell function. */
5771   variable_context = return_catch_flag = funcnest = evalnest = sourcenest = 0;
5772 
5773   executing_list = 0;		/* XXX */
5774 
5775   /* If we're not interactive, close the file descriptor from which we're
5776      reading the current shell script. */
5777   if (interactive_shell == 0)
5778     unset_bash_input (0);
5779 }
5780 
5781 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5782 #  define SETOSTYPE(x)	__setostype(x)
5783 #else
5784 #  define SETOSTYPE(x)
5785 #endif
5786 
5787 #define HASH_BANG_BUFSIZ	128
5788 
5789 #define READ_SAMPLE_BUF(file, buf, len) \
5790   do \
5791     { \
5792       fd = open(file, O_RDONLY); \
5793       if (fd >= 0) \
5794 	{ \
5795 	  len = read (fd, buf, HASH_BANG_BUFSIZ); \
5796 	  close (fd); \
5797 	} \
5798       else \
5799 	len = -1; \
5800     } \
5801   while (0)
5802 
5803 /* Call execve (), handling interpreting shell scripts, and handling
5804    exec failures. */
5805 int
shell_execve(command,args,env)5806 shell_execve (command, args, env)
5807      char *command;
5808      char **args, **env;
5809 {
5810   int larray, i, fd;
5811   char sample[HASH_BANG_BUFSIZ];
5812   int sample_len;
5813 
5814   SETOSTYPE (0);		/* Some systems use for USG/POSIX semantics */
5815   execve (command, args, env);
5816   i = errno;			/* error from execve() */
5817   CHECK_TERMSIG;
5818   SETOSTYPE (1);
5819 
5820   /* If we get to this point, then start checking out the file.
5821      Maybe it is something we can hack ourselves. */
5822   if (i != ENOEXEC)
5823     {
5824       /* make sure this is set correctly for file_error/report_error */
5825       last_command_exit_value = (i == ENOENT) ?  EX_NOTFOUND : EX_NOEXEC; /* XXX Posix.2 says that exit status is 126 */
5826       if (file_isdir (command))
5827 #if defined (EISDIR)
5828 	internal_error (_("%s: %s"), command, strerror (EISDIR));
5829 #else
5830 	internal_error (_("%s: is a directory"), command);
5831 #endif
5832       else if (executable_file (command) == 0)
5833 	{
5834 	  errno = i;
5835 	  file_error (command);
5836 	}
5837       /* errors not involving the path argument to execve. */
5838       else if (i == E2BIG || i == ENOMEM)
5839 	{
5840 	  errno = i;
5841 	  file_error (command);
5842 	}
5843       else
5844 	{
5845 	  /* The file has the execute bits set, but the kernel refuses to
5846 	     run it for some reason.  See why. */
5847 #if defined (HAVE_HASH_BANG_EXEC)
5848 	  READ_SAMPLE_BUF (command, sample, sample_len);
5849 	  if (sample_len > 0)
5850 	    sample[sample_len - 1] = '\0';
5851 	  if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5852 	    {
5853 	      char *interp;
5854 	      int ilen;
5855 
5856 	      interp = getinterp (sample, sample_len, (int *)NULL);
5857 	      ilen = strlen (interp);
5858 	      errno = i;
5859 	      if (interp[ilen - 1] == '\r')
5860 		{
5861 		  interp = xrealloc (interp, ilen + 2);
5862 		  interp[ilen - 1] = '^';
5863 		  interp[ilen] = 'M';
5864 		  interp[ilen + 1] = '\0';
5865 		}
5866 	      sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
5867 	      FREE (interp);
5868 	      return (EX_NOEXEC);
5869 	    }
5870 #endif
5871 	  errno = i;
5872 	  file_error (command);
5873 	}
5874       return (last_command_exit_value);
5875     }
5876 
5877   /* This file is executable.
5878      If it begins with #!, then help out people with losing operating
5879      systems.  Otherwise, check to see if it is a binary file by seeing
5880      if the contents of the first line (or up to 80 characters) are in the
5881      ASCII set.  If it's a text file, execute the contents as shell commands,
5882      otherwise return 126 (EX_BINARY_FILE). */
5883   READ_SAMPLE_BUF (command, sample, sample_len);
5884 
5885   if (sample_len == 0)
5886     return (EXECUTION_SUCCESS);
5887 
5888   /* Is this supposed to be an executable script?
5889      If so, the format of the line is "#! interpreter [argument]".
5890      A single argument is allowed.  The BSD kernel restricts
5891      the length of the entire line to 32 characters (32 bytes
5892      being the size of the BSD exec header), but we allow 80
5893      characters. */
5894   if (sample_len > 0)
5895     {
5896 #if !defined (HAVE_HASH_BANG_EXEC)
5897       if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5898 	return (execute_shell_script (sample, sample_len, command, args, env));
5899       else
5900 #endif
5901       if (check_binary_file (sample, sample_len))
5902 	{
5903 	  internal_error (_("%s: cannot execute binary file: %s"), command, strerror (i));
5904 	  errno = i;
5905 	  return (EX_BINARY_FILE);
5906 	}
5907     }
5908 
5909   /* We have committed to attempting to execute the contents of this file
5910      as shell commands. */
5911 
5912   reset_parser ();
5913   initialize_subshell ();
5914 
5915   set_sigint_handler ();
5916 
5917   /* Insert the name of this shell into the argument list. */
5918   larray = strvec_len (args) + 1;
5919   args = strvec_resize (args, larray + 1);
5920 
5921   for (i = larray - 1; i; i--)
5922     args[i] = args[i - 1];
5923 
5924   args[0] = shell_name;
5925   args[1] = command;
5926   args[larray] = (char *)NULL;
5927 
5928   if (args[0][0] == '-')
5929     args[0]++;
5930 
5931 #if defined (RESTRICTED_SHELL)
5932   if (restricted)
5933     change_flag ('r', FLAG_OFF);
5934 #endif
5935 
5936   if (subshell_argv)
5937     {
5938       /* Can't free subshell_argv[0]; that is shell_name. */
5939       for (i = 1; i < subshell_argc; i++)
5940 	free (subshell_argv[i]);
5941       free (subshell_argv);
5942     }
5943 
5944   dispose_command (currently_executing_command);	/* XXX */
5945   currently_executing_command = (COMMAND *)NULL;
5946 
5947   subshell_argc = larray;
5948   subshell_argv = args;
5949   subshell_envp = env;
5950 
5951   unbind_args ();	/* remove the positional parameters */
5952 
5953 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5954   clear_fifo_list ();	/* pipe fds are what they are now */
5955 #endif
5956 
5957   sh_longjmp (subshell_top_level, 1);
5958   /*NOTREACHED*/
5959 }
5960 
5961 static int
execute_intern_function(name,funcdef)5962 execute_intern_function (name, funcdef)
5963      WORD_DESC *name;
5964      FUNCTION_DEF *funcdef;
5965 {
5966   SHELL_VAR *var;
5967   char *t;
5968 
5969   if (check_identifier (name, posixly_correct) == 0)
5970     {
5971       if (posixly_correct && interactive_shell == 0)
5972 	{
5973 	  last_command_exit_value = EX_BADUSAGE;
5974 	  jump_to_top_level (ERREXIT);
5975 	}
5976       return (EXECUTION_FAILURE);
5977     }
5978 
5979   if (strchr (name->word, CTLESC))	/* WHY? */
5980     {
5981       t = dequote_escapes (name->word);
5982       free (name->word);
5983       name->word = t;
5984     }
5985 
5986   /* Posix interpretation 383 */
5987   if (posixly_correct && find_special_builtin (name->word))
5988     {
5989       internal_error (_("`%s': is a special builtin"), name->word);
5990       last_command_exit_value = EX_BADUSAGE;
5991       jump_to_top_level (interactive_shell ? DISCARD : ERREXIT);
5992     }
5993 
5994   var = find_function (name->word);
5995   if (var && (readonly_p (var) || noassign_p (var)))
5996     {
5997       if (readonly_p (var))
5998 	internal_error (_("%s: readonly function"), var->name);
5999       return (EXECUTION_FAILURE);
6000     }
6001 
6002 #if defined (DEBUGGER)
6003   bind_function_def (name->word, funcdef, 1);
6004 #endif
6005 
6006   bind_function (name->word, funcdef->command);
6007   return (EXECUTION_SUCCESS);
6008 }
6009 
6010 #if defined (INCLUDE_UNUSED)
6011 #if defined (PROCESS_SUBSTITUTION)
6012 void
close_all_files()6013 close_all_files ()
6014 {
6015   register int i, fd_table_size;
6016 
6017   fd_table_size = getdtablesize ();
6018   if (fd_table_size > 256)	/* clamp to a reasonable value */
6019     fd_table_size = 256;
6020 
6021   for (i = 3; i < fd_table_size; i++)
6022     close (i);
6023 }
6024 #endif /* PROCESS_SUBSTITUTION */
6025 #endif
6026 
6027 static void
close_pipes(in,out)6028 close_pipes (in, out)
6029      int in, out;
6030 {
6031   if (in >= 0)
6032     close (in);
6033   if (out >= 0)
6034     close (out);
6035 }
6036 
6037 static void
dup_error(oldd,newd)6038 dup_error (oldd, newd)
6039      int oldd, newd;
6040 {
6041   sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
6042 }
6043 
6044 /* Redirect input and output to be from and to the specified pipes.
6045    NO_PIPE and REDIRECT_BOTH are handled correctly. */
6046 static void
do_piping(pipe_in,pipe_out)6047 do_piping (pipe_in, pipe_out)
6048      int pipe_in, pipe_out;
6049 {
6050   if (pipe_in != NO_PIPE)
6051     {
6052       if (dup2 (pipe_in, 0) < 0)
6053 	dup_error (pipe_in, 0);
6054       if (pipe_in > 0)
6055 	close (pipe_in);
6056 #ifdef __CYGWIN__
6057       /* Let stdio know the fd may have changed from text to binary mode. */
6058       freopen (NULL, "r", stdin);
6059 #endif /* __CYGWIN__ */
6060     }
6061   if (pipe_out != NO_PIPE)
6062     {
6063       if (pipe_out != REDIRECT_BOTH)
6064 	{
6065 	  if (dup2 (pipe_out, 1) < 0)
6066 	    dup_error (pipe_out, 1);
6067 	  if (pipe_out == 0 || pipe_out > 1)
6068 	    close (pipe_out);
6069 	}
6070       else
6071 	{
6072 	  if (dup2 (1, 2) < 0)
6073 	    dup_error (1, 2);
6074 	}
6075 #ifdef __CYGWIN__
6076       /* Let stdio know the fd may have changed from text to binary mode, and
6077 	 make sure to preserve stdout line buffering. */
6078       freopen (NULL, "w", stdout);
6079       sh_setlinebuf (stdout);
6080 #endif /* __CYGWIN__ */
6081     }
6082 }
6083