]> git.ipfire.org Git - thirdparty/bash.git/blob - execute_cmd.c
Bash-5.1 patch 4: fix key-value pair associative array assignment word expansions
[thirdparty/bash.git] / execute_cmd.c
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 *
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
324 dispose_fd_bitmap (fdbp)
325 struct fd_bitmap *fdbp;
326 {
327 FREE (fdbp->bitmap);
328 free (fdbp);
329 }
330
331 void
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
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
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
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
447 cleanup_redirects (list)
448 REDIRECT *list;
449 {
450 do_redirections (list, RX_ACTIVE);
451 dispose_redirects (list);
452 }
453
454 void
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
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
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
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
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
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
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
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
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
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
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
1551 /* We are in a subshell, so forget that we are running a trap handler or
1552 that the signal handler has changed (we haven't changed it!) */
1553 if (running_trap > 0)
1554 {
1555 run_trap_cleanup (running_trap - 1);
1556 running_trap = 0; /* XXX - maybe leave this */
1557 }
1558
1559 /* Make sure restore_original_signals doesn't undo the work done by
1560 make_child to ensure that asynchronous children are immune to SIGINT
1561 and SIGQUIT. Turn off asynchronous to make sure more subshells are
1562 not spawned. */
1563 if (asynchronous)
1564 {
1565 setup_async_signals ();
1566 asynchronous = 0;
1567 }
1568 else
1569 set_sigint_handler ();
1570
1571 #if defined (JOB_CONTROL)
1572 set_sigchld_handler ();
1573 #endif /* JOB_CONTROL */
1574
1575 /* Delete all traces that there were any jobs running. This is
1576 only for subshells. */
1577 without_job_control ();
1578
1579 if (fds_to_close)
1580 close_fd_bitmap (fds_to_close);
1581
1582 do_piping (pipe_in, pipe_out);
1583
1584 #if defined (COPROCESS_SUPPORT)
1585 coproc_closeall ();
1586 #endif
1587
1588 #if defined (PROCESS_SUBSTITUTION)
1589 clear_fifo_list (); /* XXX- we haven't created any FIFOs */
1590 #endif
1591
1592 /* If this is a user subshell, set a flag if stdin was redirected.
1593 This is used later to decide whether to redirect fd 0 to
1594 /dev/null for async commands in the subshell. This adds more
1595 sh compatibility, but I'm not sure it's the right thing to do.
1596 Note that an input pipe to a compound command suffices to inhibit
1597 the implicit /dev/null redirection for asynchronous commands
1598 executed as part of that compound command. */
1599 if (user_subshell)
1600 {
1601 stdin_redir = stdin_redirects (command->redirects) || pipe_in != NO_PIPE;
1602 #if 0
1603 restore_default_signal (EXIT_TRAP); /* XXX - reset_signal_handlers above */
1604 #endif
1605 }
1606 else if (shell_control_structure (command->type) && pipe_in != NO_PIPE)
1607 stdin_redir = 1;
1608
1609 /* If this is an asynchronous command (command &), we want to
1610 redirect the standard input from /dev/null in the absence of
1611 any specific redirection involving stdin. */
1612 if (should_redir_stdin && stdin_redir == 0)
1613 async_redirect_stdin ();
1614
1615 #if defined (BUFFERED_INPUT)
1616 /* In any case, we are not reading our command input from stdin. */
1617 default_buffered_input = -1;
1618 #endif
1619
1620 #if 0 /* TAG: bash-5.2 */
1621 if (user_subshell && command->type == cm_subshell)
1622 optimize_subshell_command (command->value.Subshell->command);
1623 #endif
1624
1625 /* Do redirections, then dispose of them before recursive call. */
1626 if (command->redirects)
1627 {
1628 if (do_redirections (command->redirects, RX_ACTIVE) != 0)
1629 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
1630
1631 dispose_redirects (command->redirects);
1632 command->redirects = (REDIRECT *)NULL;
1633 }
1634
1635 if (command->type == cm_subshell)
1636 tcom = command->value.Subshell->command;
1637 else if (user_coproc)
1638 tcom = command->value.Coproc->command;
1639 else
1640 tcom = command;
1641
1642 if (command->flags & CMD_TIME_PIPELINE)
1643 tcom->flags |= CMD_TIME_PIPELINE;
1644 if (command->flags & CMD_TIME_POSIX)
1645 tcom->flags |= CMD_TIME_POSIX;
1646
1647 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1648 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1649 tcom->flags |= CMD_IGNORE_RETURN;
1650
1651 /* If this is a simple command, tell execute_disk_command that it
1652 might be able to get away without forking and simply exec.
1653 This means things like ( sleep 10 ) will only cause one fork.
1654 If we're timing the command or inverting its return value, however,
1655 we cannot do this optimization. */
1656 if ((user_subshell || user_coproc) && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
1657 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1658 ((tcom->flags & CMD_INVERT_RETURN) == 0))
1659 {
1660 tcom->flags |= CMD_NO_FORK;
1661 if (tcom->type == cm_simple)
1662 tcom->value.Simple->flags |= CMD_NO_FORK;
1663 }
1664
1665 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1666 tcom->flags &= ~CMD_INVERT_RETURN;
1667
1668 result = setjmp_nosigs (top_level);
1669
1670 /* If we're inside a function while executing this subshell, we
1671 need to handle a possible `return'. */
1672 function_value = 0;
1673 if (return_catch_flag)
1674 function_value = setjmp_nosigs (return_catch);
1675
1676 /* If we're going to exit the shell, we don't want to invert the return
1677 status. */
1678 if (result == EXITPROG)
1679 invert = 0, return_code = last_command_exit_value;
1680 else if (result)
1681 return_code = (last_command_exit_value == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : last_command_exit_value;
1682 else if (function_value)
1683 return_code = return_catch_value;
1684 else
1685 return_code = execute_command_internal ((COMMAND *)tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1686
1687 /* If we are asked to, invert the return value. */
1688 if (invert)
1689 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1690 : EXECUTION_SUCCESS;
1691
1692
1693 /* If we were explicitly placed in a subshell with (), we need
1694 to do the `shell cleanup' things, such as running traps[0]. */
1695 if (user_subshell && signal_is_trapped (0))
1696 {
1697 last_command_exit_value = return_code;
1698 return_code = run_exit_trap ();
1699 }
1700
1701 #if 0
1702 subshell_level--; /* don't bother, caller will just exit */
1703 #endif
1704 return (return_code);
1705 /* NOTREACHED */
1706 }
1707
1708 #if defined (COPROCESS_SUPPORT)
1709 #define COPROC_MAX 16
1710
1711 typedef struct cpelement
1712 {
1713 struct cpelement *next;
1714 struct coproc *coproc;
1715 }
1716 cpelement_t;
1717
1718 typedef struct cplist
1719 {
1720 struct cpelement *head;
1721 struct cpelement *tail;
1722 int ncoproc;
1723 int lock;
1724 }
1725 cplist_t;
1726
1727 static struct cpelement *cpe_alloc PARAMS((struct coproc *));
1728 static void cpe_dispose PARAMS((struct cpelement *));
1729 static struct cpelement *cpl_add PARAMS((struct coproc *));
1730 static struct cpelement *cpl_delete PARAMS((pid_t));
1731 static void cpl_reap PARAMS((void));
1732 static void cpl_flush PARAMS((void));
1733 static void cpl_closeall PARAMS((void));
1734 static struct cpelement *cpl_search PARAMS((pid_t));
1735 static struct cpelement *cpl_searchbyname PARAMS((const char *));
1736 static void cpl_prune PARAMS((void));
1737
1738 static void coproc_free PARAMS((struct coproc *));
1739
1740 /* Will go away when there is fully-implemented support for multiple coprocs. */
1741 Coproc sh_coproc = { 0, NO_PID, -1, -1, 0, 0, 0, 0, 0 };
1742
1743 cplist_t coproc_list = {0, 0, 0};
1744
1745 /* Functions to manage the list of coprocs */
1746
1747 static struct cpelement *
1748 cpe_alloc (cp)
1749 Coproc *cp;
1750 {
1751 struct cpelement *cpe;
1752
1753 cpe = (struct cpelement *)xmalloc (sizeof (struct cpelement));
1754 cpe->coproc = cp;
1755 cpe->next = (struct cpelement *)0;
1756 return cpe;
1757 }
1758
1759 static void
1760 cpe_dispose (cpe)
1761 struct cpelement *cpe;
1762 {
1763 free (cpe);
1764 }
1765
1766 static struct cpelement *
1767 cpl_add (cp)
1768 Coproc *cp;
1769 {
1770 struct cpelement *cpe;
1771
1772 cpe = cpe_alloc (cp);
1773
1774 if (coproc_list.head == 0)
1775 {
1776 coproc_list.head = coproc_list.tail = cpe;
1777 coproc_list.ncoproc = 0; /* just to make sure */
1778 }
1779 else
1780 {
1781 coproc_list.tail->next = cpe;
1782 coproc_list.tail = cpe;
1783 }
1784 coproc_list.ncoproc++;
1785
1786 return cpe;
1787 }
1788
1789 static struct cpelement *
1790 cpl_delete (pid)
1791 pid_t pid;
1792 {
1793 struct cpelement *prev, *p;
1794
1795 for (prev = p = coproc_list.head; p; prev = p, p = p->next)
1796 if (p->coproc->c_pid == pid)
1797 {
1798 prev->next = p->next; /* remove from list */
1799 break;
1800 }
1801
1802 if (p == 0)
1803 return 0; /* not found */
1804
1805 #if defined (DEBUG)
1806 itrace("cpl_delete: deleting %d", pid);
1807 #endif
1808
1809 /* Housekeeping in the border cases. */
1810 if (p == coproc_list.head)
1811 coproc_list.head = coproc_list.head->next;
1812 else if (p == coproc_list.tail)
1813 coproc_list.tail = prev;
1814
1815 coproc_list.ncoproc--;
1816 if (coproc_list.ncoproc == 0)
1817 coproc_list.head = coproc_list.tail = 0;
1818 else if (coproc_list.ncoproc == 1)
1819 coproc_list.tail = coproc_list.head; /* just to make sure */
1820
1821 return (p);
1822 }
1823
1824 static void
1825 cpl_reap ()
1826 {
1827 struct cpelement *p, *next, *nh, *nt;
1828
1829 /* Build a new list by removing dead coprocs and fix up the coproc_list
1830 pointers when done. */
1831 nh = nt = next = (struct cpelement *)0;
1832 for (p = coproc_list.head; p; p = next)
1833 {
1834 next = p->next;
1835 if (p->coproc->c_flags & COPROC_DEAD)
1836 {
1837 coproc_list.ncoproc--; /* keep running count, fix up pointers later */
1838
1839 #if defined (DEBUG)
1840 itrace("cpl_reap: deleting %d", p->coproc->c_pid);
1841 #endif
1842
1843 coproc_dispose (p->coproc);
1844 cpe_dispose (p);
1845 }
1846 else if (nh == 0)
1847 nh = nt = p;
1848 else
1849 {
1850 nt->next = p;
1851 nt = nt->next;
1852 }
1853 }
1854
1855 if (coproc_list.ncoproc == 0)
1856 coproc_list.head = coproc_list.tail = 0;
1857 else
1858 {
1859 if (nt)
1860 nt->next = 0;
1861 coproc_list.head = nh;
1862 coproc_list.tail = nt;
1863 if (coproc_list.ncoproc == 1)
1864 coproc_list.tail = coproc_list.head; /* just to make sure */
1865 }
1866 }
1867
1868 /* Clear out the list of saved statuses */
1869 static void
1870 cpl_flush ()
1871 {
1872 struct cpelement *cpe, *p;
1873
1874 for (cpe = coproc_list.head; cpe; )
1875 {
1876 p = cpe;
1877 cpe = cpe->next;
1878
1879 coproc_dispose (p->coproc);
1880 cpe_dispose (p);
1881 }
1882
1883 coproc_list.head = coproc_list.tail = 0;
1884 coproc_list.ncoproc = 0;
1885 }
1886
1887 static void
1888 cpl_closeall ()
1889 {
1890 struct cpelement *cpe;
1891
1892 for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1893 coproc_close (cpe->coproc);
1894 }
1895
1896 static void
1897 cpl_fdchk (fd)
1898 int fd;
1899 {
1900 struct cpelement *cpe;
1901
1902 for (cpe = coproc_list.head; cpe; cpe = cpe->next)
1903 coproc_checkfd (cpe->coproc, fd);
1904 }
1905
1906 /* Search for PID in the list of coprocs; return the cpelement struct if
1907 found. If not found, return NULL. */
1908 static struct cpelement *
1909 cpl_search (pid)
1910 pid_t pid;
1911 {
1912 struct cpelement *cpe;
1913
1914 for (cpe = coproc_list.head ; cpe; cpe = cpe->next)
1915 if (cpe->coproc->c_pid == pid)
1916 return cpe;
1917 return (struct cpelement *)NULL;
1918 }
1919
1920 /* Search for the coproc named NAME in the list of coprocs; return the
1921 cpelement struct if found. If not found, return NULL. */
1922 static struct cpelement *
1923 cpl_searchbyname (name)
1924 const char *name;
1925 {
1926 struct cpelement *cp;
1927
1928 for (cp = coproc_list.head ; cp; cp = cp->next)
1929 if (STREQ (cp->coproc->c_name, name))
1930 return cp;
1931 return (struct cpelement *)NULL;
1932 }
1933
1934 static pid_t
1935 cpl_firstactive ()
1936 {
1937 struct cpelement *cpe;
1938
1939 for (cpe = coproc_list.head ; cpe; cpe = cpe->next)
1940 if ((cpe->coproc->c_flags & COPROC_DEAD) == 0)
1941 return cpe->coproc->c_pid;
1942 return (pid_t)NO_PID;
1943 }
1944
1945 #if 0
1946 static void
1947 cpl_prune ()
1948 {
1949 struct cpelement *cp;
1950
1951 while (coproc_list.head && coproc_list.ncoproc > COPROC_MAX)
1952 {
1953 cp = coproc_list.head;
1954 coproc_list.head = coproc_list.head->next;
1955 coproc_dispose (cp->coproc);
1956 cpe_dispose (cp);
1957 coproc_list.ncoproc--;
1958 }
1959 }
1960 #endif
1961
1962 /* These currently use a single global "shell coproc" but are written in a
1963 way to not preclude additional coprocs later (using the list management
1964 package above). */
1965
1966 struct coproc *
1967 getcoprocbypid (pid)
1968 pid_t pid;
1969 {
1970 #if MULTIPLE_COPROCS
1971 struct cpelement *p;
1972
1973 p = cpl_search (pid);
1974 return (p ? p->coproc : 0);
1975 #else
1976 return (pid == sh_coproc.c_pid ? &sh_coproc : 0);
1977 #endif
1978 }
1979
1980 struct coproc *
1981 getcoprocbyname (name)
1982 const char *name;
1983 {
1984 #if MULTIPLE_COPROCS
1985 struct cpelement *p;
1986
1987 p = cpl_searchbyname (name);
1988 return (p ? p->coproc : 0);
1989 #else
1990 return ((sh_coproc.c_name && STREQ (sh_coproc.c_name, name)) ? &sh_coproc : 0);
1991 #endif
1992 }
1993
1994 void
1995 coproc_init (cp)
1996 struct coproc *cp;
1997 {
1998 cp->c_name = 0;
1999 cp->c_pid = NO_PID;
2000 cp->c_rfd = cp->c_wfd = -1;
2001 cp->c_rsave = cp->c_wsave = -1;
2002 cp->c_flags = cp->c_status = cp->c_lock = 0;
2003 }
2004
2005 struct coproc *
2006 coproc_alloc (name, pid)
2007 char *name;
2008 pid_t pid;
2009 {
2010 struct coproc *cp;
2011
2012 #if MULTIPLE_COPROCS
2013 cp = (struct coproc *)xmalloc (sizeof (struct coproc));
2014 #else
2015 cp = &sh_coproc;
2016 #endif
2017 coproc_init (cp);
2018 cp->c_lock = 2;
2019
2020 cp->c_pid = pid;
2021 cp->c_name = savestring (name);
2022 #if MULTIPLE_COPROCS
2023 cpl_add (cp);
2024 #endif
2025 cp->c_lock = 0;
2026 return (cp);
2027 }
2028
2029 static void
2030 coproc_free (cp)
2031 struct coproc *cp;
2032 {
2033 free (cp);
2034 }
2035
2036 void
2037 coproc_dispose (cp)
2038 struct coproc *cp;
2039 {
2040 sigset_t set, oset;
2041
2042 if (cp == 0)
2043 return;
2044
2045 BLOCK_SIGNAL (SIGCHLD, set, oset);
2046 cp->c_lock = 3;
2047 coproc_unsetvars (cp);
2048 FREE (cp->c_name);
2049 coproc_close (cp);
2050 #if MULTIPLE_COPROCS
2051 coproc_free (cp);
2052 #else
2053 coproc_init (cp);
2054 cp->c_lock = 0;
2055 #endif
2056 UNBLOCK_SIGNAL (oset);
2057 }
2058
2059 /* Placeholder for now. Will require changes for multiple coprocs */
2060 void
2061 coproc_flush ()
2062 {
2063 #if MULTIPLE_COPROCS
2064 cpl_flush ();
2065 #else
2066 coproc_dispose (&sh_coproc);
2067 #endif
2068 }
2069
2070 void
2071 coproc_close (cp)
2072 struct coproc *cp;
2073 {
2074 if (cp->c_rfd >= 0)
2075 {
2076 close (cp->c_rfd);
2077 cp->c_rfd = -1;
2078 }
2079 if (cp->c_wfd >= 0)
2080 {
2081 close (cp->c_wfd);
2082 cp->c_wfd = -1;
2083 }
2084 cp->c_rsave = cp->c_wsave = -1;
2085 }
2086
2087 void
2088 coproc_closeall ()
2089 {
2090 #if MULTIPLE_COPROCS
2091 cpl_closeall ();
2092 #else
2093 coproc_close (&sh_coproc); /* XXX - will require changes for multiple coprocs */
2094 #endif
2095 }
2096
2097 void
2098 coproc_reap ()
2099 {
2100 #if MULTIPLE_COPROCS
2101 cpl_reap ();
2102 #else
2103 struct coproc *cp;
2104
2105 cp = &sh_coproc; /* XXX - will require changes for multiple coprocs */
2106 if (cp && (cp->c_flags & COPROC_DEAD))
2107 coproc_dispose (cp);
2108 #endif
2109 }
2110
2111 void
2112 coproc_rclose (cp, fd)
2113 struct coproc *cp;
2114 int fd;
2115 {
2116 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
2117 {
2118 close (cp->c_rfd);
2119 cp->c_rfd = -1;
2120 }
2121 }
2122
2123 void
2124 coproc_wclose (cp, fd)
2125 struct coproc *cp;
2126 int fd;
2127 {
2128 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2129 {
2130 close (cp->c_wfd);
2131 cp->c_wfd = -1;
2132 }
2133 }
2134
2135 void
2136 coproc_checkfd (cp, fd)
2137 struct coproc *cp;
2138 int fd;
2139 {
2140 int update;
2141
2142 update = 0;
2143 if (cp->c_rfd >= 0 && cp->c_rfd == fd)
2144 update = cp->c_rfd = -1;
2145 if (cp->c_wfd >= 0 && cp->c_wfd == fd)
2146 update = cp->c_wfd = -1;
2147 if (update)
2148 coproc_setvars (cp);
2149 }
2150
2151 void
2152 coproc_fdchk (fd)
2153 int fd;
2154 {
2155 #if MULTIPLE_COPROCS
2156 cpl_fdchk (fd);
2157 #else
2158 coproc_checkfd (&sh_coproc, fd);
2159 #endif
2160 }
2161
2162 void
2163 coproc_fdclose (cp, fd)
2164 struct coproc *cp;
2165 int fd;
2166 {
2167 coproc_rclose (cp, fd);
2168 coproc_wclose (cp, fd);
2169 coproc_setvars (cp);
2170 }
2171
2172 void
2173 coproc_fdsave (cp)
2174 struct coproc *cp;
2175 {
2176 cp->c_rsave = cp->c_rfd;
2177 cp->c_wsave = cp->c_wfd;
2178 }
2179
2180 void
2181 coproc_fdrestore (cp)
2182 struct coproc *cp;
2183 {
2184 cp->c_rfd = cp->c_rsave;
2185 cp->c_wfd = cp->c_wsave;
2186 }
2187
2188 static void
2189 coproc_setstatus (cp, status)
2190 struct coproc *cp;
2191 int status;
2192 {
2193 cp->c_lock = 4;
2194 cp->c_status = status;
2195 cp->c_flags |= COPROC_DEAD;
2196 cp->c_flags &= ~COPROC_RUNNING;
2197 /* Don't dispose the coproc or unset the COPROC_XXX variables because
2198 this is executed in a signal handler context. Wait until coproc_reap
2199 takes care of it. */
2200 cp->c_lock = 0;
2201 }
2202
2203 void
2204 coproc_pidchk (pid, status)
2205 pid_t pid;
2206 int status;
2207 {
2208 struct coproc *cp;
2209
2210 #if MULTIPLE_COPROCS
2211 struct cpelement *cpe;
2212
2213 /* We're not disposing the coproc because this is executed in a signal
2214 handler context */
2215 cpe = cpl_search (pid);
2216 cp = cpe ? cpe->coproc : 0;
2217 #else
2218 cp = getcoprocbypid (pid);
2219 #endif
2220 if (cp)
2221 coproc_setstatus (cp, status);
2222 }
2223
2224 pid_t
2225 coproc_active ()
2226 {
2227 #if MULTIPLE_COPROCS
2228 return (cpl_firstactive ());
2229 #else
2230 return ((sh_coproc.c_flags & COPROC_DEAD) ? NO_PID : sh_coproc.c_pid);
2231 #endif
2232 }
2233 void
2234 coproc_setvars (cp)
2235 struct coproc *cp;
2236 {
2237 SHELL_VAR *v;
2238 char *namevar, *t;
2239 int l;
2240 WORD_DESC w;
2241 #if defined (ARRAY_VARS)
2242 arrayind_t ind;
2243 #endif
2244
2245 if (cp->c_name == 0)
2246 return;
2247
2248 /* We could do more here but right now we only check the name, warn if it's
2249 not a valid identifier, and refuse to create variables with invalid names
2250 if a coproc with such a name is supplied. */
2251 w.word = cp->c_name;
2252 w.flags = 0;
2253 if (check_identifier (&w, 1) == 0)
2254 return;
2255
2256 l = strlen (cp->c_name);
2257 namevar = xmalloc (l + 16);
2258
2259 #if defined (ARRAY_VARS)
2260 v = find_variable (cp->c_name);
2261
2262 /* This is the same code as in find_or_make_array_variable */
2263 if (v == 0)
2264 {
2265 v = find_variable_nameref_for_create (cp->c_name, 1);
2266 if (v == INVALID_NAMEREF_VALUE)
2267 {
2268 free (namevar);
2269 return;
2270 }
2271 if (v && nameref_p (v))
2272 {
2273 free (cp->c_name);
2274 cp->c_name = savestring (nameref_cell (v));
2275 v = make_new_array_variable (cp->c_name);
2276 }
2277 }
2278
2279 if (v && (readonly_p (v) || noassign_p (v)))
2280 {
2281 if (readonly_p (v))
2282 err_readonly (cp->c_name);
2283 free (namevar);
2284 return;
2285 }
2286 if (v == 0)
2287 v = make_new_array_variable (cp->c_name);
2288 if (array_p (v) == 0)
2289 v = convert_var_to_array (v);
2290
2291 t = itos (cp->c_rfd);
2292 ind = 0;
2293 v = bind_array_variable (cp->c_name, ind, t, 0);
2294 free (t);
2295
2296 t = itos (cp->c_wfd);
2297 ind = 1;
2298 v = bind_array_variable (cp->c_name, ind, t, 0);
2299 free (t);
2300 #else
2301 sprintf (namevar, "%s_READ", cp->c_name);
2302 t = itos (cp->c_rfd);
2303 bind_variable (namevar, t, 0);
2304 free (t);
2305 sprintf (namevar, "%s_WRITE", cp->c_name);
2306 t = itos (cp->c_wfd);
2307 bind_variable (namevar, t, 0);
2308 free (t);
2309 #endif
2310
2311 sprintf (namevar, "%s_PID", cp->c_name);
2312 t = itos (cp->c_pid);
2313 v = bind_variable (namevar, t, 0);
2314 free (t);
2315
2316 free (namevar);
2317 }
2318
2319 void
2320 coproc_unsetvars (cp)
2321 struct coproc *cp;
2322 {
2323 int l;
2324 char *namevar;
2325
2326 if (cp->c_name == 0)
2327 return;
2328
2329 l = strlen (cp->c_name);
2330 namevar = xmalloc (l + 16);
2331
2332 sprintf (namevar, "%s_PID", cp->c_name);
2333 unbind_variable_noref (namevar);
2334
2335 #if defined (ARRAY_VARS)
2336 check_unbind_variable (cp->c_name);
2337 #else
2338 sprintf (namevar, "%s_READ", cp->c_name);
2339 unbind_variable (namevar);
2340 sprintf (namevar, "%s_WRITE", cp->c_name);
2341 unbind_variable (namevar);
2342 #endif
2343
2344 free (namevar);
2345 }
2346
2347 static int
2348 execute_coproc (command, pipe_in, pipe_out, fds_to_close)
2349 COMMAND *command;
2350 int pipe_in, pipe_out;
2351 struct fd_bitmap *fds_to_close;
2352 {
2353 int rpipe[2], wpipe[2], estat, invert;
2354 pid_t coproc_pid;
2355 Coproc *cp;
2356 char *tcmd, *p, *name;
2357 sigset_t set, oset;
2358
2359 /* XXX -- can be removed after changes to handle multiple coprocs */
2360 #if !MULTIPLE_COPROCS
2361 if (sh_coproc.c_pid != NO_PID && (sh_coproc.c_rfd >= 0 || sh_coproc.c_wfd >= 0))
2362 internal_warning (_("execute_coproc: coproc [%d:%s] still exists"), sh_coproc.c_pid, sh_coproc.c_name);
2363 coproc_init (&sh_coproc);
2364 #endif
2365
2366 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2367
2368 /* expand name without splitting - could make this dependent on a shopt option */
2369 name = expand_string_unsplit_to_string (command->value.Coproc->name, 0);
2370 /* Optional check -- could be relaxed */
2371 if (legal_identifier (name) == 0)
2372 {
2373 internal_error (_("`%s': not a valid identifier"), name);
2374 return (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
2375 }
2376 else
2377 {
2378 free (command->value.Coproc->name);
2379 command->value.Coproc->name = name;
2380 }
2381
2382 command_string_index = 0;
2383 tcmd = make_command_string (command);
2384
2385 sh_openpipe ((int *)&rpipe); /* 0 = parent read, 1 = child write */
2386 sh_openpipe ((int *)&wpipe); /* 0 = child read, 1 = parent write */
2387
2388 BLOCK_SIGNAL (SIGCHLD, set, oset);
2389
2390 coproc_pid = make_child (p = savestring (tcmd), FORK_ASYNC);
2391
2392 if (coproc_pid == 0)
2393 {
2394 close (rpipe[0]);
2395 close (wpipe[1]);
2396
2397 #if defined (JOB_CONTROL)
2398 FREE (p);
2399 #endif
2400
2401 UNBLOCK_SIGNAL (oset);
2402 estat = execute_in_subshell (command, 1, wpipe[0], rpipe[1], fds_to_close);
2403
2404 fflush (stdout);
2405 fflush (stderr);
2406
2407 exit (estat);
2408 }
2409
2410 close (rpipe[1]);
2411 close (wpipe[0]);
2412
2413 cp = coproc_alloc (command->value.Coproc->name, coproc_pid);
2414 cp->c_rfd = rpipe[0];
2415 cp->c_wfd = wpipe[1];
2416
2417 cp->c_flags |= COPROC_RUNNING;
2418
2419 SET_CLOSE_ON_EXEC (cp->c_rfd);
2420 SET_CLOSE_ON_EXEC (cp->c_wfd);
2421
2422 coproc_setvars (cp);
2423
2424 UNBLOCK_SIGNAL (oset);
2425
2426 #if 0
2427 itrace ("execute_coproc (%s): [%d] %s", command->value.Coproc->name, coproc_pid, the_printed_command);
2428 #endif
2429
2430 close_pipes (pipe_in, pipe_out);
2431 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2432 unlink_fifo_list ();
2433 #endif
2434 stop_pipeline (1, (COMMAND *)NULL);
2435 DESCRIBE_PID (coproc_pid);
2436 run_pending_traps ();
2437
2438 return (invert ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
2439 }
2440 #endif
2441
2442 static void
2443 restore_stdin (s)
2444 int s;
2445 {
2446 dup2 (s, 0);
2447 close (s);
2448 }
2449
2450 /* Catch-all cleanup function for lastpipe code for unwind-protects */
2451 static void
2452 lastpipe_cleanup (s)
2453 int s;
2454 {
2455 set_jobs_list_frozen (s);
2456 }
2457
2458 static int
2459 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2460 COMMAND *command;
2461 int asynchronous, pipe_in, pipe_out;
2462 struct fd_bitmap *fds_to_close;
2463 {
2464 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
2465 int lstdin, lastpipe_flag, lastpipe_jid, old_frozen;
2466 COMMAND *cmd;
2467 struct fd_bitmap *fd_bitmap;
2468 pid_t lastpid;
2469
2470 #if defined (JOB_CONTROL)
2471 sigset_t set, oset;
2472 BLOCK_CHILD (set, oset);
2473 #endif /* JOB_CONTROL */
2474
2475 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2476
2477 prev = pipe_in;
2478 cmd = command;
2479
2480 while (cmd && cmd->type == cm_connection &&
2481 cmd->value.Connection && cmd->value.Connection->connector == '|')
2482 {
2483 /* Make a pipeline between the two commands. */
2484 if (pipe (fildes) < 0)
2485 {
2486 sys_error (_("pipe error"));
2487 #if defined (JOB_CONTROL)
2488 terminate_current_pipeline ();
2489 kill_current_pipeline ();
2490 UNBLOCK_CHILD (oset);
2491 #endif /* JOB_CONTROL */
2492 last_command_exit_value = EXECUTION_FAILURE;
2493 /* The unwind-protects installed below will take care
2494 of closing all of the open file descriptors. */
2495 throw_to_top_level ();
2496 return (EXECUTION_FAILURE); /* XXX */
2497 }
2498
2499 /* Here is a problem: with the new file close-on-exec
2500 code, the read end of the pipe (fildes[0]) stays open
2501 in the first process, so that process will never get a
2502 SIGPIPE. There is no way to signal the first process
2503 that it should close fildes[0] after forking, so it
2504 remains open. No SIGPIPE is ever sent because there
2505 is still a file descriptor open for reading connected
2506 to the pipe. We take care of that here. This passes
2507 around a bitmap of file descriptors that must be
2508 closed after making a child process in execute_simple_command. */
2509
2510 /* We need fd_bitmap to be at least as big as fildes[0].
2511 If fildes[0] is less than fds_to_close->size, then
2512 use fds_to_close->size. */
2513 new_bitmap_size = (fildes[0] < fds_to_close->size)
2514 ? fds_to_close->size
2515 : fildes[0] + 8;
2516
2517 fd_bitmap = new_fd_bitmap (new_bitmap_size);
2518
2519 /* Now copy the old information into the new bitmap. */
2520 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
2521
2522 /* And mark the pipe file descriptors to be closed. */
2523 fd_bitmap->bitmap[fildes[0]] = 1;
2524
2525 /* In case there are pipe or out-of-processes errors, we
2526 want all these file descriptors to be closed when
2527 unwind-protects are run, and the storage used for the
2528 bitmaps freed up. */
2529 begin_unwind_frame ("pipe-file-descriptors");
2530 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
2531 add_unwind_protect (close_fd_bitmap, fd_bitmap);
2532 if (prev >= 0)
2533 add_unwind_protect (close, prev);
2534 dummyfd = fildes[1];
2535 add_unwind_protect (close, dummyfd);
2536
2537 #if defined (JOB_CONTROL)
2538 add_unwind_protect (restore_signal_mask, &oset);
2539 #endif /* JOB_CONTROL */
2540
2541 if (ignore_return && cmd->value.Connection->first)
2542 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2543 execute_command_internal (cmd->value.Connection->first, asynchronous,
2544 prev, fildes[1], fd_bitmap);
2545
2546 if (prev >= 0)
2547 close (prev);
2548
2549 prev = fildes[0];
2550 close (fildes[1]);
2551
2552 dispose_fd_bitmap (fd_bitmap);
2553 discard_unwind_frame ("pipe-file-descriptors");
2554
2555 cmd = cmd->value.Connection->second;
2556 }
2557
2558 lastpid = last_made_pid;
2559
2560 /* Now execute the rightmost command in the pipeline. */
2561 if (ignore_return && cmd)
2562 cmd->flags |= CMD_IGNORE_RETURN;
2563
2564 lastpipe_flag = 0;
2565
2566 begin_unwind_frame ("lastpipe-exec");
2567 lstdin = -1;
2568 /* If the `lastpipe' option is set with shopt, and job control is not
2569 enabled, execute the last element of non-async pipelines in the
2570 current shell environment. */
2571 if (lastpipe_opt && job_control == 0 && asynchronous == 0 && pipe_out == NO_PIPE && prev > 0)
2572 {
2573 lstdin = move_to_high_fd (0, 1, -1);
2574 if (lstdin > 0)
2575 {
2576 do_piping (prev, pipe_out);
2577 prev = NO_PIPE;
2578 add_unwind_protect (restore_stdin, lstdin);
2579 lastpipe_flag = 1;
2580 old_frozen = freeze_jobs_list ();
2581 lastpipe_jid = stop_pipeline (0, (COMMAND *)NULL); /* XXX */
2582 add_unwind_protect (lastpipe_cleanup, old_frozen);
2583 #if defined (JOB_CONTROL)
2584 UNBLOCK_CHILD (oset); /* XXX */
2585 #endif
2586 }
2587 if (cmd)
2588 cmd->flags |= CMD_LASTPIPE;
2589 }
2590 if (prev >= 0)
2591 add_unwind_protect (close, prev);
2592
2593 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
2594
2595 if (lstdin > 0)
2596 restore_stdin (lstdin);
2597
2598 if (prev >= 0)
2599 close (prev);
2600
2601 #if defined (JOB_CONTROL)
2602 UNBLOCK_CHILD (oset);
2603 #endif
2604
2605 QUIT;
2606
2607 if (lastpipe_flag)
2608 {
2609 #if defined (JOB_CONTROL)
2610 if (INVALID_JOB (lastpipe_jid) == 0)
2611 {
2612 append_process (savestring (the_printed_command_except_trap), dollar_dollar_pid, exec_result, lastpipe_jid);
2613 lstdin = wait_for (lastpid, 0);
2614 }
2615 else
2616 lstdin = wait_for_single_pid (lastpid, 0); /* checks bgpids list */
2617 #else
2618 lstdin = wait_for (lastpid, 0);
2619 #endif
2620
2621 #if defined (JOB_CONTROL)
2622 /* If wait_for removes the job from the jobs table, use result of last
2623 command as pipeline's exit status as usual. The jobs list can get
2624 frozen and unfrozen at inconvenient times if there are multiple pipelines
2625 running simultaneously. */
2626 if (INVALID_JOB (lastpipe_jid) == 0)
2627 exec_result = job_exit_status (lastpipe_jid);
2628 else if (pipefail_opt)
2629 exec_result = exec_result | lstdin; /* XXX */
2630 /* otherwise we use exec_result */
2631 #endif
2632
2633 set_jobs_list_frozen (old_frozen);
2634 }
2635
2636 discard_unwind_frame ("lastpipe-exec");
2637
2638 return (exec_result);
2639 }
2640
2641 static int
2642 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
2643 COMMAND *command;
2644 int asynchronous, pipe_in, pipe_out;
2645 struct fd_bitmap *fds_to_close;
2646 {
2647 COMMAND *tc, *second;
2648 int ignore_return, exec_result, was_error_trap, invert;
2649 volatile int save_line_number;
2650
2651 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2652
2653 switch (command->value.Connection->connector)
2654 {
2655 /* Do the first command asynchronously. */
2656 case '&':
2657 tc = command->value.Connection->first;
2658 if (tc == 0)
2659 return (EXECUTION_SUCCESS);
2660
2661 if (ignore_return)
2662 tc->flags |= CMD_IGNORE_RETURN;
2663 tc->flags |= CMD_AMPERSAND;
2664
2665 /* If this shell was compiled without job control support,
2666 if we are currently in a subshell via `( xxx )', or if job
2667 control is not active then the standard input for an
2668 asynchronous command is forced to /dev/null. */
2669 #if defined (JOB_CONTROL)
2670 if ((subshell_environment || !job_control) && !stdin_redir)
2671 #else
2672 if (!stdin_redir)
2673 #endif /* JOB_CONTROL */
2674 tc->flags |= CMD_STDIN_REDIR;
2675
2676 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
2677 QUIT;
2678
2679 if (tc->flags & CMD_STDIN_REDIR)
2680 tc->flags &= ~CMD_STDIN_REDIR;
2681
2682 second = command->value.Connection->second;
2683 if (second)
2684 {
2685 if (ignore_return)
2686 second->flags |= CMD_IGNORE_RETURN;
2687
2688 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
2689 }
2690
2691 break;
2692
2693 /* Just call execute command on both sides. */
2694 case ';':
2695 if (ignore_return)
2696 {
2697 if (command->value.Connection->first)
2698 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2699 if (command->value.Connection->second)
2700 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
2701 }
2702 executing_list++;
2703 QUIT;
2704
2705 #if 1
2706 execute_command (command->value.Connection->first);
2707 #else
2708 execute_command_internal (command->value.Connection->first,
2709 asynchronous, pipe_in, pipe_out,
2710 fds_to_close);
2711 #endif
2712
2713 QUIT;
2714 optimize_fork (command); /* XXX */
2715 exec_result = execute_command_internal (command->value.Connection->second,
2716 asynchronous, pipe_in, pipe_out,
2717 fds_to_close);
2718 executing_list--;
2719 break;
2720
2721 case '|':
2722 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
2723 invert = (command->flags & CMD_INVERT_RETURN) != 0;
2724 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
2725
2726 line_number_for_err_trap = line_number; /* XXX - save value? */
2727 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
2728
2729 if (asynchronous)
2730 {
2731 exec_result = EXECUTION_SUCCESS;
2732 invert = 0;
2733 }
2734
2735 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
2736 {
2737 last_command_exit_value = exec_result;
2738 save_line_number = line_number;
2739 line_number = line_number_for_err_trap;
2740 run_error_trap ();
2741 line_number = save_line_number;
2742 }
2743
2744 if (ignore_return == 0 && invert == 0 && exit_immediately_on_error && exec_result != EXECUTION_SUCCESS)
2745 {
2746 last_command_exit_value = exec_result;
2747 run_pending_traps ();
2748 jump_to_top_level (ERREXIT);
2749 }
2750
2751 break;
2752
2753 case AND_AND:
2754 case OR_OR:
2755 if (asynchronous)
2756 {
2757 /* If we have something like `a && b &' or `a || b &', run the
2758 && or || stuff in a subshell. Force a subshell and just call
2759 execute_command_internal again. Leave asynchronous on
2760 so that we get a report from the parent shell about the
2761 background job. */
2762 command->flags |= CMD_FORCE_SUBSHELL;
2763 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
2764 break;
2765 }
2766
2767 /* Execute the first command. If the result of that is successful
2768 and the connector is AND_AND, or the result is not successful
2769 and the connector is OR_OR, then execute the second command,
2770 otherwise return. */
2771
2772 executing_list++;
2773 if (command->value.Connection->first)
2774 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
2775
2776 #if 1
2777 exec_result = execute_command (command->value.Connection->first);
2778 #else
2779 exec_result = execute_command_internal (command->value.Connection->first, 0, NO_PIPE, NO_PIPE, fds_to_close);
2780 #endif
2781 QUIT;
2782 if (((command->value.Connection->connector == AND_AND) &&
2783 (exec_result == EXECUTION_SUCCESS)) ||
2784 ((command->value.Connection->connector == OR_OR) &&
2785 (exec_result != EXECUTION_SUCCESS)))
2786 {
2787 optimize_fork (command);
2788
2789 second = command->value.Connection->second;
2790 if (ignore_return && second)
2791 second->flags |= CMD_IGNORE_RETURN;
2792
2793 exec_result = execute_command (second);
2794 }
2795 executing_list--;
2796 break;
2797
2798 default:
2799 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
2800 jump_to_top_level (DISCARD);
2801 exec_result = EXECUTION_FAILURE;
2802 }
2803
2804 return exec_result;
2805 }
2806
2807 /* The test used to be only for interactive_shell, but we don't want to report
2808 job status when the shell is not interactive or when job control isn't
2809 enabled. */
2810 #define REAP() \
2811 do \
2812 { \
2813 if (job_control == 0 || interactive_shell == 0) \
2814 reap_dead_jobs (); \
2815 } \
2816 while (0)
2817
2818 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2819 DO command; DONE */
2820 static int
2821 execute_for_command (for_command)
2822 FOR_COM *for_command;
2823 {
2824 register WORD_LIST *releaser, *list;
2825 SHELL_VAR *v;
2826 char *identifier;
2827 int retval, save_line_number;
2828 #if 0
2829 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
2830 #endif
2831
2832 save_line_number = line_number;
2833 if (check_identifier (for_command->name, 1) == 0)
2834 {
2835 if (posixly_correct && interactive_shell == 0)
2836 {
2837 last_command_exit_value = EX_BADUSAGE;
2838 jump_to_top_level (ERREXIT);
2839 }
2840 return (EXECUTION_FAILURE);
2841 }
2842
2843 loop_level++;
2844 identifier = for_command->name->word;
2845
2846 line_number = for_command->line; /* for expansion error messages */
2847 list = releaser = expand_words_no_vars (for_command->map_list);
2848
2849 begin_unwind_frame ("for");
2850 add_unwind_protect (dispose_words, releaser);
2851
2852 #if 0
2853 if (lexical_scoping)
2854 {
2855 old_value = copy_variable (find_variable (identifier));
2856 if (old_value)
2857 add_unwind_protect (dispose_variable, old_value);
2858 }
2859 #endif
2860
2861 if (for_command->flags & CMD_IGNORE_RETURN)
2862 for_command->action->flags |= CMD_IGNORE_RETURN;
2863
2864 for (retval = EXECUTION_SUCCESS; list; list = list->next)
2865 {
2866 QUIT;
2867
2868 line_number = for_command->line;
2869
2870 /* Remember what this command looks like, for debugger. */
2871 command_string_index = 0;
2872 print_for_command_head (for_command);
2873
2874 if (echo_command_at_execute)
2875 xtrace_print_for_command_head (for_command);
2876
2877 /* Save this command unless it's a trap command and we're not running
2878 a debug trap. */
2879 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
2880 {
2881 FREE (the_printed_command_except_trap);
2882 the_printed_command_except_trap = savestring (the_printed_command);
2883 }
2884
2885 retval = run_debug_trap ();
2886 #if defined (DEBUGGER)
2887 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2888 skip the command. */
2889 if (debugging_mode && retval != EXECUTION_SUCCESS)
2890 continue;
2891 #endif
2892
2893 this_command_name = (char *)NULL;
2894 /* XXX - special ksh93 for command index variable handling */
2895 v = find_variable_last_nameref (identifier, 1);
2896 if (v && nameref_p (v))
2897 {
2898 if (valid_nameref_value (list->word->word, 1) == 0)
2899 {
2900 sh_invalidid (list->word->word);
2901 v = 0;
2902 }
2903 else if (readonly_p (v))
2904 err_readonly (name_cell (v));
2905 else
2906 v = bind_variable_value (v, list->word->word, ASS_NAMEREF);
2907 }
2908 else
2909 v = bind_variable (identifier, list->word->word, 0);
2910
2911 if (v == 0 || readonly_p (v) || noassign_p (v))
2912 {
2913 line_number = save_line_number;
2914 if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
2915 {
2916 last_command_exit_value = EXECUTION_FAILURE;
2917 jump_to_top_level (FORCE_EOF);
2918 }
2919 else
2920 {
2921 dispose_words (releaser);
2922 discard_unwind_frame ("for");
2923 loop_level--;
2924 return (EXECUTION_FAILURE);
2925 }
2926 }
2927
2928 if (ifsname (identifier))
2929 setifs (v);
2930 else
2931 stupidly_hack_special_variables (identifier);
2932
2933 retval = execute_command (for_command->action);
2934 REAP ();
2935 QUIT;
2936
2937 if (breaking)
2938 {
2939 breaking--;
2940 break;
2941 }
2942
2943 if (continuing)
2944 {
2945 continuing--;
2946 if (continuing)
2947 break;
2948 }
2949 }
2950
2951 loop_level--;
2952 line_number = save_line_number;
2953
2954 #if 0
2955 if (lexical_scoping)
2956 {
2957 if (!old_value)
2958 unbind_variable (identifier);
2959 else
2960 {
2961 SHELL_VAR *new_value;
2962
2963 new_value = bind_variable (identifier, value_cell (old_value), 0);
2964 new_value->attributes = old_value->attributes;
2965 dispose_variable (old_value);
2966 }
2967 }
2968 #endif
2969
2970 dispose_words (releaser);
2971 discard_unwind_frame ("for");
2972 return (retval);
2973 }
2974
2975 #if defined (ARITH_FOR_COMMAND)
2976 /* Execute an arithmetic for command. The syntax is
2977
2978 for (( init ; step ; test ))
2979 do
2980 body
2981 done
2982
2983 The execution should be exactly equivalent to
2984
2985 eval \(\( init \)\)
2986 while eval \(\( test \)\) ; do
2987 body;
2988 eval \(\( step \)\)
2989 done
2990 */
2991 static intmax_t
2992 eval_arith_for_expr (l, okp)
2993 WORD_LIST *l;
2994 int *okp;
2995 {
2996 WORD_LIST *new;
2997 intmax_t expresult;
2998 int r;
2999
3000 new = expand_words_no_vars (l);
3001 if (new)
3002 {
3003 if (echo_command_at_execute)
3004 xtrace_print_arith_cmd (new);
3005 this_command_name = "(("; /* )) for expression error messages */
3006
3007 command_string_index = 0;
3008 print_arith_command (new);
3009 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3010 {
3011 FREE (the_printed_command_except_trap);
3012 the_printed_command_except_trap = savestring (the_printed_command);
3013 }
3014
3015 r = run_debug_trap ();
3016 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3017 skip the command. */
3018 #if defined (DEBUGGER)
3019 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
3020 expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
3021 else
3022 {
3023 expresult = 0;
3024 if (okp)
3025 *okp = 1;
3026 }
3027 #else
3028 expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
3029 #endif
3030 dispose_words (new);
3031 }
3032 else
3033 {
3034 expresult = 0;
3035 if (okp)
3036 *okp = 1;
3037 }
3038 return (expresult);
3039 }
3040
3041 static int
3042 execute_arith_for_command (arith_for_command)
3043 ARITH_FOR_COM *arith_for_command;
3044 {
3045 intmax_t expresult;
3046 int expok, body_status, arith_lineno, save_lineno;
3047
3048 body_status = EXECUTION_SUCCESS;
3049 loop_level++;
3050 save_lineno = line_number;
3051
3052 if (arith_for_command->flags & CMD_IGNORE_RETURN)
3053 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
3054
3055 this_command_name = "(("; /* )) for expression error messages */
3056
3057 /* save the starting line number of the command so we can reset
3058 line_number before executing each expression -- for $LINENO
3059 and the DEBUG trap. */
3060 line_number = arith_lineno = arith_for_command->line;
3061 if (variable_context && interactive_shell && sourcelevel == 0)
3062 {
3063 /* line numbers in a function start at 1 */
3064 line_number -= function_line_number - 1;
3065 if (line_number <= 0)
3066 line_number = 1;
3067 }
3068
3069 /* Evaluate the initialization expression. */
3070 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
3071 if (expok == 0)
3072 {
3073 line_number = save_lineno;
3074 return (EXECUTION_FAILURE);
3075 }
3076
3077 while (1)
3078 {
3079 /* Evaluate the test expression. */
3080 line_number = arith_lineno;
3081 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
3082 line_number = save_lineno;
3083
3084 if (expok == 0)
3085 {
3086 body_status = EXECUTION_FAILURE;
3087 break;
3088 }
3089 REAP ();
3090 if (expresult == 0)
3091 break;
3092
3093 /* Execute the body of the arithmetic for command. */
3094 QUIT;
3095 body_status = execute_command (arith_for_command->action);
3096 QUIT;
3097
3098 /* Handle any `break' or `continue' commands executed by the body. */
3099 if (breaking)
3100 {
3101 breaking--;
3102 break;
3103 }
3104
3105 if (continuing)
3106 {
3107 continuing--;
3108 if (continuing)
3109 break;
3110 }
3111
3112 /* Evaluate the step expression. */
3113 line_number = arith_lineno;
3114 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
3115 line_number = save_lineno;
3116
3117 if (expok == 0)
3118 {
3119 body_status = EXECUTION_FAILURE;
3120 break;
3121 }
3122 }
3123
3124 loop_level--;
3125 line_number = save_lineno;
3126
3127 return (body_status);
3128 }
3129 #endif
3130
3131 #if defined (SELECT_COMMAND)
3132 static int LINES, COLS, tabsize;
3133
3134 #define RP_SPACE ") "
3135 #define RP_SPACE_LEN 2
3136
3137 /* XXX - does not handle numbers > 1000000 at all. */
3138 #define NUMBER_LEN(s) \
3139 ((s < 10) ? 1 \
3140 : ((s < 100) ? 2 \
3141 : ((s < 1000) ? 3 \
3142 : ((s < 10000) ? 4 \
3143 : ((s < 100000) ? 5 \
3144 : 6)))))
3145
3146 static int
3147 displen (s)
3148 const char *s;
3149 {
3150 #if defined (HANDLE_MULTIBYTE)
3151 wchar_t *wcstr;
3152 size_t slen;
3153 int wclen;
3154
3155 wcstr = 0;
3156 slen = mbstowcs (wcstr, s, 0);
3157 if (slen == -1)
3158 slen = 0;
3159 wcstr = (wchar_t *)xmalloc (sizeof (wchar_t) * (slen + 1));
3160 mbstowcs (wcstr, s, slen + 1);
3161 wclen = wcswidth (wcstr, slen);
3162 free (wcstr);
3163 return (wclen < 0 ? STRLEN(s) : wclen);
3164 #else
3165 return (STRLEN (s));
3166 #endif
3167 }
3168
3169 static int
3170 print_index_and_element (len, ind, list)
3171 int len, ind;
3172 WORD_LIST *list;
3173 {
3174 register WORD_LIST *l;
3175 register int i;
3176
3177 if (list == 0)
3178 return (0);
3179 for (i = ind, l = list; l && --i; l = l->next)
3180 ;
3181 if (l == 0) /* don't think this can happen */
3182 return (0);
3183 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
3184 return (displen (l->word->word));
3185 }
3186
3187 static void
3188 indent (from, to)
3189 int from, to;
3190 {
3191 while (from < to)
3192 {
3193 if ((to / tabsize) > (from / tabsize))
3194 {
3195 putc ('\t', stderr);
3196 from += tabsize - from % tabsize;
3197 }
3198 else
3199 {
3200 putc (' ', stderr);
3201 from++;
3202 }
3203 }
3204 }
3205
3206 static void
3207 print_select_list (list, list_len, max_elem_len, indices_len)
3208 WORD_LIST *list;
3209 int list_len, max_elem_len, indices_len;
3210 {
3211 int ind, row, elem_len, pos, cols, rows;
3212 int first_column_indices_len, other_indices_len;
3213
3214 if (list == 0)
3215 {
3216 putc ('\n', stderr);
3217 return;
3218 }
3219
3220 cols = max_elem_len ? COLS / max_elem_len : 1;
3221 if (cols == 0)
3222 cols = 1;
3223 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
3224 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
3225
3226 if (rows == 1)
3227 {
3228 rows = cols;
3229 cols = 1;
3230 }
3231
3232 first_column_indices_len = NUMBER_LEN (rows);
3233 other_indices_len = indices_len;
3234
3235 for (row = 0; row < rows; row++)
3236 {
3237 ind = row;
3238 pos = 0;
3239 while (1)
3240 {
3241 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
3242 elem_len = print_index_and_element (indices_len, ind + 1, list);
3243 elem_len += indices_len + RP_SPACE_LEN;
3244 ind += rows;
3245 if (ind >= list_len)
3246 break;
3247 indent (pos + elem_len, pos + max_elem_len);
3248 pos += max_elem_len;
3249 }
3250 putc ('\n', stderr);
3251 }
3252 }
3253
3254 /* Print the elements of LIST, one per line, preceded by an index from 1 to
3255 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
3256 If the number is between 1 and LIST_LEN, return that selection. If EOF
3257 is read, return a null string. If a blank line is entered, or an invalid
3258 number is entered, the loop is executed again. */
3259 static char *
3260 select_query (list, list_len, prompt, print_menu)
3261 WORD_LIST *list;
3262 int list_len;
3263 char *prompt;
3264 int print_menu;
3265 {
3266 int max_elem_len, indices_len, len, r, oe;
3267 intmax_t reply;
3268 WORD_LIST *l;
3269 char *repl_string, *t;
3270
3271 COLS = default_columns ();
3272
3273 #if 0
3274 t = get_string_value ("TABSIZE");
3275 tabsize = (t && *t) ? atoi (t) : 8;
3276 if (tabsize <= 0)
3277 tabsize = 8;
3278 #else
3279 tabsize = 8;
3280 #endif
3281
3282 max_elem_len = 0;
3283 for (l = list; l; l = l->next)
3284 {
3285 len = displen (l->word->word);
3286 if (len > max_elem_len)
3287 max_elem_len = len;
3288 }
3289 indices_len = NUMBER_LEN (list_len);
3290 max_elem_len += indices_len + RP_SPACE_LEN + 2;
3291
3292 while (1)
3293 {
3294 if (print_menu)
3295 print_select_list (list, list_len, max_elem_len, indices_len);
3296 fprintf (stderr, "%s", prompt);
3297 fflush (stderr);
3298 QUIT;
3299
3300 oe = executing_builtin;
3301 executing_builtin = 1;
3302 r = read_builtin ((WORD_LIST *)NULL);
3303 executing_builtin = oe;
3304 if (r != EXECUTION_SUCCESS)
3305 {
3306 putchar ('\n');
3307 return ((char *)NULL);
3308 }
3309 repl_string = get_string_value ("REPLY");
3310 if (repl_string == 0)
3311 return ((char *)NULL);
3312 if (*repl_string == 0)
3313 {
3314 print_menu = 1;
3315 continue;
3316 }
3317 if (legal_number (repl_string, &reply) == 0)
3318 return "";
3319 if (reply < 1 || reply > list_len)
3320 return "";
3321
3322 for (l = list; l && --reply; l = l->next)
3323 ;
3324 return (l->word->word); /* XXX - can't be null? */
3325 }
3326 }
3327
3328 /* Execute a SELECT command. The syntax is:
3329 SELECT word IN list DO command_list DONE
3330 Only `break' or `return' in command_list will terminate
3331 the command. */
3332 static int
3333 execute_select_command (select_command)
3334 SELECT_COM *select_command;
3335 {
3336 WORD_LIST *releaser, *list;
3337 SHELL_VAR *v;
3338 char *identifier, *ps3_prompt, *selection;
3339 int retval, list_len, show_menu, save_line_number;
3340
3341 if (check_identifier (select_command->name, 1) == 0)
3342 return (EXECUTION_FAILURE);
3343
3344 save_line_number = line_number;
3345 line_number = select_command->line;
3346
3347 command_string_index = 0;
3348 print_select_command_head (select_command);
3349
3350 if (echo_command_at_execute)
3351 xtrace_print_select_command_head (select_command);
3352
3353 #if 0
3354 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3355 #else
3356 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3357 #endif
3358 {
3359 FREE (the_printed_command_except_trap);
3360 the_printed_command_except_trap = savestring (the_printed_command);
3361 }
3362
3363 retval = run_debug_trap ();
3364 #if defined (DEBUGGER)
3365 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3366 skip the command. */
3367 if (debugging_mode && retval != EXECUTION_SUCCESS)
3368 return (EXECUTION_SUCCESS);
3369 #endif
3370
3371 loop_level++;
3372 identifier = select_command->name->word;
3373
3374 /* command and arithmetic substitution, parameter and variable expansion,
3375 word splitting, pathname expansion, and quote removal. */
3376 list = releaser = expand_words_no_vars (select_command->map_list);
3377 list_len = list_length (list);
3378 if (list == 0 || list_len == 0)
3379 {
3380 if (list)
3381 dispose_words (list);
3382 line_number = save_line_number;
3383 return (EXECUTION_SUCCESS);
3384 }
3385
3386 begin_unwind_frame ("select");
3387 add_unwind_protect (dispose_words, releaser);
3388
3389 if (select_command->flags & CMD_IGNORE_RETURN)
3390 select_command->action->flags |= CMD_IGNORE_RETURN;
3391
3392 retval = EXECUTION_SUCCESS;
3393 show_menu = 1;
3394
3395 while (1)
3396 {
3397 line_number = select_command->line;
3398 ps3_prompt = get_string_value ("PS3");
3399 if (ps3_prompt == 0)
3400 ps3_prompt = "#? ";
3401
3402 QUIT;
3403 selection = select_query (list, list_len, ps3_prompt, show_menu);
3404 QUIT;
3405 if (selection == 0)
3406 {
3407 /* select_query returns EXECUTION_FAILURE if the read builtin
3408 fails, so we want to return failure in this case. */
3409 retval = EXECUTION_FAILURE;
3410 break;
3411 }
3412
3413 v = bind_variable (identifier, selection, 0);
3414 if (v == 0 || readonly_p (v) || noassign_p (v))
3415 {
3416 if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
3417 {
3418 last_command_exit_value = EXECUTION_FAILURE;
3419 jump_to_top_level (FORCE_EOF);
3420 }
3421 else
3422 {
3423 dispose_words (releaser);
3424 discard_unwind_frame ("select");
3425 loop_level--;
3426 line_number = save_line_number;
3427 return (EXECUTION_FAILURE);
3428 }
3429 }
3430
3431 stupidly_hack_special_variables (identifier);
3432
3433 retval = execute_command (select_command->action);
3434
3435 REAP ();
3436 QUIT;
3437
3438 if (breaking)
3439 {
3440 breaking--;
3441 break;
3442 }
3443
3444 if (continuing)
3445 {
3446 continuing--;
3447 if (continuing)
3448 break;
3449 }
3450
3451 #if defined (KSH_COMPATIBLE_SELECT)
3452 show_menu = 0;
3453 selection = get_string_value ("REPLY");
3454 if (selection && *selection == '\0')
3455 show_menu = 1;
3456 #endif
3457 }
3458
3459 loop_level--;
3460 line_number = save_line_number;
3461
3462 dispose_words (releaser);
3463 discard_unwind_frame ("select");
3464 return (retval);
3465 }
3466 #endif /* SELECT_COMMAND */
3467
3468 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3469 The pattern_list is a linked list of pattern clauses; each clause contains
3470 some patterns to compare word_desc against, and an associated command to
3471 execute. */
3472 static int
3473 execute_case_command (case_command)
3474 CASE_COM *case_command;
3475 {
3476 register WORD_LIST *list;
3477 WORD_LIST *wlist, *es;
3478 PATTERN_LIST *clauses;
3479 char *word, *pattern;
3480 int retval, match, ignore_return, save_line_number, qflags;
3481
3482 save_line_number = line_number;
3483 line_number = case_command->line;
3484
3485 command_string_index = 0;
3486 print_case_command_head (case_command);
3487
3488 if (echo_command_at_execute)
3489 xtrace_print_case_command_head (case_command);
3490
3491 #if 0
3492 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3493 #else
3494 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3495 #endif
3496 {
3497 FREE (the_printed_command_except_trap);
3498 the_printed_command_except_trap = savestring (the_printed_command);
3499 }
3500
3501 retval = run_debug_trap();
3502 #if defined (DEBUGGER)
3503 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3504 skip the command. */
3505 if (debugging_mode && retval != EXECUTION_SUCCESS)
3506 {
3507 line_number = save_line_number;
3508 return (EXECUTION_SUCCESS);
3509 }
3510 #endif
3511
3512 /* Use the same expansions (the ones POSIX specifies) as the patterns;
3513 dequote the resulting string (as POSIX specifies) since the quotes in
3514 patterns are handled specially below. We have to do it in this order
3515 because we're not supposed to perform word splitting. */
3516 wlist = expand_word_leave_quoted (case_command->word, 0);
3517 if (wlist)
3518 {
3519 char *t;
3520 t = string_list (wlist);
3521 word = dequote_string (t);
3522 free (t);
3523 }
3524 else
3525 word = savestring ("");
3526 dispose_words (wlist);
3527
3528 retval = EXECUTION_SUCCESS;
3529 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
3530
3531 begin_unwind_frame ("case");
3532 add_unwind_protect (xfree, word);
3533
3534 #define EXIT_CASE() goto exit_case_command
3535
3536 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
3537 {
3538 QUIT;
3539 for (list = clauses->patterns; list; list = list->next)
3540 {
3541 es = expand_word_leave_quoted (list->word, 0);
3542
3543 if (es && es->word && es->word->word && *(es->word->word))
3544 {
3545 /* Convert quoted null strings into empty strings. */
3546 qflags = QGLOB_CVTNULL;
3547
3548 /* We left CTLESC in place quoting CTLESC and CTLNUL after the
3549 call to expand_word_leave_quoted; tell quote_string_for_globbing
3550 to remove those here. This works for both unquoted portions of
3551 the word (which call quote_escapes) and quoted portions
3552 (which call quote_string). */
3553 qflags |= QGLOB_CTLESC;
3554 pattern = quote_string_for_globbing (es->word->word, qflags);
3555 }
3556 else
3557 {
3558 pattern = (char *)xmalloc (1);
3559 pattern[0] = '\0';
3560 }
3561
3562 /* Since the pattern does not undergo quote removal (as per
3563 Posix.2, section 3.9.4.3), the strmatch () call must be able
3564 to recognize backslashes as escape characters. */
3565 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
3566 free (pattern);
3567
3568 dispose_words (es);
3569
3570 if (match)
3571 {
3572 do
3573 {
3574 if (clauses->action && ignore_return)
3575 clauses->action->flags |= CMD_IGNORE_RETURN;
3576 retval = execute_command (clauses->action);
3577 }
3578 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
3579 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3580 EXIT_CASE ();
3581 else
3582 break;
3583 }
3584
3585 QUIT;
3586 }
3587 }
3588
3589 exit_case_command:
3590 free (word);
3591 discard_unwind_frame ("case");
3592 line_number = save_line_number;
3593 return (retval);
3594 }
3595
3596 #define CMD_WHILE 0
3597 #define CMD_UNTIL 1
3598
3599 /* The WHILE command. Syntax: WHILE test DO action; DONE.
3600 Repeatedly execute action while executing test produces
3601 EXECUTION_SUCCESS. */
3602 static int
3603 execute_while_command (while_command)
3604 WHILE_COM *while_command;
3605 {
3606 return (execute_while_or_until (while_command, CMD_WHILE));
3607 }
3608
3609 /* UNTIL is just like WHILE except that the test result is negated. */
3610 static int
3611 execute_until_command (while_command)
3612 WHILE_COM *while_command;
3613 {
3614 return (execute_while_or_until (while_command, CMD_UNTIL));
3615 }
3616
3617 /* The body for both while and until. The only difference between the
3618 two is that the test value is treated differently. TYPE is
3619 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3620 be EXECUTION_SUCCESS if no commands in the body are executed, and
3621 the status of the last command executed in the body otherwise. */
3622 static int
3623 execute_while_or_until (while_command, type)
3624 WHILE_COM *while_command;
3625 int type;
3626 {
3627 int return_value, body_status;
3628
3629 body_status = EXECUTION_SUCCESS;
3630 loop_level++;
3631
3632 while_command->test->flags |= CMD_IGNORE_RETURN;
3633 if (while_command->flags & CMD_IGNORE_RETURN)
3634 while_command->action->flags |= CMD_IGNORE_RETURN;
3635
3636 while (1)
3637 {
3638 return_value = execute_command (while_command->test);
3639 REAP ();
3640
3641 /* Need to handle `break' in the test when we would break out of the
3642 loop. The job control code will set `breaking' to loop_level
3643 when a job in a loop is stopped with SIGTSTP. If the stopped job
3644 is in the loop test, `breaking' will not be reset unless we do
3645 this, and the shell will cease to execute commands. The same holds
3646 true for `continue'. */
3647 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
3648 {
3649 if (breaking)
3650 breaking--;
3651 if (continuing)
3652 continuing--;
3653 break;
3654 }
3655 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
3656 {
3657 if (breaking)
3658 breaking--;
3659 if (continuing)
3660 continuing--;
3661 break;
3662 }
3663
3664 QUIT;
3665 body_status = execute_command (while_command->action);
3666 QUIT;
3667
3668 if (breaking)
3669 {
3670 breaking--;
3671 break;
3672 }
3673
3674 if (continuing)
3675 {
3676 continuing--;
3677 if (continuing)
3678 break;
3679 }
3680 }
3681 loop_level--;
3682
3683 return (body_status);
3684 }
3685
3686 /* IF test THEN command [ELSE command].
3687 IF also allows ELIF in the place of ELSE IF, but
3688 the parser makes *that* stupidity transparent. */
3689 static int
3690 execute_if_command (if_command)
3691 IF_COM *if_command;
3692 {
3693 int return_value, save_line_number;
3694
3695 save_line_number = line_number;
3696 if_command->test->flags |= CMD_IGNORE_RETURN;
3697 return_value = execute_command (if_command->test);
3698 line_number = save_line_number;
3699
3700 if (return_value == EXECUTION_SUCCESS)
3701 {
3702 QUIT;
3703
3704 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
3705 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3706
3707 return (execute_command (if_command->true_case));
3708 }
3709 else
3710 {
3711 QUIT;
3712
3713 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3714 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3715
3716 return (execute_command (if_command->false_case));
3717 }
3718 }
3719
3720 #if defined (DPAREN_ARITHMETIC)
3721 static int
3722 execute_arith_command (arith_command)
3723 ARITH_COM *arith_command;
3724 {
3725 int expok, save_line_number, retval;
3726 intmax_t expresult;
3727 WORD_LIST *new;
3728 char *exp, *t;
3729
3730 expresult = 0;
3731
3732 save_line_number = line_number;
3733 this_command_name = "(("; /* )) */
3734 line_number_for_err_trap = line_number = arith_command->line;
3735 /* If we're in a function, update the line number information. */
3736 if (variable_context && interactive_shell && sourcelevel == 0)
3737 {
3738 /* line numbers in a function start at 1 */
3739 line_number -= function_line_number - 1;
3740 if (line_number <= 0)
3741 line_number = 1;
3742 }
3743
3744 command_string_index = 0;
3745 print_arith_command (arith_command->exp);
3746
3747 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3748 {
3749 FREE (the_printed_command_except_trap);
3750 the_printed_command_except_trap = savestring (the_printed_command);
3751 }
3752
3753 /* Run the debug trap before each arithmetic command, but do it after we
3754 update the line number information and before we expand the various
3755 words in the expression. */
3756 retval = run_debug_trap ();
3757 #if defined (DEBUGGER)
3758 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3759 skip the command. */
3760 if (debugging_mode && retval != EXECUTION_SUCCESS)
3761 {
3762 line_number = save_line_number;
3763 return (EXECUTION_SUCCESS);
3764 }
3765 #endif
3766
3767 t = (char *)NULL;
3768 new = arith_command->exp;
3769 if (new->next)
3770 exp = t = string_list (new); /* just in case */
3771 else
3772 exp = new->word->word;
3773
3774 exp = expand_arith_string (exp, Q_DOUBLE_QUOTES|Q_ARITH);
3775
3776 /* If we're tracing, make a new word list with `((' at the front and `))'
3777 at the back and print it. Change xtrace_print_arith_cmd to take a string
3778 when I change eval_arith_for_expr to use expand_arith_string(). */
3779 if (echo_command_at_execute)
3780 {
3781 new = make_word_list (make_word (exp ? exp : ""), (WORD_LIST *)NULL);
3782 xtrace_print_arith_cmd (new);
3783 dispose_words (new);
3784 }
3785
3786 if (exp)
3787 {
3788 expresult = evalexp (exp, EXP_EXPANDED, &expok);
3789 line_number = save_line_number;
3790 free (exp);
3791 }
3792 else
3793 {
3794 expresult = 0;
3795 expok = 1;
3796 }
3797 FREE (t);
3798
3799 if (expok == 0)
3800 return (EXECUTION_FAILURE);
3801
3802 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
3803 }
3804 #endif /* DPAREN_ARITHMETIC */
3805
3806 #if defined (COND_COMMAND)
3807
3808 static char * const nullstr = "";
3809
3810 /* XXX - can COND ever be NULL when this is called? */
3811 static int
3812 execute_cond_node (cond)
3813 COND_COM *cond;
3814 {
3815 int result, invert, patmatch, rmatch, mflags, ignore;
3816 char *arg1, *arg2;
3817 #if 0
3818 char *t1, *t2;
3819 #endif
3820
3821 invert = (cond->flags & CMD_INVERT_RETURN);
3822 ignore = (cond->flags & CMD_IGNORE_RETURN);
3823 if (ignore)
3824 {
3825 if (cond->left)
3826 cond->left->flags |= CMD_IGNORE_RETURN;
3827 if (cond->right)
3828 cond->right->flags |= CMD_IGNORE_RETURN;
3829 }
3830
3831 if (cond->type == COND_EXPR)
3832 result = execute_cond_node (cond->left);
3833 else if (cond->type == COND_OR)
3834 {
3835 result = execute_cond_node (cond->left);
3836 if (result != EXECUTION_SUCCESS)
3837 result = execute_cond_node (cond->right);
3838 }
3839 else if (cond->type == COND_AND)
3840 {
3841 result = execute_cond_node (cond->left);
3842 if (result == EXECUTION_SUCCESS)
3843 result = execute_cond_node (cond->right);
3844 }
3845 else if (cond->type == COND_UNARY)
3846 {
3847 if (ignore)
3848 comsub_ignore_return++;
3849 arg1 = cond_expand_word (cond->left->op, 0);
3850 if (ignore)
3851 comsub_ignore_return--;
3852 if (arg1 == 0)
3853 arg1 = nullstr;
3854 if (echo_command_at_execute)
3855 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3856 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3857 if (arg1 != nullstr)
3858 free (arg1);
3859 }
3860 else if (cond->type == COND_BINARY)
3861 {
3862 rmatch = 0;
3863 patmatch = (((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3864 (cond->op->word[0] == '!' || cond->op->word[0] == '=')) ||
3865 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
3866 #if defined (COND_REGEXP)
3867 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3868 cond->op->word[2] == '\0');
3869 #endif
3870
3871 if (ignore)
3872 comsub_ignore_return++;
3873 arg1 = cond_expand_word (cond->left->op, 0);
3874 if (ignore)
3875 comsub_ignore_return--;
3876 if (arg1 == 0)
3877 arg1 = nullstr;
3878 if (ignore)
3879 comsub_ignore_return++;
3880 arg2 = cond_expand_word (cond->right->op,
3881 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
3882 if (ignore)
3883 comsub_ignore_return--;
3884 if (arg2 == 0)
3885 arg2 = nullstr;
3886
3887 if (echo_command_at_execute)
3888 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3889
3890 #if defined (COND_REGEXP)
3891 if (rmatch)
3892 {
3893 mflags = SHMAT_PWARN;
3894 #if defined (ARRAY_VARS)
3895 mflags |= SHMAT_SUBEXP;
3896 #endif
3897
3898 #if 0
3899 t1 = strescape(arg1);
3900 t2 = strescape(arg2);
3901 itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1, t2);
3902 free(t1);
3903 free(t2);
3904 #endif
3905
3906 result = sh_regmatch (arg1, arg2, mflags);
3907 }
3908 else
3909 #endif /* COND_REGEXP */
3910 {
3911 int oe;
3912 oe = extended_glob;
3913 extended_glob = 1;
3914 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
3915 ? EXECUTION_SUCCESS
3916 : EXECUTION_FAILURE;
3917 extended_glob = oe;
3918 }
3919 if (arg1 != nullstr)
3920 free (arg1);
3921 if (arg2 != nullstr)
3922 free (arg2);
3923 }
3924 else
3925 {
3926 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
3927 jump_to_top_level (DISCARD);
3928 result = EXECUTION_FAILURE;
3929 }
3930
3931 if (invert)
3932 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3933
3934 return result;
3935 }
3936
3937 static int
3938 execute_cond_command (cond_command)
3939 COND_COM *cond_command;
3940 {
3941 int retval, save_line_number;
3942
3943 save_line_number = line_number;
3944
3945 this_command_name = "[[";
3946 line_number_for_err_trap = line_number = cond_command->line;
3947 /* If we're in a function, update the line number information. */
3948 if (variable_context && interactive_shell && sourcelevel == 0)
3949 {
3950 /* line numbers in a function start at 1 */
3951 line_number -= function_line_number - 1;
3952 if (line_number <= 0)
3953 line_number = 1;
3954 }
3955 command_string_index = 0;
3956 print_cond_command (cond_command);
3957
3958 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3959 {
3960 FREE (the_printed_command_except_trap);
3961 the_printed_command_except_trap = savestring (the_printed_command);
3962 }
3963
3964 /* Run the debug trap before each conditional command, but do it after we
3965 update the line number information. */
3966 retval = run_debug_trap ();
3967 #if defined (DEBUGGER)
3968 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3969 skip the command. */
3970 if (debugging_mode && retval != EXECUTION_SUCCESS)
3971 {
3972 line_number = save_line_number;
3973 return (EXECUTION_SUCCESS);
3974 }
3975 #endif
3976
3977 #if 0
3978 debug_print_cond_command (cond_command);
3979 #endif
3980
3981 last_command_exit_value = retval = execute_cond_node (cond_command);
3982 line_number = save_line_number;
3983 return (retval);
3984 }
3985 #endif /* COND_COMMAND */
3986
3987 static void
3988 bind_lastarg (arg)
3989 char *arg;
3990 {
3991 SHELL_VAR *var;
3992
3993 if (arg == 0)
3994 arg = "";
3995 var = bind_variable ("_", arg, 0);
3996 if (var)
3997 VUNSETATTR (var, att_exported);
3998 }
3999
4000 /* Execute a null command. Fork a subshell if the command uses pipes or is
4001 to be run asynchronously. This handles all the side effects that are
4002 supposed to take place. */
4003 static int
4004 execute_null_command (redirects, pipe_in, pipe_out, async)
4005 REDIRECT *redirects;
4006 int pipe_in, pipe_out, async;
4007 {
4008 int r;
4009 int forcefork, fork_flags;
4010 REDIRECT *rd;
4011
4012 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
4013 {
4014 forcefork += rd->rflags & REDIR_VARASSIGN;
4015 /* Safety */
4016 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);
4017 }
4018
4019 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
4020 {
4021 /* We have a null command, but we really want a subshell to take
4022 care of it. Just fork, do piping and redirections, and exit. */
4023 fork_flags = async ? FORK_ASYNC : 0;
4024 if (make_child ((char *)NULL, fork_flags) == 0)
4025 {
4026 /* Cancel traps, in trap.c. */
4027 restore_original_signals (); /* XXX */
4028
4029 do_piping (pipe_in, pipe_out);
4030
4031 #if defined (COPROCESS_SUPPORT)
4032 coproc_closeall ();
4033 #endif
4034
4035 interactive = 0; /* XXX */
4036
4037 subshell_environment = 0;
4038 if (async)
4039 subshell_environment |= SUBSHELL_ASYNC;
4040 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4041 subshell_environment |= SUBSHELL_PIPE;
4042
4043 if (do_redirections (redirects, RX_ACTIVE) == 0)
4044 exit (EXECUTION_SUCCESS);
4045 else
4046 exit (EXECUTION_FAILURE);
4047 }
4048 else
4049 {
4050 close_pipes (pipe_in, pipe_out);
4051 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
4052 if (pipe_out == NO_PIPE)
4053 unlink_fifo_list ();
4054 #endif
4055 return (EXECUTION_SUCCESS);
4056 }
4057 }
4058 else
4059 {
4060 /* Even if there aren't any command names, pretend to do the
4061 redirections that are specified. The user expects the side
4062 effects to take place. If the redirections fail, then return
4063 failure. Otherwise, if a command substitution took place while
4064 expanding the command or a redirection, return the value of that
4065 substitution. Otherwise, return EXECUTION_SUCCESS. */
4066
4067 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
4068 cleanup_redirects (redirection_undo_list);
4069 redirection_undo_list = (REDIRECT *)NULL;
4070
4071 if (r != 0)
4072 return (EXECUTION_FAILURE);
4073 else if (last_command_subst_pid != NO_PID)
4074 return (last_command_exit_value);
4075 else
4076 return (EXECUTION_SUCCESS);
4077 }
4078 }
4079
4080 /* This is a hack to suppress word splitting for assignment statements
4081 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
4082 static void
4083 fix_assignment_words (words)
4084 WORD_LIST *words;
4085 {
4086 WORD_LIST *w, *wcmd;
4087 struct builtin *b;
4088 int assoc, global, array, integer;
4089
4090 if (words == 0)
4091 return;
4092
4093 b = 0;
4094 assoc = global = array = integer = 0;
4095
4096 /* Skip over assignment statements preceding a command name */
4097 wcmd = words;
4098 for (wcmd = words; wcmd; wcmd = wcmd->next)
4099 if ((wcmd->word->flags & W_ASSIGNMENT) == 0)
4100 break;
4101 /* Posix (post-2008) says that `command' doesn't change whether
4102 or not the builtin it shadows is a `declaration command', even
4103 though it removes other special builtin properties. In Posix
4104 mode, we skip over one or more instances of `command' and
4105 deal with the next word as the assignment builtin. */
4106 while (posixly_correct && wcmd && wcmd->word && wcmd->word->word && STREQ (wcmd->word->word, "command"))
4107 wcmd = wcmd->next;
4108
4109 for (w = wcmd; w; w = w->next)
4110 if (w->word->flags & W_ASSIGNMENT)
4111 {
4112 /* Lazy builtin lookup, only do it if we find an assignment */
4113 if (b == 0)
4114 {
4115 b = builtin_address_internal (wcmd->word->word, 0);
4116 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4117 return;
4118 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
4119 wcmd->word->flags |= W_ASSNBLTIN;
4120 }
4121 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
4122 #if defined (ARRAY_VARS)
4123 if (assoc)
4124 w->word->flags |= W_ASSIGNASSOC;
4125 if (array)
4126 w->word->flags |= W_ASSIGNARRAY;
4127 #endif
4128 if (global)
4129 w->word->flags |= W_ASSNGLOBAL;
4130
4131 /* If we have an assignment builtin that does not create local variables,
4132 make sure we create global variables even if we internally call
4133 `declare'. The CHKLOCAL flag means to set attributes or values on
4134 an existing local variable, if there is one. */
4135 if (b && ((b->flags & (ASSIGNMENT_BUILTIN|LOCALVAR_BUILTIN)) == ASSIGNMENT_BUILTIN))
4136 w->word->flags |= W_ASSNGLOBAL|W_CHKLOCAL;
4137 else if (b && (b->flags & ASSIGNMENT_BUILTIN) && (b->flags & LOCALVAR_BUILTIN) && variable_context)
4138 w->word->flags |= W_FORCELOCAL;
4139 }
4140 #if defined (ARRAY_VARS)
4141 /* Note that we saw an associative array option to a builtin that takes
4142 assignment statements. This is a bit of a kludge. */
4143 else if (w->word->word[0] == '-' && (strpbrk (w->word->word+1, "Aag") != 0))
4144 #else
4145 else if (w->word->word[0] == '-' && strchr (w->word->word+1, 'g'))
4146 #endif
4147 {
4148 if (b == 0)
4149 {
4150 b = builtin_address_internal (wcmd->word->word, 0);
4151 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4152 return;
4153 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
4154 wcmd->word->flags |= W_ASSNBLTIN;
4155 }
4156 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'A'))
4157 assoc = 1;
4158 else if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'a'))
4159 array = 1;
4160 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'g'))
4161 global = 1;
4162 }
4163 }
4164
4165 #ifndef ISOPTION
4166 # define ISOPTION(s, c) (s[0] == '-' && s[1] == c && s[2] == 0)
4167 #endif
4168
4169 #define RETURN_NOT_COMMAND() \
4170 do { if (typep) *typep = 0; return words; } while (0)
4171
4172 /* Make sure we have `command [-p] command_name [args]', and handle skipping
4173 over the usual `--' that ends the options. Returns the updated WORDS with
4174 the command and options stripped and sets *TYPEP to a non-zero value. If
4175 any other options are supplied, or there is not a command_name, we punt
4176 and return a zero value in *TYPEP without updating WORDS. */
4177 static WORD_LIST *
4178 check_command_builtin (words, typep)
4179 WORD_LIST *words;
4180 int *typep;
4181 {
4182 int type;
4183 WORD_LIST *w;
4184
4185 w = words->next;
4186 type = 1;
4187
4188 if (w && ISOPTION (w->word->word, 'p')) /* command -p */
4189 {
4190 #if defined (RESTRICTED_SHELL)
4191 if (restricted)
4192 RETURN_NOT_COMMAND();
4193 #endif
4194 w = w->next;
4195 type = 2;
4196 }
4197
4198 if (w && ISOPTION (w->word->word, '-')) /* command [-p] -- */
4199 w = w->next;
4200 else if (w && w->word->word[0] == '-') /* any other option */
4201 RETURN_NOT_COMMAND();
4202
4203 if (w == 0 || w->word->word == 0) /* must have a command_name */
4204 RETURN_NOT_COMMAND();
4205
4206 if (typep)
4207 *typep = type;
4208 return w;
4209 }
4210
4211 /* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
4212 to PATHNAME, is a directory. Used by the autocd code below. */
4213 static int
4214 is_dirname (pathname)
4215 char *pathname;
4216 {
4217 char *temp;
4218 int ret;
4219
4220 temp = search_for_command (pathname, 0);
4221 ret = temp ? file_isdir (temp) : file_isdir (pathname);
4222 free (temp);
4223 return ret;
4224 }
4225
4226 /* The meaty part of all the executions. We have to start hacking the
4227 real execution of commands here. Fork a process, set things up,
4228 execute the command. */
4229 static int
4230 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
4231 SIMPLE_COM *simple_command;
4232 int pipe_in, pipe_out, async;
4233 struct fd_bitmap *fds_to_close;
4234 {
4235 WORD_LIST *words, *lastword;
4236 char *command_line, *lastarg, *temp;
4237 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
4238 int fork_flags, cmdflags;
4239 pid_t old_last_async_pid;
4240 sh_builtin_func_t *builtin;
4241 SHELL_VAR *func;
4242 volatile int old_builtin, old_command_builtin;
4243
4244 result = EXECUTION_SUCCESS;
4245 special_builtin_failed = builtin_is_special = 0;
4246 command_line = (char *)0;
4247
4248 QUIT;
4249
4250 /* If we're in a function, update the line number information. */
4251 if (variable_context && interactive_shell && sourcelevel == 0)
4252 {
4253 /* line numbers in a function start at 1 */
4254 line_number -= function_line_number - 1;
4255 if (line_number <= 0)
4256 line_number = 1;
4257 }
4258
4259 /* Remember what this command line looks like at invocation. */
4260 command_string_index = 0;
4261 print_simple_command (simple_command);
4262
4263 #if 0
4264 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
4265 #else
4266 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
4267 #endif
4268 {
4269 FREE (the_printed_command_except_trap);
4270 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
4271 }
4272
4273 /* Run the debug trap before each simple command, but do it after we
4274 update the line number information. */
4275 result = run_debug_trap ();
4276 #if defined (DEBUGGER)
4277 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4278 skip the command. */
4279 if (debugging_mode && result != EXECUTION_SUCCESS)
4280 return (EXECUTION_SUCCESS);
4281 #endif
4282
4283 cmdflags = simple_command->flags;
4284
4285 first_word_quoted =
4286 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
4287
4288 last_command_subst_pid = NO_PID;
4289 old_last_async_pid = last_asynchronous_pid;
4290
4291 already_forked = 0;
4292
4293 /* If we're in a pipeline or run in the background, set DOFORK so we
4294 make the child early, before word expansion. This keeps assignment
4295 statements from affecting the parent shell's environment when they
4296 should not. */
4297 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
4298
4299 /* Something like `%2 &' should restart job 2 in the background, not cause
4300 the shell to fork here. */
4301 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
4302 simple_command->words && simple_command->words->word &&
4303 simple_command->words->word->word &&
4304 (simple_command->words->word->word[0] == '%'))
4305 dofork = 0;
4306
4307 if (dofork)
4308 {
4309 char *p;
4310
4311 /* Do this now, because execute_disk_command will do it anyway in the
4312 vast majority of cases. */
4313 maybe_make_export_env ();
4314
4315 /* Don't let a DEBUG trap overwrite the command string to be saved with
4316 the process/job associated with this child. */
4317 fork_flags = async ? FORK_ASYNC : 0;
4318 if (make_child (p = savestring (the_printed_command_except_trap), fork_flags) == 0)
4319 {
4320 already_forked = 1;
4321 cmdflags |= CMD_NO_FORK;
4322
4323 subshell_environment = SUBSHELL_FORK; /* XXX */
4324 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4325 subshell_environment |= SUBSHELL_PIPE;
4326 if (async)
4327 subshell_environment |= SUBSHELL_ASYNC;
4328
4329 /* We need to do this before piping to handle some really
4330 pathological cases where one of the pipe file descriptors
4331 is < 2. */
4332 if (fds_to_close)
4333 close_fd_bitmap (fds_to_close);
4334
4335 /* If we fork because of an input pipe, note input pipe for later to
4336 inhibit async commands from redirecting stdin from /dev/null */
4337 stdin_redir |= pipe_in != NO_PIPE;
4338
4339 do_piping (pipe_in, pipe_out);
4340 pipe_in = pipe_out = NO_PIPE;
4341 #if defined (COPROCESS_SUPPORT)
4342 coproc_closeall ();
4343 #endif
4344
4345 last_asynchronous_pid = old_last_async_pid;
4346
4347 if (async)
4348 subshell_level++; /* not for pipes yet */
4349
4350 #if defined (JOB_CONTROL)
4351 FREE (p); /* child doesn't use pointer */
4352 #endif
4353 }
4354 else
4355 {
4356 /* Don't let simple commands that aren't the last command in a
4357 pipeline change $? for the rest of the pipeline (or at all). */
4358 if (pipe_out != NO_PIPE)
4359 result = last_command_exit_value;
4360 close_pipes (pipe_in, pipe_out);
4361 command_line = (char *)NULL; /* don't free this. */
4362 return (result);
4363 }
4364 }
4365
4366 QUIT; /* XXX */
4367
4368 /* If we are re-running this as the result of executing the `command'
4369 builtin, do not expand the command words a second time. */
4370 if ((cmdflags & CMD_INHIBIT_EXPANSION) == 0)
4371 {
4372 current_fds_to_close = fds_to_close;
4373 fix_assignment_words (simple_command->words);
4374 /* Pass the ignore return flag down to command substitutions */
4375 if (cmdflags & CMD_IGNORE_RETURN) /* XXX */
4376 comsub_ignore_return++;
4377 words = expand_words (simple_command->words);
4378 if (cmdflags & CMD_IGNORE_RETURN)
4379 comsub_ignore_return--;
4380 current_fds_to_close = (struct fd_bitmap *)NULL;
4381 }
4382 else
4383 words = copy_word_list (simple_command->words);
4384
4385 /* It is possible for WORDS not to have anything left in it.
4386 Perhaps all the words consisted of `$foo', and there was
4387 no variable `$foo'. */
4388 if (words == 0)
4389 {
4390 this_command_name = 0;
4391 result = execute_null_command (simple_command->redirects,
4392 pipe_in, pipe_out,
4393 already_forked ? 0 : async);
4394 if (already_forked)
4395 sh_exit (result);
4396 else
4397 {
4398 bind_lastarg ((char *)NULL);
4399 set_pipestatus_from_exit (result);
4400 return (result);
4401 }
4402 }
4403
4404 lastarg = (char *)NULL;
4405
4406 begin_unwind_frame ("simple-command");
4407
4408 if (echo_command_at_execute && (cmdflags & CMD_COMMAND_BUILTIN) == 0)
4409 xtrace_print_word_list (words, 1);
4410
4411 builtin = (sh_builtin_func_t *)NULL;
4412 func = (SHELL_VAR *)NULL;
4413
4414 /* This test is still here in case we want to change the command builtin
4415 handler code below to recursively call execute_simple_command (after
4416 modifying the simple_command struct). */
4417 if ((cmdflags & CMD_NO_FUNCTIONS) == 0)
4418 {
4419 /* Posix.2 says special builtins are found before functions. We
4420 don't set builtin_is_special anywhere other than here, because
4421 this path is followed only when the `command' builtin is *not*
4422 being used, and we don't want to exit the shell if a special
4423 builtin executed with `command builtin' fails. `command' is not
4424 a special builtin. */
4425 if (posixly_correct)
4426 {
4427 builtin = find_special_builtin (words->word->word);
4428 if (builtin)
4429 builtin_is_special = 1;
4430 }
4431 if (builtin == 0)
4432 func = find_function (words->word->word);
4433 }
4434
4435 /* In POSIX mode, assignment errors in the temporary environment cause a
4436 non-interactive shell to exit. */
4437 #if 1
4438 if (posixly_correct && builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
4439 #else
4440 /* This is for strict posix conformance. */
4441 if (posixly_correct && interactive_shell == 0 && tempenv_assign_error)
4442 #endif
4443 {
4444 last_command_exit_value = EXECUTION_FAILURE;
4445 jump_to_top_level (ERREXIT);
4446 }
4447 tempenv_assign_error = 0; /* don't care about this any more */
4448
4449 /* This is where we handle the command builtin as a pseudo-reserved word
4450 prefix. This allows us to optimize away forks if we can. */
4451 old_command_builtin = -1;
4452 if (builtin == 0 && func == 0)
4453 {
4454 WORD_LIST *disposer, *l;
4455 int cmdtype;
4456
4457 builtin = find_shell_builtin (words->word->word);
4458 while (builtin == command_builtin)
4459 {
4460 disposer = words;
4461 cmdtype = 0;
4462 words = check_command_builtin (words, &cmdtype);
4463 if (cmdtype > 0) /* command -p [--] words */
4464 {
4465 for (l = disposer; l->next != words; l = l->next)
4466 ;
4467 l->next = 0;
4468 dispose_words (disposer);
4469 cmdflags |= CMD_COMMAND_BUILTIN | CMD_NO_FUNCTIONS;
4470 if (cmdtype == 2)
4471 cmdflags |= CMD_STDPATH;
4472 builtin = find_shell_builtin (words->word->word);
4473 }
4474 else
4475 break;
4476 }
4477 if (cmdflags & CMD_COMMAND_BUILTIN)
4478 {
4479 old_command_builtin = executing_command_builtin;
4480 unwind_protect_int (executing_command_builtin);
4481 executing_command_builtin |= 1;
4482 }
4483 builtin = 0;
4484 }
4485
4486 add_unwind_protect (dispose_words, words);
4487 QUIT;
4488
4489 /* Bind the last word in this command to "$_" after execution. */
4490 for (lastword = words; lastword->next; lastword = lastword->next)
4491 ;
4492 lastarg = lastword->word->word;
4493
4494 #if defined (JOB_CONTROL)
4495 /* Is this command a job control related thing? */
4496 if (words->word->word[0] == '%' && already_forked == 0)
4497 {
4498 this_command_name = async ? "bg" : "fg";
4499 last_shell_builtin = this_shell_builtin;
4500 this_shell_builtin = builtin_address (this_command_name);
4501 result = (*this_shell_builtin) (words);
4502 goto return_result;
4503 }
4504
4505 /* One other possibililty. The user may want to resume an existing job.
4506 If they do, find out whether this word is a candidate for a running
4507 job. */
4508 if (job_control && already_forked == 0 && async == 0 &&
4509 !first_word_quoted &&
4510 !words->next &&
4511 words->word->word[0] &&
4512 !simple_command->redirects &&
4513 pipe_in == NO_PIPE &&
4514 pipe_out == NO_PIPE &&
4515 (temp = get_string_value ("auto_resume")))
4516 {
4517 int job, jflags, started_status;
4518
4519 jflags = JM_STOPPED|JM_FIRSTMATCH;
4520 if (STREQ (temp, "exact"))
4521 jflags |= JM_EXACT;
4522 else if (STREQ (temp, "substring"))
4523 jflags |= JM_SUBSTRING;
4524 else
4525 jflags |= JM_PREFIX;
4526 job = get_job_by_name (words->word->word, jflags);
4527 if (job != NO_JOB)
4528 {
4529 run_unwind_frame ("simple-command");
4530 this_command_name = "fg";
4531 last_shell_builtin = this_shell_builtin;
4532 this_shell_builtin = builtin_address ("fg");
4533
4534 started_status = start_job (job, 1);
4535 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
4536 }
4537 }
4538 #endif /* JOB_CONTROL */
4539
4540 run_builtin:
4541 /* Remember the name of this command globally. */
4542 this_command_name = words->word->word;
4543
4544 QUIT;
4545
4546 /* This command could be a shell builtin or a user-defined function.
4547 We have already found special builtins by this time, so we do not
4548 set builtin_is_special. If this is a function or builtin, and we
4549 have pipes, then fork a subshell in here. Otherwise, just execute
4550 the command directly. */
4551 if (func == 0 && builtin == 0)
4552 builtin = find_shell_builtin (this_command_name);
4553
4554 last_shell_builtin = this_shell_builtin;
4555 this_shell_builtin = builtin;
4556
4557 if (builtin || func)
4558 {
4559 if (builtin)
4560 {
4561 old_builtin = executing_builtin;
4562 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
4563 if (old_command_builtin == -1) /* sentinel, can be set above */
4564 {
4565 old_command_builtin = executing_command_builtin;
4566 unwind_protect_int (executing_command_builtin); /* ditto and set above */
4567 }
4568 }
4569 if (already_forked)
4570 {
4571 /* reset_terminating_signals (); */ /* XXX */
4572 /* Reset the signal handlers in the child, but don't free the
4573 trap strings. Set a flag noting that we have to free the
4574 trap strings if we run trap to change a signal disposition. */
4575 reset_signal_handlers ();
4576 subshell_environment |= SUBSHELL_RESETTRAP;
4577
4578 if (async)
4579 {
4580 if ((cmdflags & CMD_STDIN_REDIR) &&
4581 pipe_in == NO_PIPE &&
4582 (stdin_redirects (simple_command->redirects) == 0))
4583 async_redirect_stdin ();
4584 setup_async_signals ();
4585 }
4586
4587 if (async == 0)
4588 subshell_level++;
4589 execute_subshell_builtin_or_function
4590 (words, simple_command->redirects, builtin, func,
4591 pipe_in, pipe_out, async, fds_to_close,
4592 cmdflags);
4593 subshell_level--;
4594 }
4595 else
4596 {
4597 result = execute_builtin_or_function
4598 (words, builtin, func, simple_command->redirects, fds_to_close,
4599 cmdflags);
4600 if (builtin)
4601 {
4602 if (result > EX_SHERRBASE)
4603 {
4604 switch (result)
4605 {
4606 case EX_REDIRFAIL:
4607 case EX_BADASSIGN:
4608 case EX_EXPFAIL:
4609 /* These errors cause non-interactive posix mode shells to exit */
4610 if (posixly_correct && builtin_is_special && interactive_shell == 0)
4611 {
4612 last_command_exit_value = EXECUTION_FAILURE;
4613 jump_to_top_level (ERREXIT);
4614 }
4615 break;
4616 case EX_DISKFALLBACK:
4617 /* XXX - experimental */
4618 executing_builtin = old_builtin;
4619 executing_command_builtin = old_command_builtin;
4620 builtin = 0;
4621 /* XXX - redirections will have to be performed again */
4622 goto execute_from_filesystem;
4623 }
4624 result = builtin_status (result);
4625 if (builtin_is_special)
4626 special_builtin_failed = 1; /* XXX - take command builtin into account? */
4627 }
4628 /* In POSIX mode, if there are assignment statements preceding
4629 a special builtin, they persist after the builtin
4630 completes. */
4631 if (posixly_correct && builtin_is_special && temporary_env)
4632 merge_temporary_env ();
4633 }
4634 else /* function */
4635 {
4636 if (result == EX_USAGE)
4637 result = EX_BADUSAGE;
4638 else if (result > EX_SHERRBASE)
4639 result = builtin_status (result);
4640 }
4641
4642 set_pipestatus_from_exit (result);
4643
4644 goto return_result;
4645 }
4646 }
4647
4648 if (autocd && interactive && words->word && is_dirname (words->word->word))
4649 {
4650 words = make_word_list (make_word ("--"), words);
4651 words = make_word_list (make_word ("cd"), words);
4652 xtrace_print_word_list (words, 0);
4653 func = find_function ("cd");
4654 goto run_builtin;
4655 }
4656
4657 execute_from_filesystem:
4658 if (command_line == 0)
4659 command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
4660
4661 #if defined (PROCESS_SUBSTITUTION)
4662 /* The old code did not test already_forked and only did this if
4663 subshell_environment&SUBSHELL_COMSUB != 0 (comsubs and procsubs). Other
4664 uses of the no-fork optimization left FIFOs in $TMPDIR */
4665 if (already_forked == 0 && (cmdflags & CMD_NO_FORK) && fifos_pending() > 0)
4666 cmdflags &= ~CMD_NO_FORK;
4667 #endif
4668 result = execute_disk_command (words, simple_command->redirects, command_line,
4669 pipe_in, pipe_out, async, fds_to_close,
4670 cmdflags);
4671
4672 return_result:
4673 bind_lastarg (lastarg);
4674 FREE (command_line);
4675 dispose_words (words);
4676 if (builtin)
4677 {
4678 executing_builtin = old_builtin;
4679 executing_command_builtin = old_command_builtin;
4680 }
4681 discard_unwind_frame ("simple-command");
4682 this_command_name = (char *)NULL; /* points to freed memory now */
4683 return (result);
4684 }
4685
4686 /* Translate the special builtin exit statuses. We don't really need a
4687 function for this; it's a placeholder for future work. */
4688 static int
4689 builtin_status (result)
4690 int result;
4691 {
4692 int r;
4693
4694 switch (result)
4695 {
4696 case EX_USAGE:
4697 case EX_BADSYNTAX:
4698 r = EX_BADUSAGE;
4699 break;
4700 case EX_REDIRFAIL:
4701 case EX_BADASSIGN:
4702 case EX_EXPFAIL:
4703 r = EXECUTION_FAILURE;
4704 break;
4705 default:
4706 /* other special exit statuses not yet defined */
4707 r = (result > EX_SHERRBASE) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
4708 break;
4709 }
4710 return (r);
4711 }
4712
4713 static int
4714 execute_builtin (builtin, words, flags, subshell)
4715 sh_builtin_func_t *builtin;
4716 WORD_LIST *words;
4717 int flags, subshell;
4718 {
4719 int result, eval_unwind, ignexit_flag;
4720 int isbltinenv, should_keep;
4721 char *error_trap;
4722
4723 error_trap = 0;
4724 should_keep = 0;
4725
4726 /* The eval builtin calls parse_and_execute, which does not know about
4727 the setting of flags, and always calls the execution functions with
4728 flags that will exit the shell on an error if -e is set. If the
4729 eval builtin is being called, and we're supposed to ignore the exit
4730 value of the command, we turn the -e flag off ourselves and disable
4731 the ERR trap, then restore them when the command completes. This is
4732 also a problem (as below) for the command and source/. builtins. */
4733 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
4734 (builtin == eval_builtin || (flags & CMD_COMMAND_BUILTIN) || builtin == source_builtin))
4735 {
4736 begin_unwind_frame ("eval_builtin");
4737 unwind_protect_int (exit_immediately_on_error);
4738 unwind_protect_int (builtin_ignoring_errexit);
4739 error_trap = TRAP_STRING (ERROR_TRAP);
4740 if (error_trap)
4741 {
4742 error_trap = savestring (error_trap);
4743 add_unwind_protect (xfree, error_trap);
4744 add_unwind_protect (set_error_trap, error_trap);
4745 restore_default_signal (ERROR_TRAP);
4746 }
4747 exit_immediately_on_error = 0;
4748 ignexit_flag = builtin_ignoring_errexit;
4749 builtin_ignoring_errexit = 1;
4750 eval_unwind = 1;
4751 }
4752 else
4753 eval_unwind = 0;
4754
4755 /* The temporary environment for a builtin is supposed to apply to
4756 all commands executed by that builtin. Currently, this is a
4757 problem only with the `unset', `source' and `eval' builtins.
4758 `mapfile' is a special case because it uses evalstring (same as
4759 eval or source) to run its callbacks. */
4760 /* SHOULD_KEEP is for the pop_scope call below; it only matters when
4761 posixly_correct is set, but we should propagate the temporary environment
4762 to the enclosing environment only for special builtins. */
4763 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin || builtin == mapfile_builtin);
4764 should_keep = isbltinenv && builtin != mapfile_builtin;
4765 #if defined (HISTORY) && defined (READLINE)
4766 if (builtin == fc_builtin || builtin == read_builtin)
4767 {
4768 isbltinenv = 1;
4769 should_keep = 0;
4770 }
4771 #endif
4772
4773 if (isbltinenv)
4774 {
4775 if (subshell == 0)
4776 begin_unwind_frame ("builtin_env");
4777
4778 if (temporary_env)
4779 {
4780 push_scope (VC_BLTNENV, temporary_env);
4781 if (flags & CMD_COMMAND_BUILTIN)
4782 should_keep = 0;
4783 if (subshell == 0)
4784 add_unwind_protect (pop_scope, should_keep ? "1" : 0);
4785 temporary_env = (HASH_TABLE *)NULL;
4786 }
4787 }
4788
4789 if (subshell == 0 && builtin == eval_builtin)
4790 {
4791 if (evalnest_max > 0 && evalnest >= evalnest_max)
4792 {
4793 internal_error (_("eval: maximum eval nesting level exceeded (%d)"), evalnest);
4794 evalnest = 0;
4795 jump_to_top_level (DISCARD);
4796 }
4797 unwind_protect_int (evalnest);
4798 /* The test for subshell == 0 above doesn't make a difference */
4799 evalnest++; /* execute_subshell_builtin_or_function sets this to 0 */
4800 }
4801 else if (subshell == 0 && builtin == source_builtin)
4802 {
4803 if (sourcenest_max > 0 && sourcenest >= sourcenest_max)
4804 {
4805 internal_error (_("%s: maximum source nesting level exceeded (%d)"), this_command_name, sourcenest);
4806 sourcenest = 0;
4807 jump_to_top_level (DISCARD);
4808 }
4809 unwind_protect_int (sourcenest);
4810 /* The test for subshell == 0 above doesn't make a difference */
4811 sourcenest++; /* execute_subshell_builtin_or_function sets this to 0 */
4812 }
4813
4814 /* `return' does a longjmp() back to a saved environment in execute_function.
4815 If a variable assignment list preceded the command, and the shell is
4816 running in POSIX mode, we need to merge that into the shell_variables
4817 table, since `return' is a POSIX special builtin. We don't do this if
4818 it's being run by the `command' builtin, since that's supposed to inhibit
4819 the special builtin properties. */
4820 if (posixly_correct && subshell == 0 && builtin == return_builtin && (flags & CMD_COMMAND_BUILTIN) == 0 && temporary_env)
4821 {
4822 begin_unwind_frame ("return_temp_env");
4823 add_unwind_protect (merge_temporary_env, (char *)NULL);
4824 }
4825
4826 executing_builtin++;
4827 executing_command_builtin |= builtin == command_builtin;
4828 result = ((*builtin) (words->next));
4829
4830 /* This shouldn't happen, but in case `return' comes back instead of
4831 longjmp'ing, we need to unwind. */
4832 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4833 discard_unwind_frame ("return_temp_env");
4834
4835 if (subshell == 0 && isbltinenv)
4836 run_unwind_frame ("builtin_env");
4837
4838 if (eval_unwind)
4839 {
4840 builtin_ignoring_errexit = ignexit_flag;
4841 exit_immediately_on_error = builtin_ignoring_errexit ? 0 : errexit_flag;
4842 if (error_trap)
4843 {
4844 set_error_trap (error_trap);
4845 free (error_trap);
4846 }
4847 discard_unwind_frame ("eval_builtin");
4848 }
4849
4850 return (result);
4851 }
4852
4853 static void
4854 maybe_restore_getopt_state (gs)
4855 sh_getopt_state_t *gs;
4856 {
4857 /* If we have a local copy of OPTIND and it's at the right (current)
4858 context, then we restore getopt's internal state. If not, we just
4859 let it go. We know there is a local OPTIND if gs->gs_flags & 1.
4860 This is set below in execute_function() before the context is run. */
4861 if (gs->gs_flags & 1)
4862 sh_getopt_restore_istate (gs);
4863 else
4864 free (gs);
4865 }
4866
4867 #if defined (ARRAY_VARS)
4868 void
4869 restore_funcarray_state (fa)
4870 struct func_array_state *fa;
4871 {
4872 SHELL_VAR *nfv;
4873 ARRAY *funcname_a;
4874
4875 array_pop (fa->source_a);
4876 array_pop (fa->lineno_a);
4877
4878 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4879 if (nfv == fa->funcname_v)
4880 array_pop (funcname_a);
4881
4882 free (fa);
4883 }
4884 #endif
4885
4886 static int
4887 execute_function (var, words, flags, fds_to_close, async, subshell)
4888 SHELL_VAR *var;
4889 WORD_LIST *words;
4890 int flags;
4891 struct fd_bitmap *fds_to_close;
4892 int async, subshell;
4893 {
4894 int return_val, result;
4895 COMMAND *tc, *fc, *save_current;
4896 char *debug_trap, *error_trap, *return_trap;
4897 #if defined (ARRAY_VARS)
4898 SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
4899 ARRAY *funcname_a;
4900 volatile ARRAY *bash_source_a;
4901 volatile ARRAY *bash_lineno_a;
4902 struct func_array_state *fa;
4903 #endif
4904 FUNCTION_DEF *shell_fn;
4905 char *sfile, *t;
4906 sh_getopt_state_t *gs;
4907 SHELL_VAR *gv;
4908
4909 USE_VAR(fc);
4910
4911 if (funcnest_max > 0 && funcnest >= funcnest_max)
4912 {
4913 internal_error (_("%s: maximum function nesting level exceeded (%d)"), var->name, funcnest);
4914 funcnest = 0; /* XXX - should we reset it somewhere else? */
4915 jump_to_top_level (DISCARD);
4916 }
4917
4918 #if defined (ARRAY_VARS)
4919 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4920 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4921 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4922 #endif
4923
4924 tc = (COMMAND *)copy_command (function_cell (var));
4925 if (tc && (flags & CMD_IGNORE_RETURN))
4926 tc->flags |= CMD_IGNORE_RETURN;
4927
4928 /* A limited attempt at optimization: shell functions at the end of command
4929 substitutions that are already marked NO_FORK. */
4930 if (tc && (flags & CMD_NO_FORK) && (subshell_environment & SUBSHELL_COMSUB))
4931 optimize_shell_function (tc);
4932
4933 gs = sh_getopt_save_istate ();
4934 if (subshell == 0)
4935 {
4936 begin_unwind_frame ("function_calling");
4937 /* If the shell is in posix mode, this will push the variables in
4938 the temporary environment to the "current shell environment" (the
4939 global scope), and dispose the temporary env before setting it to
4940 NULL later. This behavior has disappeared from the latest edition
4941 of the standard, so I will eventually remove it from variables.c:
4942 push_var_context. */
4943 push_context (var->name, subshell, temporary_env);
4944 /* This has to be before the pop_context(), because the unwinding of
4945 local variables may cause the restore of a local declaration of
4946 OPTIND to force a getopts state reset. */
4947 add_unwind_protect (maybe_restore_getopt_state, gs);
4948 add_unwind_protect (pop_context, (char *)NULL);
4949 unwind_protect_int (line_number);
4950 unwind_protect_int (line_number_for_err_trap);
4951 unwind_protect_int (function_line_number);
4952 unwind_protect_int (return_catch_flag);
4953 unwind_protect_jmp_buf (return_catch);
4954 add_unwind_protect (dispose_command, (char *)tc);
4955 unwind_protect_pointer (this_shell_function);
4956 unwind_protect_int (funcnest);
4957 unwind_protect_int (loop_level);
4958 }
4959 else
4960 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4961
4962 temporary_env = (HASH_TABLE *)NULL;
4963
4964 this_shell_function = var;
4965 make_funcname_visible (1);
4966
4967 debug_trap = TRAP_STRING(DEBUG_TRAP);
4968 error_trap = TRAP_STRING(ERROR_TRAP);
4969 return_trap = TRAP_STRING(RETURN_TRAP);
4970
4971 /* The order of the unwind protects for debug_trap, error_trap and
4972 return_trap is important here! unwind-protect commands are run
4973 in reverse order of registration. If this causes problems, take
4974 out the xfree unwind-protect calls and live with the small memory leak. */
4975
4976 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4977 if the function has the trace attribute set, it inherits the DEBUG trap */
4978 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
4979 {
4980 if (subshell == 0)
4981 {
4982 debug_trap = savestring (debug_trap);
4983 add_unwind_protect (xfree, debug_trap);
4984 add_unwind_protect (maybe_set_debug_trap, debug_trap);
4985 }
4986 restore_default_signal (DEBUG_TRAP);
4987 }
4988
4989 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4990 if (error_trap && error_trace_mode == 0)
4991 {
4992 if (subshell == 0)
4993 {
4994 error_trap = savestring (error_trap);
4995 add_unwind_protect (xfree, error_trap);
4996 add_unwind_protect (maybe_set_error_trap, error_trap);
4997 }
4998 restore_default_signal (ERROR_TRAP);
4999 }
5000
5001 /* Shell functions inherit the RETURN trap if function tracing is on
5002 globally or on individually for this function. */
5003 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
5004 {
5005 if (subshell == 0)
5006 {
5007 return_trap = savestring (return_trap);
5008 add_unwind_protect (xfree, return_trap);
5009 add_unwind_protect (maybe_set_return_trap, return_trap);
5010 }
5011 restore_default_signal (RETURN_TRAP);
5012 }
5013
5014 funcnest++;
5015 #if defined (ARRAY_VARS)
5016 /* This is quite similar to the code in shell.c and elsewhere. */
5017 shell_fn = find_function_def (this_shell_function->name);
5018 sfile = shell_fn ? shell_fn->source_file : "";
5019 array_push ((ARRAY *)funcname_a, this_shell_function->name);
5020
5021 array_push ((ARRAY *)bash_source_a, sfile);
5022 t = itos (executing_line_number ());
5023 array_push ((ARRAY *)bash_lineno_a, t);
5024 free (t);
5025 #endif
5026
5027 #if defined (ARRAY_VARS)
5028 fa = (struct func_array_state *)xmalloc (sizeof (struct func_array_state));
5029 fa->source_a = (ARRAY *)bash_source_a;
5030 fa->source_v = bash_source_v;
5031 fa->lineno_a = (ARRAY *)bash_lineno_a;
5032 fa->lineno_v = bash_lineno_v;
5033 fa->funcname_a = (ARRAY *)funcname_a;
5034 fa->funcname_v = funcname_v;
5035 if (subshell == 0)
5036 add_unwind_protect (restore_funcarray_state, fa);
5037 #endif
5038
5039 /* The temporary environment for a function is supposed to apply to
5040 all commands executed within the function body. */
5041
5042 /* Initialize BASH_ARGC and BASH_ARGV before we blow away the positional
5043 parameters */
5044 if (debugging_mode || shell_compatibility_level <= 44)
5045 init_bash_argv ();
5046
5047 remember_args (words->next, 1);
5048
5049 /* Update BASH_ARGV and BASH_ARGC */
5050 if (debugging_mode)
5051 {
5052 push_args (words->next);
5053 if (subshell == 0)
5054 add_unwind_protect (pop_args, 0);
5055 }
5056
5057 /* Number of the line on which the function body starts. */
5058 line_number = function_line_number = tc->line;
5059
5060 #if defined (JOB_CONTROL)
5061 if (subshell)
5062 stop_pipeline (async, (COMMAND *)NULL);
5063 #endif
5064
5065 if (shell_compatibility_level > 43)
5066 loop_level = 0;
5067
5068 fc = tc;
5069
5070 from_return_trap = 0;
5071
5072 return_catch_flag++;
5073 return_val = setjmp_nosigs (return_catch);
5074
5075 if (return_val)
5076 {
5077 result = return_catch_value;
5078 /* Run the RETURN trap in the function's context. */
5079 save_current = currently_executing_command;
5080 if (from_return_trap == 0)
5081 run_return_trap ();
5082 currently_executing_command = save_current;
5083 }
5084 else
5085 {
5086 /* Run the debug trap here so we can trap at the start of a function's
5087 execution rather than the execution of the body's first command. */
5088 showing_function_line = 1;
5089 save_current = currently_executing_command;
5090 result = run_debug_trap ();
5091 #if defined (DEBUGGER)
5092 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
5093 skip the command. */
5094 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
5095 {
5096 showing_function_line = 0;
5097 currently_executing_command = save_current;
5098 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
5099
5100 /* Run the RETURN trap in the function's context */
5101 save_current = currently_executing_command;
5102 run_return_trap ();
5103 currently_executing_command = save_current;
5104 }
5105 #else
5106 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
5107
5108 save_current = currently_executing_command;
5109 run_return_trap ();
5110 currently_executing_command = save_current;
5111 #endif
5112 showing_function_line = 0;
5113 }
5114
5115 /* If we have a local copy of OPTIND, note it in the saved getopts state. */
5116 gv = find_variable ("OPTIND");
5117 if (gv && gv->context == variable_context)
5118 gs->gs_flags |= 1;
5119
5120 if (subshell == 0)
5121 run_unwind_frame ("function_calling");
5122 #if defined (ARRAY_VARS)
5123 else
5124 {
5125 restore_funcarray_state (fa);
5126 /* Restore BASH_ARGC and BASH_ARGV */
5127 if (debugging_mode)
5128 pop_args ();
5129 }
5130 #endif
5131
5132 if (variable_context == 0 || this_shell_function == 0)
5133 {
5134 make_funcname_visible (0);
5135 #if defined (PROCESS_SUBSTITUTION)
5136 unlink_fifo_list ();
5137 #endif
5138 }
5139
5140 return (result);
5141 }
5142
5143 /* A convenience routine for use by other parts of the shell to execute
5144 a particular shell function. */
5145 int
5146 execute_shell_function (var, words)
5147 SHELL_VAR *var;
5148 WORD_LIST *words;
5149 {
5150 int ret;
5151 struct fd_bitmap *bitmap;
5152
5153 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
5154 begin_unwind_frame ("execute-shell-function");
5155 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
5156
5157 ret = execute_function (var, words, 0, bitmap, 0, 0);
5158
5159 dispose_fd_bitmap (bitmap);
5160 discard_unwind_frame ("execute-shell-function");
5161
5162 return ret;
5163 }
5164
5165 /* Execute a shell builtin or function in a subshell environment. This
5166 routine does not return; it only calls exit(). If BUILTIN is non-null,
5167 it points to a function to call to execute a shell builtin; otherwise
5168 VAR points at the body of a function to execute. WORDS is the arguments
5169 to the command, REDIRECTS specifies redirections to perform before the
5170 command is executed. */
5171 static void
5172 execute_subshell_builtin_or_function (words, redirects, builtin, var,
5173 pipe_in, pipe_out, async, fds_to_close,
5174 flags)
5175 WORD_LIST *words;
5176 REDIRECT *redirects;
5177 sh_builtin_func_t *builtin;
5178 SHELL_VAR *var;
5179 int pipe_in, pipe_out, async;
5180 struct fd_bitmap *fds_to_close;
5181 int flags;
5182 {
5183 int result, r, funcvalue;
5184 #if defined (JOB_CONTROL)
5185 int jobs_hack;
5186
5187 jobs_hack = (builtin == jobs_builtin) &&
5188 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
5189 #endif
5190
5191 /* A subshell is neither a login shell nor interactive. */
5192 login_shell = interactive = 0;
5193 if (builtin == eval_builtin)
5194 evalnest = 0;
5195 else if (builtin == source_builtin)
5196 sourcenest = 0;
5197
5198 if (async)
5199 subshell_environment |= SUBSHELL_ASYNC;
5200 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
5201 subshell_environment |= SUBSHELL_PIPE;
5202
5203 maybe_make_export_env (); /* XXX - is this needed? */
5204
5205 #if defined (JOB_CONTROL)
5206 /* Eradicate all traces of job control after we fork the subshell, so
5207 all jobs begun by this subshell are in the same process group as
5208 the shell itself. */
5209
5210 /* Allow the output of `jobs' to be piped. */
5211 if (jobs_hack)
5212 kill_current_pipeline ();
5213 else
5214 without_job_control ();
5215
5216 set_sigchld_handler ();
5217 #else
5218 without_job_control ();
5219 #endif /* JOB_CONTROL */
5220
5221 set_sigint_handler ();
5222
5223 if (fds_to_close)
5224 close_fd_bitmap (fds_to_close);
5225
5226 do_piping (pipe_in, pipe_out);
5227
5228 if (do_redirections (redirects, RX_ACTIVE) != 0)
5229 exit (EXECUTION_FAILURE);
5230
5231 if (builtin)
5232 {
5233 /* Give builtins a place to jump back to on failure,
5234 so we don't go back up to main(). */
5235 result = setjmp_nosigs (top_level);
5236
5237 /* Give the return builtin a place to jump to when executed in a subshell
5238 or pipeline */
5239 funcvalue = 0;
5240 if (return_catch_flag && builtin == return_builtin)
5241 funcvalue = setjmp_nosigs (return_catch);
5242
5243 if (result == EXITPROG)
5244 subshell_exit (last_command_exit_value);
5245 else if (result)
5246 subshell_exit (EXECUTION_FAILURE);
5247 else if (funcvalue)
5248 subshell_exit (return_catch_value);
5249 else
5250 {
5251 r = execute_builtin (builtin, words, flags, 1);
5252 fflush (stdout);
5253 if (r == EX_USAGE)
5254 r = EX_BADUSAGE;
5255 /* XXX - experimental */
5256 else if (r == EX_DISKFALLBACK)
5257 {
5258 char *command_line;
5259
5260 command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
5261 r = execute_disk_command (words, (REDIRECT *)0, command_line,
5262 -1, -1, async, (struct fd_bitmap *)0, flags|CMD_NO_FORK);
5263 }
5264 subshell_exit (r);
5265 }
5266 }
5267 else
5268 {
5269 r = execute_function (var, words, flags, fds_to_close, async, 1);
5270 fflush (stdout);
5271 subshell_exit (r);
5272 }
5273 }
5274
5275 /* Execute a builtin or function in the current shell context. If BUILTIN
5276 is non-null, it is the builtin command to execute, otherwise VAR points
5277 to the body of a function. WORDS are the command's arguments, REDIRECTS
5278 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
5279 file descriptors to close.
5280
5281 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
5282 not undone before this function returns. */
5283 static int
5284 execute_builtin_or_function (words, builtin, var, redirects,
5285 fds_to_close, flags)
5286 WORD_LIST *words;
5287 sh_builtin_func_t *builtin;
5288 SHELL_VAR *var;
5289 REDIRECT *redirects;
5290 struct fd_bitmap *fds_to_close;
5291 int flags;
5292 {
5293 int result;
5294 REDIRECT *saved_undo_list;
5295 #if defined (PROCESS_SUBSTITUTION)
5296 int ofifo, nfifo, osize;
5297 void *ofifo_list;
5298 #endif
5299
5300 #if defined (PROCESS_SUBSTITUTION)
5301 begin_unwind_frame ("saved_fifos");
5302 /* If we return, we longjmp and don't get a chance to restore the old
5303 fifo list, so we add an unwind protect to free it */
5304 ofifo = num_fifos ();
5305 ofifo_list = copy_fifo_list (&osize);
5306 if (ofifo_list)
5307 add_unwind_protect (xfree, ofifo_list);
5308 #endif
5309
5310 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
5311 {
5312 undo_partial_redirects ();
5313 dispose_exec_redirects ();
5314 #if defined (PROCESS_SUBSTITUTION)
5315 free (ofifo_list);
5316 #endif
5317 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
5318 }
5319
5320 saved_undo_list = redirection_undo_list;
5321
5322 /* Calling the "exec" builtin changes redirections forever. */
5323 if (builtin == exec_builtin)
5324 {
5325 dispose_redirects (saved_undo_list);
5326 saved_undo_list = exec_redirection_undo_list;
5327 exec_redirection_undo_list = (REDIRECT *)NULL;
5328 }
5329 else
5330 dispose_exec_redirects ();
5331
5332 if (saved_undo_list)
5333 {
5334 begin_unwind_frame ("saved-redirects");
5335 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
5336 }
5337
5338 redirection_undo_list = (REDIRECT *)NULL;
5339
5340 if (builtin)
5341 result = execute_builtin (builtin, words, flags, 0);
5342 else
5343 result = execute_function (var, words, flags, fds_to_close, 0, 0);
5344
5345 /* We do this before undoing the effects of any redirections. */
5346 fflush (stdout);
5347 fpurge (stdout);
5348 if (ferror (stdout))
5349 clearerr (stdout);
5350
5351 /* If we are executing the `command' builtin, but this_shell_builtin is
5352 set to `exec_builtin', we know that we have something like
5353 `command exec [redirection]', since otherwise `exec' would have
5354 overwritten the shell and we wouldn't get here. In this case, we
5355 want to behave as if the `command' builtin had not been specified
5356 and preserve the redirections. */
5357 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
5358 {
5359 int discard;
5360
5361 discard = 0;
5362 if (saved_undo_list)
5363 {
5364 dispose_redirects (saved_undo_list);
5365 discard = 1;
5366 }
5367 redirection_undo_list = exec_redirection_undo_list;
5368 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
5369 if (discard)
5370 discard_unwind_frame ("saved-redirects");
5371 }
5372
5373 if (saved_undo_list)
5374 {
5375 redirection_undo_list = saved_undo_list;
5376 discard_unwind_frame ("saved-redirects");
5377 }
5378
5379 undo_partial_redirects ();
5380
5381 #if defined (PROCESS_SUBSTITUTION)
5382 /* Close any FIFOs created by this builtin or function. */
5383 nfifo = num_fifos ();
5384 if (nfifo > ofifo)
5385 close_new_fifos (ofifo_list, osize);
5386 if (ofifo_list)
5387 free (ofifo_list);
5388 discard_unwind_frame ("saved_fifos");
5389 #endif
5390
5391 return (result);
5392 }
5393
5394 void
5395 setup_async_signals ()
5396 {
5397 #if defined (__BEOS__)
5398 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
5399 #endif
5400
5401 #if defined (JOB_CONTROL)
5402 if (job_control == 0)
5403 #endif
5404 {
5405 /* Make sure we get the original signal dispositions now so we don't
5406 confuse the trap builtin later if the subshell tries to use it to
5407 reset SIGINT/SIGQUIT. Don't call set_signal_ignored; that sets
5408 the value of original_signals to SIG_IGN. Posix interpretation 751. */
5409 get_original_signal (SIGINT);
5410 set_signal_handler (SIGINT, SIG_IGN);
5411
5412 get_original_signal (SIGQUIT);
5413 set_signal_handler (SIGQUIT, SIG_IGN);
5414 }
5415 }
5416
5417 /* Execute a simple command that is hopefully defined in a disk file
5418 somewhere.
5419
5420 1) fork ()
5421 2) connect pipes
5422 3) look up the command
5423 4) do redirections
5424 5) execve ()
5425 6) If the execve failed, see if the file has executable mode set.
5426 If so, and it isn't a directory, then execute its contents as
5427 a shell script.
5428
5429 Note that the filename hashing stuff has to take place up here,
5430 in the parent. This is probably why the Bourne style shells
5431 don't handle it, since that would require them to go through
5432 this gnarly hair, for no good reason.
5433
5434 NOTE: callers expect this to fork or exit(). */
5435
5436 /* Name of a shell function to call when a command name is not found. */
5437 #ifndef NOTFOUND_HOOK
5438 # define NOTFOUND_HOOK "command_not_found_handle"
5439 #endif
5440
5441 static int
5442 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
5443 async, fds_to_close, cmdflags)
5444 WORD_LIST *words;
5445 REDIRECT *redirects;
5446 char *command_line;
5447 int pipe_in, pipe_out, async;
5448 struct fd_bitmap *fds_to_close;
5449 int cmdflags;
5450 {
5451 char *pathname, *command, **args, *p;
5452 int nofork, stdpath, result, fork_flags;
5453 pid_t pid;
5454 SHELL_VAR *hookf;
5455 WORD_LIST *wl;
5456
5457 stdpath = (cmdflags & CMD_STDPATH); /* use command -p path */
5458 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
5459 pathname = words->word->word;
5460
5461 p = 0;
5462 result = EXECUTION_SUCCESS;
5463 #if defined (RESTRICTED_SHELL)
5464 command = (char *)NULL;
5465 if (restricted && mbschr (pathname, '/'))
5466 {
5467 internal_error (_("%s: restricted: cannot specify `/' in command names"),
5468 pathname);
5469 result = last_command_exit_value = EXECUTION_FAILURE;
5470
5471 /* If we're not going to fork below, we must already be in a child
5472 process or a context in which it's safe to call exit(2). */
5473 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5474 exit (last_command_exit_value);
5475 else
5476 goto parent_return;
5477 }
5478 #endif /* RESTRICTED_SHELL */
5479
5480 command = search_for_command (pathname, CMDSRCH_HASH|(stdpath ? CMDSRCH_STDPATH : 0));
5481 QUIT;
5482
5483 if (command)
5484 {
5485 /* If we're optimizing out the fork (implicit `exec'), decrement the
5486 shell level like `exec' would do. */
5487 #if 0 /* TAG: bash-5.2 psmith 10/11/2020 */
5488 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE && (subshell_environment & SUBSHELL_PIPE) == 0)
5489 #else
5490 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5491 #endif
5492 adjust_shell_level (-1);
5493
5494 maybe_make_export_env ();
5495 put_command_name_into_env (command);
5496 }
5497
5498 /* We have to make the child before we check for the non-existence
5499 of COMMAND, since we want the error messages to be redirected. */
5500 /* If we can get away without forking and there are no pipes to deal with,
5501 don't bother to fork, just directly exec the command. */
5502 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5503 pid = 0;
5504 else
5505 {
5506 fork_flags = async ? FORK_ASYNC : 0;
5507 pid = make_child (p = savestring (command_line), fork_flags);
5508 }
5509
5510 if (pid == 0)
5511 {
5512 int old_interactive;
5513
5514 reset_terminating_signals (); /* XXX */
5515 /* Cancel traps, in trap.c. */
5516 restore_original_signals ();
5517
5518 #if defined (JOB_CONTROL)
5519 FREE (p);
5520 #endif
5521
5522 /* restore_original_signals may have undone the work done
5523 by make_child to ensure that SIGINT and SIGQUIT are ignored
5524 in asynchronous children. */
5525 if (async)
5526 {
5527 if ((cmdflags & CMD_STDIN_REDIR) &&
5528 pipe_in == NO_PIPE &&
5529 (stdin_redirects (redirects) == 0))
5530 async_redirect_stdin ();
5531 setup_async_signals ();
5532 }
5533
5534 /* This functionality is now provided by close-on-exec of the
5535 file descriptors manipulated by redirection and piping.
5536 Some file descriptors still need to be closed in all children
5537 because of the way bash does pipes; fds_to_close is a
5538 bitmap of all such file descriptors. */
5539 if (fds_to_close)
5540 close_fd_bitmap (fds_to_close);
5541
5542 do_piping (pipe_in, pipe_out);
5543
5544 old_interactive = interactive;
5545 if (async)
5546 interactive = 0;
5547
5548 subshell_environment |= SUBSHELL_FORK; /* XXX - was just = */
5549
5550 #if defined (PROCESS_SUBSTITUTION) && !defined (HAVE_DEV_FD)
5551 clear_fifo_list (); /* XXX - we haven't created any FIFOs */
5552 #endif
5553
5554 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
5555 {
5556 #if defined (PROCESS_SUBSTITUTION)
5557 /* Try to remove named pipes that may have been created as the
5558 result of redirections. */
5559 unlink_fifo_list ();
5560 #endif /* PROCESS_SUBSTITUTION */
5561 exit (EXECUTION_FAILURE);
5562 }
5563
5564 if (async)
5565 interactive = old_interactive;
5566
5567 if (command == 0)
5568 {
5569 hookf = find_function (NOTFOUND_HOOK);
5570 if (hookf == 0)
5571 {
5572 /* Make sure filenames are displayed using printable characters */
5573 pathname = printable_filename (pathname, 0);
5574 internal_error (_("%s: command not found"), pathname);
5575 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
5576 }
5577
5578 /* We don't want to manage process groups for processes we start
5579 from here, so we turn off job control and don't attempt to
5580 manipulate the terminal's process group. */
5581 without_job_control ();
5582
5583 #if defined (JOB_CONTROL)
5584 set_sigchld_handler ();
5585 #endif
5586
5587 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
5588 exit (execute_shell_function (hookf, wl));
5589 }
5590
5591 /* Execve expects the command name to be in args[0]. So we
5592 leave it there, in the same format that the user used to
5593 type it in. */
5594 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
5595 exit (shell_execve (command, args, export_env));
5596 }
5597 else
5598 {
5599 parent_return:
5600 QUIT;
5601
5602 /* Make sure that the pipes are closed in the parent. */
5603 close_pipes (pipe_in, pipe_out);
5604 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5605 #if 0
5606 if (variable_context == 0)
5607 unlink_fifo_list ();
5608 #endif
5609 #endif
5610 FREE (command);
5611 return (result);
5612 }
5613 }
5614
5615 /* CPP defines to decide whether a particular index into the #! line
5616 corresponds to a valid interpreter name or argument character, or
5617 whitespace. The MSDOS define is to allow \r to be treated the same
5618 as \n. */
5619
5620 #if !defined (MSDOS)
5621 # define STRINGCHAR(ind) \
5622 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
5623 # define WHITECHAR(ind) \
5624 (ind < sample_len && whitespace (sample[ind]))
5625 #else /* MSDOS */
5626 # define STRINGCHAR(ind) \
5627 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
5628 # define WHITECHAR(ind) \
5629 (ind < sample_len && whitespace (sample[ind]))
5630 #endif /* MSDOS */
5631
5632 static char *
5633 getinterp (sample, sample_len, endp)
5634 char *sample;
5635 int sample_len, *endp;
5636 {
5637 register int i;
5638 char *execname;
5639 int start;
5640
5641 /* Find the name of the interpreter to exec. */
5642 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
5643 ;
5644
5645 for (start = i; STRINGCHAR(i); i++)
5646 ;
5647
5648 execname = substring (sample, start, i);
5649
5650 if (endp)
5651 *endp = i;
5652 return execname;
5653 }
5654
5655 #if !defined (HAVE_HASH_BANG_EXEC)
5656 /* If the operating system on which we're running does not handle
5657 the #! executable format, then help out. SAMPLE is the text read
5658 from the file, SAMPLE_LEN characters. COMMAND is the name of
5659 the script; it and ARGS, the arguments given by the user, will
5660 become arguments to the specified interpreter. ENV is the environment
5661 to pass to the interpreter.
5662
5663 The word immediately following the #! is the interpreter to execute.
5664 A single argument to the interpreter is allowed. */
5665
5666 static int
5667 execute_shell_script (sample, sample_len, command, args, env)
5668 char *sample;
5669 int sample_len;
5670 char *command;
5671 char **args, **env;
5672 {
5673 char *execname, *firstarg;
5674 int i, start, size_increment, larry;
5675
5676 /* Find the name of the interpreter to exec. */
5677 execname = getinterp (sample, sample_len, &i);
5678 size_increment = 1;
5679
5680 /* Now the argument, if any. */
5681 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
5682 ;
5683
5684 /* If there is more text on the line, then it is an argument for the
5685 interpreter. */
5686
5687 if (STRINGCHAR(i))
5688 {
5689 for (start = i; STRINGCHAR(i); i++)
5690 ;
5691 firstarg = substring ((char *)sample, start, i);
5692 size_increment = 2;
5693 }
5694
5695 larry = strvec_len (args) + size_increment;
5696 args = strvec_resize (args, larry + 1);
5697
5698 for (i = larry - 1; i; i--)
5699 args[i] = args[i - size_increment];
5700
5701 args[0] = execname;
5702 if (firstarg)
5703 {
5704 args[1] = firstarg;
5705 args[2] = command;
5706 }
5707 else
5708 args[1] = command;
5709
5710 args[larry] = (char *)NULL;
5711
5712 return (shell_execve (execname, args, env));
5713 }
5714 #undef STRINGCHAR
5715 #undef WHITECHAR
5716
5717 #endif /* !HAVE_HASH_BANG_EXEC */
5718
5719 static void
5720 initialize_subshell ()
5721 {
5722 #if defined (ALIAS)
5723 /* Forget about any aliases that we knew of. We are in a subshell. */
5724 delete_all_aliases ();
5725 #endif /* ALIAS */
5726
5727 #if defined (HISTORY)
5728 /* Forget about the history lines we have read. This is a non-interactive
5729 subshell. */
5730 history_lines_this_session = 0;
5731 #endif
5732
5733 /* Forget about the way job control was working. We are in a subshell. */
5734 without_job_control ();
5735
5736 #if defined (JOB_CONTROL)
5737 set_sigchld_handler ();
5738 init_job_stats ();
5739 #endif /* JOB_CONTROL */
5740
5741 /* Reset the values of the shell flags and options. */
5742 reset_shell_flags ();
5743 reset_shell_options ();
5744 reset_shopt_options ();
5745
5746 /* Zero out builtin_env, since this could be a shell script run from a
5747 sourced file with a temporary environment supplied to the `source/.'
5748 builtin. Such variables are not supposed to be exported (empirical
5749 testing with sh and ksh). Just throw it away; don't worry about a
5750 memory leak. */
5751 if (vc_isbltnenv (shell_variables))
5752 shell_variables = shell_variables->down;
5753
5754 clear_unwind_protect_list (0);
5755 /* XXX -- are there other things we should be resetting here? */
5756 parse_and_execute_level = 0; /* nothing left to restore it */
5757
5758 /* We're no longer inside a shell function. */
5759 variable_context = return_catch_flag = funcnest = evalnest = sourcenest = 0;
5760
5761 executing_list = 0; /* XXX */
5762
5763 /* If we're not interactive, close the file descriptor from which we're
5764 reading the current shell script. */
5765 if (interactive_shell == 0)
5766 unset_bash_input (0);
5767 }
5768
5769 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5770 # define SETOSTYPE(x) __setostype(x)
5771 #else
5772 # define SETOSTYPE(x)
5773 #endif
5774
5775 #define HASH_BANG_BUFSIZ 128
5776
5777 #define READ_SAMPLE_BUF(file, buf, len) \
5778 do \
5779 { \
5780 fd = open(file, O_RDONLY); \
5781 if (fd >= 0) \
5782 { \
5783 len = read (fd, buf, HASH_BANG_BUFSIZ); \
5784 close (fd); \
5785 } \
5786 else \
5787 len = -1; \
5788 } \
5789 while (0)
5790
5791 /* Call execve (), handling interpreting shell scripts, and handling
5792 exec failures. */
5793 int
5794 shell_execve (command, args, env)
5795 char *command;
5796 char **args, **env;
5797 {
5798 int larray, i, fd;
5799 char sample[HASH_BANG_BUFSIZ];
5800 int sample_len;
5801
5802 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
5803 execve (command, args, env);
5804 i = errno; /* error from execve() */
5805 CHECK_TERMSIG;
5806 SETOSTYPE (1);
5807
5808 /* If we get to this point, then start checking out the file.
5809 Maybe it is something we can hack ourselves. */
5810 if (i != ENOEXEC)
5811 {
5812 /* make sure this is set correctly for file_error/report_error */
5813 last_command_exit_value = (i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC; /* XXX Posix.2 says that exit status is 126 */
5814 if (file_isdir (command))
5815 #if defined (EISDIR)
5816 internal_error (_("%s: %s"), command, strerror (EISDIR));
5817 #else
5818 internal_error (_("%s: is a directory"), command);
5819 #endif
5820 else if (executable_file (command) == 0)
5821 {
5822 errno = i;
5823 file_error (command);
5824 }
5825 /* errors not involving the path argument to execve. */
5826 else if (i == E2BIG || i == ENOMEM)
5827 {
5828 errno = i;
5829 file_error (command);
5830 }
5831 else
5832 {
5833 /* The file has the execute bits set, but the kernel refuses to
5834 run it for some reason. See why. */
5835 #if defined (HAVE_HASH_BANG_EXEC)
5836 READ_SAMPLE_BUF (command, sample, sample_len);
5837 if (sample_len > 0)
5838 sample[sample_len - 1] = '\0';
5839 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5840 {
5841 char *interp;
5842 int ilen;
5843
5844 interp = getinterp (sample, sample_len, (int *)NULL);
5845 ilen = strlen (interp);
5846 errno = i;
5847 if (interp[ilen - 1] == '\r')
5848 {
5849 interp = xrealloc (interp, ilen + 2);
5850 interp[ilen - 1] = '^';
5851 interp[ilen] = 'M';
5852 interp[ilen + 1] = '\0';
5853 }
5854 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
5855 FREE (interp);
5856 return (EX_NOEXEC);
5857 }
5858 #endif
5859 errno = i;
5860 file_error (command);
5861 }
5862 return (last_command_exit_value);
5863 }
5864
5865 /* This file is executable.
5866 If it begins with #!, then help out people with losing operating
5867 systems. Otherwise, check to see if it is a binary file by seeing
5868 if the contents of the first line (or up to 80 characters) are in the
5869 ASCII set. If it's a text file, execute the contents as shell commands,
5870 otherwise return 126 (EX_BINARY_FILE). */
5871 READ_SAMPLE_BUF (command, sample, sample_len);
5872
5873 if (sample_len == 0)
5874 return (EXECUTION_SUCCESS);
5875
5876 /* Is this supposed to be an executable script?
5877 If so, the format of the line is "#! interpreter [argument]".
5878 A single argument is allowed. The BSD kernel restricts
5879 the length of the entire line to 32 characters (32 bytes
5880 being the size of the BSD exec header), but we allow 80
5881 characters. */
5882 if (sample_len > 0)
5883 {
5884 #if !defined (HAVE_HASH_BANG_EXEC)
5885 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5886 return (execute_shell_script (sample, sample_len, command, args, env));
5887 else
5888 #endif
5889 if (check_binary_file (sample, sample_len))
5890 {
5891 internal_error (_("%s: cannot execute binary file: %s"), command, strerror (i));
5892 errno = i;
5893 return (EX_BINARY_FILE);
5894 }
5895 }
5896
5897 /* We have committed to attempting to execute the contents of this file
5898 as shell commands. */
5899
5900 reset_parser ();
5901 initialize_subshell ();
5902
5903 set_sigint_handler ();
5904
5905 /* Insert the name of this shell into the argument list. */
5906 larray = strvec_len (args) + 1;
5907 args = strvec_resize (args, larray + 1);
5908
5909 for (i = larray - 1; i; i--)
5910 args[i] = args[i - 1];
5911
5912 args[0] = shell_name;
5913 args[1] = command;
5914 args[larray] = (char *)NULL;
5915
5916 if (args[0][0] == '-')
5917 args[0]++;
5918
5919 #if defined (RESTRICTED_SHELL)
5920 if (restricted)
5921 change_flag ('r', FLAG_OFF);
5922 #endif
5923
5924 if (subshell_argv)
5925 {
5926 /* Can't free subshell_argv[0]; that is shell_name. */
5927 for (i = 1; i < subshell_argc; i++)
5928 free (subshell_argv[i]);
5929 free (subshell_argv);
5930 }
5931
5932 dispose_command (currently_executing_command); /* XXX */
5933 currently_executing_command = (COMMAND *)NULL;
5934
5935 subshell_argc = larray;
5936 subshell_argv = args;
5937 subshell_envp = env;
5938
5939 unbind_args (); /* remove the positional parameters */
5940
5941 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
5942 clear_fifo_list (); /* pipe fds are what they are now */
5943 #endif
5944
5945 sh_longjmp (subshell_top_level, 1);
5946 /*NOTREACHED*/
5947 }
5948
5949 static int
5950 execute_intern_function (name, funcdef)
5951 WORD_DESC *name;
5952 FUNCTION_DEF *funcdef;
5953 {
5954 SHELL_VAR *var;
5955 char *t;
5956
5957 if (check_identifier (name, posixly_correct) == 0)
5958 {
5959 if (posixly_correct && interactive_shell == 0)
5960 {
5961 last_command_exit_value = EX_BADUSAGE;
5962 jump_to_top_level (ERREXIT);
5963 }
5964 return (EXECUTION_FAILURE);
5965 }
5966
5967 if (strchr (name->word, CTLESC)) /* WHY? */
5968 {
5969 t = dequote_escapes (name->word);
5970 free (name->word);
5971 name->word = t;
5972 }
5973
5974 /* Posix interpretation 383 */
5975 if (posixly_correct && find_special_builtin (name->word))
5976 {
5977 internal_error (_("`%s': is a special builtin"), name->word);
5978 last_command_exit_value = EX_BADUSAGE;
5979 jump_to_top_level (interactive_shell ? DISCARD : ERREXIT);
5980 }
5981
5982 var = find_function (name->word);
5983 if (var && (readonly_p (var) || noassign_p (var)))
5984 {
5985 if (readonly_p (var))
5986 internal_error (_("%s: readonly function"), var->name);
5987 return (EXECUTION_FAILURE);
5988 }
5989
5990 #if defined (DEBUGGER)
5991 bind_function_def (name->word, funcdef, 1);
5992 #endif
5993
5994 bind_function (name->word, funcdef->command);
5995 return (EXECUTION_SUCCESS);
5996 }
5997
5998 #if defined (INCLUDE_UNUSED)
5999 #if defined (PROCESS_SUBSTITUTION)
6000 void
6001 close_all_files ()
6002 {
6003 register int i, fd_table_size;
6004
6005 fd_table_size = getdtablesize ();
6006 if (fd_table_size > 256) /* clamp to a reasonable value */
6007 fd_table_size = 256;
6008
6009 for (i = 3; i < fd_table_size; i++)
6010 close (i);
6011 }
6012 #endif /* PROCESS_SUBSTITUTION */
6013 #endif
6014
6015 static void
6016 close_pipes (in, out)
6017 int in, out;
6018 {
6019 if (in >= 0)
6020 close (in);
6021 if (out >= 0)
6022 close (out);
6023 }
6024
6025 static void
6026 dup_error (oldd, newd)
6027 int oldd, newd;
6028 {
6029 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
6030 }
6031
6032 /* Redirect input and output to be from and to the specified pipes.
6033 NO_PIPE and REDIRECT_BOTH are handled correctly. */
6034 static void
6035 do_piping (pipe_in, pipe_out)
6036 int pipe_in, pipe_out;
6037 {
6038 if (pipe_in != NO_PIPE)
6039 {
6040 if (dup2 (pipe_in, 0) < 0)
6041 dup_error (pipe_in, 0);
6042 if (pipe_in > 0)
6043 close (pipe_in);
6044 #ifdef __CYGWIN__
6045 /* Let stdio know the fd may have changed from text to binary mode. */
6046 freopen (NULL, "r", stdin);
6047 #endif /* __CYGWIN__ */
6048 }
6049 if (pipe_out != NO_PIPE)
6050 {
6051 if (pipe_out != REDIRECT_BOTH)
6052 {
6053 if (dup2 (pipe_out, 1) < 0)
6054 dup_error (pipe_out, 1);
6055 if (pipe_out == 0 || pipe_out > 1)
6056 close (pipe_out);
6057 }
6058 else
6059 {
6060 if (dup2 (1, 2) < 0)
6061 dup_error (1, 2);
6062 }
6063 #ifdef __CYGWIN__
6064 /* Let stdio know the fd may have changed from text to binary mode, and
6065 make sure to preserve stdout line buffering. */
6066 freopen (NULL, "w", stdout);
6067 sh_setlinebuf (stdout);
6068 #endif /* __CYGWIN__ */
6069 }
6070 }