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