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