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