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