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