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