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