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