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