]> git.ipfire.org Git - thirdparty/bash.git/blame - execute_cmd.c
Bash-5.0 patch 11: fix quoted null character removal in operands of conditional ...
[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 {
41f5420d
CR
2770 optimize_fork (command);
2771
a0c0a00f
CR
2772 second = command->value.Connection->second;
2773 if (ignore_return && second)
2774 second->flags |= CMD_IGNORE_RETURN;
726f6388 2775
a0c0a00f 2776 exec_result = execute_command (second);
ccc6cda3 2777 }
3185942a 2778 executing_list--;
ccc6cda3
JA
2779 break;
2780
2781 default:
b72432fd 2782 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
ccc6cda3
JA
2783 jump_to_top_level (DISCARD);
2784 exec_result = EXECUTION_FAILURE;
726f6388
JA
2785 }
2786
ccc6cda3 2787 return exec_result;
726f6388
JA
2788}
2789
a0c0a00f
CR
2790/* The test used to be only for interactive_shell, but we don't want to report
2791 job status when the shell is not interactive or when job control isn't
2792 enabled. */
bb70624e
JA
2793#define REAP() \
2794 do \
2795 { \
a0c0a00f 2796 if (job_control == 0 || interactive_shell == 0) \
bb70624e
JA
2797 reap_dead_jobs (); \
2798 } \
2799 while (0)
726f6388
JA
2800
2801/* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
2802 DO command; DONE */
ccc6cda3 2803static int
726f6388
JA
2804execute_for_command (for_command)
2805 FOR_COM *for_command;
2806{
726f6388 2807 register WORD_LIST *releaser, *list;
ccc6cda3 2808 SHELL_VAR *v;
726f6388 2809 char *identifier;
b80f6443 2810 int retval, save_line_number;
ccc6cda3 2811#if 0
726f6388 2812 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
ccc6cda3 2813#endif
726f6388 2814
b80f6443 2815 save_line_number = line_number;
726f6388 2816 if (check_identifier (for_command->name, 1) == 0)
ccc6cda3
JA
2817 {
2818 if (posixly_correct && interactive_shell == 0)
cce855bc 2819 {
3185942a 2820 last_command_exit_value = EX_BADUSAGE;
b80f6443 2821 jump_to_top_level (ERREXIT);
cce855bc 2822 }
ccc6cda3
JA
2823 return (EXECUTION_FAILURE);
2824 }
726f6388
JA
2825
2826 loop_level++;
2827 identifier = for_command->name->word;
2828
ac50fbac 2829 line_number = for_command->line; /* for expansion error messages */
726f6388
JA
2830 list = releaser = expand_words_no_vars (for_command->map_list);
2831
2832 begin_unwind_frame ("for");
2833 add_unwind_protect (dispose_words, releaser);
2834
ccc6cda3 2835#if 0
726f6388
JA
2836 if (lexical_scoping)
2837 {
2838 old_value = copy_variable (find_variable (identifier));
2839 if (old_value)
2840 add_unwind_protect (dispose_variable, old_value);
2841 }
ccc6cda3 2842#endif
726f6388
JA
2843
2844 if (for_command->flags & CMD_IGNORE_RETURN)
2845 for_command->action->flags |= CMD_IGNORE_RETURN;
2846
ccc6cda3 2847 for (retval = EXECUTION_SUCCESS; list; list = list->next)
726f6388
JA
2848 {
2849 QUIT;
b80f6443
JA
2850
2851 line_number = for_command->line;
2852
2853 /* Remember what this command looks like, for debugger. */
2854 command_string_index = 0;
2855 print_for_command_head (for_command);
2856
2857 if (echo_command_at_execute)
2858 xtrace_print_for_command_head (for_command);
2859
95732b49
JA
2860 /* Save this command unless it's a trap command and we're not running
2861 a debug trap. */
0628567a 2862 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
b80f6443
JA
2863 {
2864 FREE (the_printed_command_except_trap);
2865 the_printed_command_except_trap = savestring (the_printed_command);
2866 }
2867
2868 retval = run_debug_trap ();
2869#if defined (DEBUGGER)
2870 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2871 skip the command. */
2872 if (debugging_mode && retval != EXECUTION_SUCCESS)
2873 continue;
2874#endif
2875
ccc6cda3 2876 this_command_name = (char *)NULL;
ac50fbac 2877 /* XXX - special ksh93 for command index variable handling */
a0c0a00f 2878 v = find_variable_last_nameref (identifier, 1);
ac50fbac 2879 if (v && nameref_p (v))
a0c0a00f
CR
2880 {
2881 if (valid_nameref_value (list->word->word, 1) == 0)
2882 {
2883 sh_invalidid (list->word->word);
2884 v = 0;
2885 }
d233b485
CR
2886 else if (readonly_p (v))
2887 err_readonly (name_cell (v));
a0c0a00f 2888 else
d233b485 2889 v = bind_variable_value (v, list->word->word, ASS_NAMEREF);
a0c0a00f 2890 }
ac50fbac 2891 else
a0c0a00f
CR
2892 v = bind_variable (identifier, list->word->word, 0);
2893
2894 if (v == 0 || readonly_p (v) || noassign_p (v))
ccc6cda3 2895 {
b80f6443 2896 line_number = save_line_number;
a0c0a00f 2897 if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
ccc6cda3
JA
2898 {
2899 last_command_exit_value = EXECUTION_FAILURE;
2900 jump_to_top_level (FORCE_EOF);
2901 }
2902 else
2903 {
b80f6443
JA
2904 dispose_words (releaser);
2905 discard_unwind_frame ("for");
d166f048 2906 loop_level--;
ccc6cda3
JA
2907 return (EXECUTION_FAILURE);
2908 }
2909 }
a0c0a00f
CR
2910
2911 if (ifsname (identifier))
2912 setifs (v);
2913
ccc6cda3 2914 retval = execute_command (for_command->action);
726f6388
JA
2915 REAP ();
2916 QUIT;
2917
2918 if (breaking)
2919 {
ccc6cda3 2920 breaking--;
726f6388
JA
2921 break;
2922 }
2923
2924 if (continuing)
2925 {
2926 continuing--;
2927 if (continuing)
2928 break;
2929 }
726f6388
JA
2930 }
2931
2932 loop_level--;
b80f6443 2933 line_number = save_line_number;
726f6388 2934
ccc6cda3 2935#if 0
726f6388
JA
2936 if (lexical_scoping)
2937 {
2938 if (!old_value)
7117c2d2 2939 unbind_variable (identifier);
726f6388
JA
2940 else
2941 {
2942 SHELL_VAR *new_value;
2943
d233b485 2944 new_value = bind_variable (identifier, value_cell (old_value), 0);
726f6388
JA
2945 new_value->attributes = old_value->attributes;
2946 dispose_variable (old_value);
2947 }
2948 }
ccc6cda3 2949#endif
726f6388
JA
2950
2951 dispose_words (releaser);
2952 discard_unwind_frame ("for");
2953 return (retval);
2954}
2955
bb70624e
JA
2956#if defined (ARITH_FOR_COMMAND)
2957/* Execute an arithmetic for command. The syntax is
2958
2959 for (( init ; step ; test ))
2960 do
2961 body
2962 done
2963
2964 The execution should be exactly equivalent to
2965
2966 eval \(\( init \)\)
2967 while eval \(\( test \)\) ; do
2968 body;
2969 eval \(\( step \)\)
2970 done
2971*/
7117c2d2 2972static intmax_t
bb70624e
JA
2973eval_arith_for_expr (l, okp)
2974 WORD_LIST *l;
2975 int *okp;
2976{
2977 WORD_LIST *new;
7117c2d2 2978 intmax_t expresult;
b80f6443 2979 int r;
bb70624e
JA
2980
2981 new = expand_words_no_vars (l);
f73dda09
JA
2982 if (new)
2983 {
2984 if (echo_command_at_execute)
2985 xtrace_print_arith_cmd (new);
7117c2d2 2986 this_command_name = "(("; /* )) for expression error messages */
b80f6443
JA
2987
2988 command_string_index = 0;
2989 print_arith_command (new);
d233b485 2990 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
95732b49
JA
2991 {
2992 FREE (the_printed_command_except_trap);
2993 the_printed_command_except_trap = savestring (the_printed_command);
2994 }
b80f6443
JA
2995
2996 r = run_debug_trap ();
2997 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
2998 skip the command. */
2999#if defined (DEBUGGER)
3000 if (debugging_mode == 0 || r == EXECUTION_SUCCESS)
d233b485 3001 expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
b80f6443
JA
3002 else
3003 {
3004 expresult = 0;
3005 if (okp)
3006 *okp = 1;
3007 }
3008#else
d233b485 3009 expresult = evalexp (new->word->word, EXP_EXPANDED, okp);
b80f6443 3010#endif
f73dda09
JA
3011 dispose_words (new);
3012 }
3013 else
3014 {
3015 expresult = 0;
3016 if (okp)
3017 *okp = 1;
3018 }
bb70624e
JA
3019 return (expresult);
3020}
3021
3022static int
3023execute_arith_for_command (arith_for_command)
3024 ARITH_FOR_COM *arith_for_command;
3025{
7117c2d2
JA
3026 intmax_t expresult;
3027 int expok, body_status, arith_lineno, save_lineno;
bb70624e
JA
3028
3029 body_status = EXECUTION_SUCCESS;
3030 loop_level++;
b80f6443 3031 save_lineno = line_number;
bb70624e
JA
3032
3033 if (arith_for_command->flags & CMD_IGNORE_RETURN)
3034 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
3035
3036 this_command_name = "(("; /* )) for expression error messages */
3037
7117c2d2
JA
3038 /* save the starting line number of the command so we can reset
3039 line_number before executing each expression -- for $LINENO
3040 and the DEBUG trap. */
b80f6443 3041 line_number = arith_lineno = arith_for_command->line;
d233b485 3042 if (variable_context && interactive_shell && sourcelevel == 0)
a0c0a00f 3043 {
d233b485
CR
3044 /* line numbers in a function start at 1 */
3045 line_number -= function_line_number - 1;
3046 if (line_number <= 0)
3047 line_number = 1;
a0c0a00f 3048 }
bb70624e
JA
3049
3050 /* Evaluate the initialization expression. */
3051 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
3052 if (expok == 0)
b80f6443
JA
3053 {
3054 line_number = save_lineno;
3055 return (EXECUTION_FAILURE);
3056 }
bb70624e
JA
3057
3058 while (1)
3059 {
3060 /* Evaluate the test expression. */
7117c2d2 3061 line_number = arith_lineno;
bb70624e 3062 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
7117c2d2
JA
3063 line_number = save_lineno;
3064
bb70624e
JA
3065 if (expok == 0)
3066 {
3067 body_status = EXECUTION_FAILURE;
3068 break;
3069 }
3070 REAP ();
3071 if (expresult == 0)
28ef6c31 3072 break;
bb70624e
JA
3073
3074 /* Execute the body of the arithmetic for command. */
3075 QUIT;
3076 body_status = execute_command (arith_for_command->action);
3077 QUIT;
3078
3079 /* Handle any `break' or `continue' commands executed by the body. */
3080 if (breaking)
3081 {
3082 breaking--;
3083 break;
3084 }
3085
3086 if (continuing)
3087 {
3088 continuing--;
3089 if (continuing)
3090 break;
3091 }
3092
3093 /* Evaluate the step expression. */
7117c2d2 3094 line_number = arith_lineno;
bb70624e 3095 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
7117c2d2
JA
3096 line_number = save_lineno;
3097
bb70624e
JA
3098 if (expok == 0)
3099 {
3100 body_status = EXECUTION_FAILURE;
3101 break;
3102 }
3103 }
3104
3105 loop_level--;
b80f6443
JA
3106 line_number = save_lineno;
3107
bb70624e
JA
3108 return (body_status);
3109}
3110#endif
3111
726f6388
JA
3112#if defined (SELECT_COMMAND)
3113static int LINES, COLS, tabsize;
3114
3115#define RP_SPACE ") "
3116#define RP_SPACE_LEN 2
3117
3118/* XXX - does not handle numbers > 1000000 at all. */
3119#define NUMBER_LEN(s) \
3120((s < 10) ? 1 \
3121 : ((s < 100) ? 2 \
3122 : ((s < 1000) ? 3 \
3123 : ((s < 10000) ? 4 \
3124 : ((s < 100000) ? 5 \
3125 : 6)))))
3126
495aee44
CR
3127static int
3128displen (s)
3129 const char *s;
3130{
3131#if defined (HANDLE_MULTIBYTE)
3132 wchar_t *wcstr;
ac50fbac
CR
3133 size_t slen;
3134 int wclen;
495aee44
CR
3135
3136 wcstr = 0;
3137 slen = mbstowcs (wcstr, s, 0);
3138 if (slen == -1)
3139 slen = 0;
3140 wcstr = (wchar_t *)xmalloc (sizeof (wchar_t) * (slen + 1));
3141 mbstowcs (wcstr, s, slen + 1);
3142 wclen = wcswidth (wcstr, slen);
3143 free (wcstr);
ac50fbac 3144 return (wclen < 0 ? STRLEN(s) : wclen);
495aee44
CR
3145#else
3146 return (STRLEN (s));
3147#endif
3148}
3149
726f6388
JA
3150static int
3151print_index_and_element (len, ind, list)
3152 int len, ind;
3153 WORD_LIST *list;
3154{
3155 register WORD_LIST *l;
3156 register int i;
3157
3158 if (list == 0)
3159 return (0);
ccc6cda3
JA
3160 for (i = ind, l = list; l && --i; l = l->next)
3161 ;
ac50fbac
CR
3162 if (l == 0) /* don't think this can happen */
3163 return (0);
726f6388 3164 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
495aee44 3165 return (displen (l->word->word));
726f6388
JA
3166}
3167
3168static void
3169indent (from, to)
3170 int from, to;
3171{
3172 while (from < to)
3173 {
3174 if ((to / tabsize) > (from / tabsize))
3175 {
3176 putc ('\t', stderr);
3177 from += tabsize - from % tabsize;
3178 }
3179 else
3180 {
3181 putc (' ', stderr);
3182 from++;
3183 }
3184 }
3185}
3186
3187static void
3188print_select_list (list, list_len, max_elem_len, indices_len)
3189 WORD_LIST *list;
3190 int list_len, max_elem_len, indices_len;
3191{
3192 int ind, row, elem_len, pos, cols, rows;
3193 int first_column_indices_len, other_indices_len;
3194
3195 if (list == 0)
3196 {
3197 putc ('\n', stderr);
3198 return;
3199 }
3200
ccc6cda3 3201 cols = max_elem_len ? COLS / max_elem_len : 1;
726f6388
JA
3202 if (cols == 0)
3203 cols = 1;
3204 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
3205 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
3206
3207 if (rows == 1)
3208 {
3209 rows = cols;
3210 cols = 1;
3211 }
3212
3213 first_column_indices_len = NUMBER_LEN (rows);
3214 other_indices_len = indices_len;
3215
3216 for (row = 0; row < rows; row++)
3217 {
3218 ind = row;
3219 pos = 0;
3220 while (1)
3221 {
3222 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
3223 elem_len = print_index_and_element (indices_len, ind + 1, list);
3224 elem_len += indices_len + RP_SPACE_LEN;
3225 ind += rows;
3226 if (ind >= list_len)
3227 break;
3228 indent (pos + elem_len, pos + max_elem_len);
3229 pos += max_elem_len;
3230 }
3231 putc ('\n', stderr);
3232 }
3233}
3234
3235/* Print the elements of LIST, one per line, preceded by an index from 1 to
3236 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
3237 If the number is between 1 and LIST_LEN, return that selection. If EOF
e8ce775d
JA
3238 is read, return a null string. If a blank line is entered, or an invalid
3239 number is entered, the loop is executed again. */
726f6388 3240static char *
7117c2d2 3241select_query (list, list_len, prompt, print_menu)
726f6388
JA
3242 WORD_LIST *list;
3243 int list_len;
3244 char *prompt;
7117c2d2 3245 int print_menu;
726f6388 3246{
e8ce775d 3247 int max_elem_len, indices_len, len;
7117c2d2 3248 intmax_t reply;
726f6388
JA
3249 WORD_LIST *l;
3250 char *repl_string, *t;
3251
d233b485 3252 COLS = default_columns ();
726f6388
JA
3253
3254#if 0
3255 t = get_string_value ("TABSIZE");
3256 tabsize = (t && *t) ? atoi (t) : 8;
3257 if (tabsize <= 0)
3258 tabsize = 8;
3259#else
3260 tabsize = 8;
3261#endif
3262
3263 max_elem_len = 0;
3264 for (l = list; l; l = l->next)
3265 {
495aee44 3266 len = displen (l->word->word);
726f6388 3267 if (len > max_elem_len)
cce855bc 3268 max_elem_len = len;
726f6388
JA
3269 }
3270 indices_len = NUMBER_LEN (list_len);
3271 max_elem_len += indices_len + RP_SPACE_LEN + 2;
3272
3273 while (1)
3274 {
7117c2d2
JA
3275 if (print_menu)
3276 print_select_list (list, list_len, max_elem_len, indices_len);
ccc6cda3
JA
3277 fprintf (stderr, "%s", prompt);
3278 fflush (stderr);
726f6388
JA
3279 QUIT;
3280
495aee44 3281 if (read_builtin ((WORD_LIST *)NULL) != EXECUTION_SUCCESS)
726f6388
JA
3282 {
3283 putchar ('\n');
3284 return ((char *)NULL);
3285 }
3286 repl_string = get_string_value ("REPLY");
a0c0a00f
CR
3287 if (repl_string == 0)
3288 return ((char *)NULL);
726f6388 3289 if (*repl_string == 0)
7117c2d2
JA
3290 {
3291 print_menu = 1;
3292 continue;
3293 }
e8ce775d 3294 if (legal_number (repl_string, &reply) == 0)
cce855bc 3295 return "";
726f6388
JA
3296 if (reply < 1 || reply > list_len)
3297 return "";
3298
ccc6cda3
JA
3299 for (l = list; l && --reply; l = l->next)
3300 ;
ac50fbac 3301 return (l->word->word); /* XXX - can't be null? */
726f6388
JA
3302 }
3303}
3304
3305/* Execute a SELECT command. The syntax is:
3306 SELECT word IN list DO command_list DONE
3307 Only `break' or `return' in command_list will terminate
3308 the command. */
ccc6cda3 3309static int
726f6388
JA
3310execute_select_command (select_command)
3311 SELECT_COM *select_command;
3312{
3313 WORD_LIST *releaser, *list;
ccc6cda3 3314 SHELL_VAR *v;
726f6388 3315 char *identifier, *ps3_prompt, *selection;
b80f6443 3316 int retval, list_len, show_menu, save_line_number;
7117c2d2 3317
726f6388
JA
3318 if (check_identifier (select_command->name, 1) == 0)
3319 return (EXECUTION_FAILURE);
3320
b80f6443
JA
3321 save_line_number = line_number;
3322 line_number = select_command->line;
3323
3324 command_string_index = 0;
3325 print_select_command_head (select_command);
3326
3327 if (echo_command_at_execute)
3328 xtrace_print_select_command_head (select_command);
3329
0628567a 3330#if 0
95732b49 3331 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
0628567a
JA
3332#else
3333 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3334#endif
95732b49
JA
3335 {
3336 FREE (the_printed_command_except_trap);
3337 the_printed_command_except_trap = savestring (the_printed_command);
3338 }
b80f6443
JA
3339
3340 retval = run_debug_trap ();
3341#if defined (DEBUGGER)
3342 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3343 skip the command. */
3344 if (debugging_mode && retval != EXECUTION_SUCCESS)
3345 return (EXECUTION_SUCCESS);
3346#endif
3347
726f6388
JA
3348 loop_level++;
3349 identifier = select_command->name->word;
3350
3351 /* command and arithmetic substitution, parameter and variable expansion,
3352 word splitting, pathname expansion, and quote removal. */
3353 list = releaser = expand_words_no_vars (select_command->map_list);
3354 list_len = list_length (list);
3355 if (list == 0 || list_len == 0)
3356 {
3357 if (list)
3358 dispose_words (list);
b80f6443 3359 line_number = save_line_number;
726f6388
JA
3360 return (EXECUTION_SUCCESS);
3361 }
3362
3363 begin_unwind_frame ("select");
3364 add_unwind_protect (dispose_words, releaser);
3365
726f6388
JA
3366 if (select_command->flags & CMD_IGNORE_RETURN)
3367 select_command->action->flags |= CMD_IGNORE_RETURN;
3368
ccc6cda3 3369 retval = EXECUTION_SUCCESS;
7117c2d2 3370 show_menu = 1;
ccc6cda3 3371
726f6388
JA
3372 while (1)
3373 {
b80f6443 3374 line_number = select_command->line;
726f6388 3375 ps3_prompt = get_string_value ("PS3");
ccc6cda3 3376 if (ps3_prompt == 0)
726f6388
JA
3377 ps3_prompt = "#? ";
3378
3379 QUIT;
7117c2d2 3380 selection = select_query (list, list_len, ps3_prompt, show_menu);
726f6388
JA
3381 QUIT;
3382 if (selection == 0)
7117c2d2
JA
3383 {
3384 /* select_query returns EXECUTION_FAILURE if the read builtin
3385 fails, so we want to return failure in this case. */
3386 retval = EXECUTION_FAILURE;
3387 break;
3388 }
ccc6cda3 3389
95732b49 3390 v = bind_variable (identifier, selection, 0);
a0c0a00f 3391 if (v == 0 || readonly_p (v) || noassign_p (v))
ccc6cda3 3392 {
a0c0a00f 3393 if (v && readonly_p (v) && interactive_shell == 0 && posixly_correct)
ccc6cda3
JA
3394 {
3395 last_command_exit_value = EXECUTION_FAILURE;
3396 jump_to_top_level (FORCE_EOF);
3397 }
3398 else
3399 {
b80f6443
JA
3400 dispose_words (releaser);
3401 discard_unwind_frame ("select");
3402 loop_level--;
3403 line_number = save_line_number;
ccc6cda3
JA
3404 return (EXECUTION_FAILURE);
3405 }
3406 }
726f6388 3407
f73dda09 3408 retval = execute_command (select_command->action);
726f6388
JA
3409
3410 REAP ();
3411 QUIT;
3412
3413 if (breaking)
3414 {
3415 breaking--;
3416 break;
3417 }
bb70624e
JA
3418
3419 if (continuing)
3420 {
3421 continuing--;
3422 if (continuing)
3423 break;
3424 }
7117c2d2
JA
3425
3426#if defined (KSH_COMPATIBLE_SELECT)
3427 show_menu = 0;
3428 selection = get_string_value ("REPLY");
3429 if (selection && *selection == '\0')
3430 show_menu = 1;
3431#endif
726f6388
JA
3432 }
3433
3434 loop_level--;
b80f6443 3435 line_number = save_line_number;
726f6388 3436
b80f6443
JA
3437 dispose_words (releaser);
3438 discard_unwind_frame ("select");
726f6388
JA
3439 return (retval);
3440}
3441#endif /* SELECT_COMMAND */
3442
3443/* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
3444 The pattern_list is a linked list of pattern clauses; each clause contains
3445 some patterns to compare word_desc against, and an associated command to
3446 execute. */
ccc6cda3 3447static int
726f6388
JA
3448execute_case_command (case_command)
3449 CASE_COM *case_command;
3450{
3451 register WORD_LIST *list;
ccc6cda3 3452 WORD_LIST *wlist, *es;
726f6388 3453 PATTERN_LIST *clauses;
ccc6cda3 3454 char *word, *pattern;
d233b485 3455 int retval, match, ignore_return, save_line_number, qflags;
b80f6443
JA
3456
3457 save_line_number = line_number;
3458 line_number = case_command->line;
3459
3460 command_string_index = 0;
3461 print_case_command_head (case_command);
3462
3463 if (echo_command_at_execute)
3464 xtrace_print_case_command_head (case_command);
3465
0628567a
JA
3466#if 0
3467 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
3468#else
3469 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
3470#endif
b80f6443
JA
3471 {
3472 FREE (the_printed_command_except_trap);
3473 the_printed_command_except_trap = savestring (the_printed_command);
3474 }
3475
3476 retval = run_debug_trap();
3477#if defined (DEBUGGER)
3478 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3479 skip the command. */
3480 if (debugging_mode && retval != EXECUTION_SUCCESS)
3481 {
3482 line_number = save_line_number;
3483 return (EXECUTION_SUCCESS);
3484 }
3485#endif
726f6388 3486
d233b485
CR
3487 /* Use the same expansions (the ones POSIX specifies) as the patterns;
3488 dequote the resulting string (as POSIX specifies) since the quotes in
3489 patterns are handled specially below. We have to do it in this order
3490 because we're not supposed to perform word splitting. */
3491 wlist = expand_word_leave_quoted (case_command->word, 0);
3492 if (wlist)
3493 {
3494 char *t;
3495 t = string_list (wlist);
3496 word = dequote_string (t);
3497 free (t);
3498 }
3499 else
3500 word = savestring ("");
ccc6cda3
JA
3501 dispose_words (wlist);
3502
726f6388 3503 retval = EXECUTION_SUCCESS;
ccc6cda3 3504 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
726f6388
JA
3505
3506 begin_unwind_frame ("case");
a0c0a00f 3507 add_unwind_protect (xfree, word);
726f6388 3508
ccc6cda3
JA
3509#define EXIT_CASE() goto exit_case_command
3510
3511 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
726f6388
JA
3512 {
3513 QUIT;
ccc6cda3 3514 for (list = clauses->patterns; list; list = list->next)
726f6388 3515 {
726f6388
JA
3516 es = expand_word_leave_quoted (list->word, 0);
3517
3518 if (es && es->word && es->word->word && *(es->word->word))
d233b485
CR
3519 {
3520 /* Convert quoted null strings into empty strings. */
3521 qflags = QGLOB_CVTNULL;
3522
3523 /* We left CTLESC in place quoting CTLESC and CTLNUL after the
3524 call to expand_word_leave_quoted; tell quote_string_for_globbing
3525 to remove those here. This works for both unquoted portions of
3526 the word (which call quote_escapes) and quoted portions
3527 (which call quote_string). */
3528 qflags |= QGLOB_CTLESC;
3529 pattern = quote_string_for_globbing (es->word->word, qflags);
3530 }
726f6388 3531 else
ccc6cda3 3532 {
f73dda09 3533 pattern = (char *)xmalloc (1);
ccc6cda3
JA
3534 pattern[0] = '\0';
3535 }
726f6388
JA
3536
3537 /* Since the pattern does not undergo quote removal (as per
f73dda09 3538 Posix.2, section 3.9.4.3), the strmatch () call must be able
726f6388 3539 to recognize backslashes as escape characters. */
95732b49 3540 match = strmatch (pattern, word, FNMATCH_EXTFLAG|FNMATCH_IGNCASE) != FNM_NOMATCH;
726f6388
JA
3541 free (pattern);
3542
3543 dispose_words (es);
3544
3545 if (match)
3546 {
3185942a
JA
3547 do
3548 {
3549 if (clauses->action && ignore_return)
3550 clauses->action->flags |= CMD_IGNORE_RETURN;
3551 retval = execute_command (clauses->action);
3552 }
3553 while ((clauses->flags & CASEPAT_FALLTHROUGH) && (clauses = clauses->next));
89a92869 3554 if (clauses == 0 || (clauses->flags & CASEPAT_TESTNEXT) == 0)
3185942a
JA
3555 EXIT_CASE ();
3556 else
3557 break;
726f6388
JA
3558 }
3559
726f6388
JA
3560 QUIT;
3561 }
726f6388
JA
3562 }
3563
ccc6cda3
JA
3564exit_case_command:
3565 free (word);
726f6388 3566 discard_unwind_frame ("case");
b80f6443 3567 line_number = save_line_number;
726f6388
JA
3568 return (retval);
3569}
3570
3571#define CMD_WHILE 0
3572#define CMD_UNTIL 1
3573
3574/* The WHILE command. Syntax: WHILE test DO action; DONE.
3575 Repeatedly execute action while executing test produces
3576 EXECUTION_SUCCESS. */
ccc6cda3 3577static int
726f6388
JA
3578execute_while_command (while_command)
3579 WHILE_COM *while_command;
3580{
3581 return (execute_while_or_until (while_command, CMD_WHILE));
3582}
3583
3584/* UNTIL is just like WHILE except that the test result is negated. */
ccc6cda3 3585static int
726f6388
JA
3586execute_until_command (while_command)
3587 WHILE_COM *while_command;
3588{
3589 return (execute_while_or_until (while_command, CMD_UNTIL));
3590}
3591
3592/* The body for both while and until. The only difference between the
3593 two is that the test value is treated differently. TYPE is
3594 CMD_WHILE or CMD_UNTIL. The return value for both commands should
3595 be EXECUTION_SUCCESS if no commands in the body are executed, and
3596 the status of the last command executed in the body otherwise. */
ccc6cda3 3597static int
726f6388
JA
3598execute_while_or_until (while_command, type)
3599 WHILE_COM *while_command;
3600 int type;
3601{
3602 int return_value, body_status;
3603
3604 body_status = EXECUTION_SUCCESS;
3605 loop_level++;
3606
3607 while_command->test->flags |= CMD_IGNORE_RETURN;
3608 if (while_command->flags & CMD_IGNORE_RETURN)
3609 while_command->action->flags |= CMD_IGNORE_RETURN;
3610
3611 while (1)
3612 {
3613 return_value = execute_command (while_command->test);
3614 REAP ();
3615
f73dda09
JA
3616 /* Need to handle `break' in the test when we would break out of the
3617 loop. The job control code will set `breaking' to loop_level
3618 when a job in a loop is stopped with SIGTSTP. If the stopped job
3619 is in the loop test, `breaking' will not be reset unless we do
a0c0a00f
CR
3620 this, and the shell will cease to execute commands. The same holds
3621 true for `continue'. */
726f6388 3622 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
f73dda09
JA
3623 {
3624 if (breaking)
3625 breaking--;
a0c0a00f
CR
3626 if (continuing)
3627 continuing--;
f73dda09
JA
3628 break;
3629 }
726f6388 3630 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
f73dda09
JA
3631 {
3632 if (breaking)
3633 breaking--;
a0c0a00f
CR
3634 if (continuing)
3635 continuing--;
f73dda09
JA
3636 break;
3637 }
726f6388
JA
3638
3639 QUIT;
3640 body_status = execute_command (while_command->action);
3641 QUIT;
3642
3643 if (breaking)
3644 {
3645 breaking--;
3646 break;
3647 }
3648
3649 if (continuing)
3650 {
3651 continuing--;
3652 if (continuing)
3653 break;
3654 }
3655 }
3656 loop_level--;
3657
3658 return (body_status);
3659}
3660
3661/* IF test THEN command [ELSE command].
3662 IF also allows ELIF in the place of ELSE IF, but
3663 the parser makes *that* stupidity transparent. */
ccc6cda3 3664static int
726f6388
JA
3665execute_if_command (if_command)
3666 IF_COM *if_command;
3667{
b80f6443 3668 int return_value, save_line_number;
726f6388 3669
b80f6443 3670 save_line_number = line_number;
726f6388
JA
3671 if_command->test->flags |= CMD_IGNORE_RETURN;
3672 return_value = execute_command (if_command->test);
b80f6443 3673 line_number = save_line_number;
726f6388
JA
3674
3675 if (return_value == EXECUTION_SUCCESS)
3676 {
3677 QUIT;
ccc6cda3 3678
726f6388 3679 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
ccc6cda3
JA
3680 if_command->true_case->flags |= CMD_IGNORE_RETURN;
3681
726f6388
JA
3682 return (execute_command (if_command->true_case));
3683 }
3684 else
3685 {
3686 QUIT;
3687
3688 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
3689 if_command->false_case->flags |= CMD_IGNORE_RETURN;
3690
3691 return (execute_command (if_command->false_case));
3692 }
3693}
3694
cce855bc
JA
3695#if defined (DPAREN_ARITHMETIC)
3696static int
3697execute_arith_command (arith_command)
3698 ARITH_COM *arith_command;
3699{
b80f6443 3700 int expok, save_line_number, retval;
7117c2d2 3701 intmax_t expresult;
f73dda09 3702 WORD_LIST *new;
0628567a 3703 char *exp;
cce855bc 3704
f73dda09 3705 expresult = 0;
cce855bc 3706
b80f6443 3707 save_line_number = line_number;
b72432fd 3708 this_command_name = "(("; /* )) */
d233b485 3709 line_number_for_err_trap = line_number = arith_command->line;
cce855bc 3710 /* If we're in a function, update the line number information. */
d233b485 3711 if (variable_context && interactive_shell && sourcelevel == 0)
a0c0a00f 3712 {
d233b485
CR
3713 /* line numbers in a function start at 1 */
3714 line_number -= function_line_number - 1;
3715 if (line_number <= 0)
3716 line_number = 1;
a0c0a00f 3717 }
b80f6443
JA
3718
3719 command_string_index = 0;
3720 print_arith_command (arith_command->exp);
95732b49 3721
d233b485 3722 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
95732b49
JA
3723 {
3724 FREE (the_printed_command_except_trap);
3725 the_printed_command_except_trap = savestring (the_printed_command);
3726 }
cce855bc 3727
7117c2d2
JA
3728 /* Run the debug trap before each arithmetic command, but do it after we
3729 update the line number information and before we expand the various
3730 words in the expression. */
b80f6443
JA
3731 retval = run_debug_trap ();
3732#if defined (DEBUGGER)
3733 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3734 skip the command. */
3735 if (debugging_mode && retval != EXECUTION_SUCCESS)
3736 {
3737 line_number = save_line_number;
3738 return (EXECUTION_SUCCESS);
3739 }
3740#endif
7117c2d2 3741
b80f6443 3742 new = expand_words_no_vars (arith_command->exp);
cce855bc
JA
3743
3744 /* If we're tracing, make a new word list with `((' at the front and `))'
3745 at the back and print it. */
3746 if (echo_command_at_execute)
3747 xtrace_print_arith_cmd (new);
3748
b80f6443
JA
3749 if (new)
3750 {
0628567a 3751 exp = new->next ? string_list (new) : new->word->word;
d233b485 3752 expresult = evalexp (exp, EXP_EXPANDED, &expok);
b80f6443 3753 line_number = save_line_number;
0628567a
JA
3754 if (exp != new->word->word)
3755 free (exp);
b80f6443
JA
3756 dispose_words (new);
3757 }
3758 else
3759 {
3760 expresult = 0;
3761 expok = 1;
3762 }
cce855bc
JA
3763
3764 if (expok == 0)
3765 return (EXECUTION_FAILURE);
3766
f73dda09 3767 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
cce855bc
JA
3768}
3769#endif /* DPAREN_ARITHMETIC */
3770
3771#if defined (COND_COMMAND)
3772
3185942a 3773static char * const nullstr = "";
cce855bc 3774
ac50fbac 3775/* XXX - can COND ever be NULL when this is called? */
cce855bc
JA
3776static int
3777execute_cond_node (cond)
3778 COND_COM *cond;
3779{
0001803f 3780 int result, invert, patmatch, rmatch, mflags, ignore;
f73dda09 3781 char *arg1, *arg2;
ac50fbac
CR
3782#if 0
3783 char *t1, *t2;
3784#endif
cce855bc
JA
3785
3786 invert = (cond->flags & CMD_INVERT_RETURN);
0001803f
CR
3787 ignore = (cond->flags & CMD_IGNORE_RETURN);
3788 if (ignore)
3789 {
3790 if (cond->left)
3791 cond->left->flags |= CMD_IGNORE_RETURN;
3792 if (cond->right)
3793 cond->right->flags |= CMD_IGNORE_RETURN;
3794 }
3795
cce855bc
JA
3796 if (cond->type == COND_EXPR)
3797 result = execute_cond_node (cond->left);
3798 else if (cond->type == COND_OR)
3799 {
3800 result = execute_cond_node (cond->left);
3801 if (result != EXECUTION_SUCCESS)
3802 result = execute_cond_node (cond->right);
3803 }
3804 else if (cond->type == COND_AND)
3805 {
3806 result = execute_cond_node (cond->left);
3807 if (result == EXECUTION_SUCCESS)
3808 result = execute_cond_node (cond->right);
3809 }
3810 else if (cond->type == COND_UNARY)
3811 {
0001803f
CR
3812 if (ignore)
3813 comsub_ignore_return++;
cce855bc 3814 arg1 = cond_expand_word (cond->left->op, 0);
0001803f
CR
3815 if (ignore)
3816 comsub_ignore_return--;
cce855bc
JA
3817 if (arg1 == 0)
3818 arg1 = nullstr;
3819 if (echo_command_at_execute)
3820 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
3821 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
3822 if (arg1 != nullstr)
3823 free (arg1);
3824 }
3825 else if (cond->type == COND_BINARY)
3826 {
0628567a 3827 rmatch = 0;
ac50fbac
CR
3828 patmatch = (((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
3829 (cond->op->word[0] == '!' || cond->op->word[0] == '=')) ||
b72432fd 3830 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
b80f6443
JA
3831#if defined (COND_REGEXP)
3832 rmatch = (cond->op->word[0] == '=' && cond->op->word[1] == '~' &&
3833 cond->op->word[2] == '\0');
3834#endif
cce855bc 3835
0001803f
CR
3836 if (ignore)
3837 comsub_ignore_return++;
cce855bc 3838 arg1 = cond_expand_word (cond->left->op, 0);
0001803f
CR
3839 if (ignore)
3840 comsub_ignore_return--;
cce855bc
JA
3841 if (arg1 == 0)
3842 arg1 = nullstr;
0001803f
CR
3843 if (ignore)
3844 comsub_ignore_return++;
f1be666c
JA
3845 arg2 = cond_expand_word (cond->right->op,
3846 (rmatch && shell_compatibility_level > 31) ? 2 : (patmatch ? 1 : 0));
0001803f
CR
3847 if (ignore)
3848 comsub_ignore_return--;
cce855bc
JA
3849 if (arg2 == 0)
3850 arg2 = nullstr;
3851
3852 if (echo_command_at_execute)
3853 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
3854
b80f6443
JA
3855#if defined (COND_REGEXP)
3856 if (rmatch)
3857 {
3858 mflags = SHMAT_PWARN;
3859#if defined (ARRAY_VARS)
3860 mflags |= SHMAT_SUBEXP;
3861#endif
3862
ac50fbac
CR
3863#if 0
3864 t1 = strescape(arg1);
3865 t2 = strescape(arg2);
3866 itrace("execute_cond_node: sh_regmatch on `%s' and `%s'", t1, t2);
3867 free(t1);
3868 free(t2);
3869#endif
3870
b80f6443
JA
3871 result = sh_regmatch (arg1, arg2, mflags);
3872 }
3873 else
3874#endif /* COND_REGEXP */
95732b49
JA
3875 {
3876 int oe;
3877 oe = extended_glob;
3878 extended_glob = 1;
0001803f 3879 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP|TEST_LOCALE)
95732b49
JA
3880 ? EXECUTION_SUCCESS
3881 : EXECUTION_FAILURE;
3882 extended_glob = oe;
3883 }
cce855bc
JA
3884 if (arg1 != nullstr)
3885 free (arg1);
3886 if (arg2 != nullstr)
3887 free (arg2);
3888 }
3889 else
3890 {
b72432fd 3891 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
cce855bc
JA
3892 jump_to_top_level (DISCARD);
3893 result = EXECUTION_FAILURE;
3894 }
3895
3896 if (invert)
3897 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
3898
3899 return result;
3900}
3901
3902static int
3903execute_cond_command (cond_command)
3904 COND_COM *cond_command;
3905{
b80f6443 3906 int retval, save_line_number;
cce855bc 3907
b80f6443 3908 save_line_number = line_number;
cce855bc
JA
3909
3910 this_command_name = "[[";
d233b485 3911 line_number_for_err_trap = line_number = cond_command->line;
cce855bc 3912 /* If we're in a function, update the line number information. */
d233b485 3913 if (variable_context && interactive_shell && sourcelevel == 0)
a0c0a00f 3914 {
d233b485
CR
3915 /* line numbers in a function start at 1 */
3916 line_number -= function_line_number - 1;
3917 if (line_number <= 0)
3918 line_number = 1;
a0c0a00f 3919 }
b80f6443
JA
3920 command_string_index = 0;
3921 print_cond_command (cond_command);
95732b49 3922
d233b485 3923 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
95732b49
JA
3924 {
3925 FREE (the_printed_command_except_trap);
3926 the_printed_command_except_trap = savestring (the_printed_command);
3927 }
cce855bc 3928
7117c2d2
JA
3929 /* Run the debug trap before each conditional command, but do it after we
3930 update the line number information. */
b80f6443
JA
3931 retval = run_debug_trap ();
3932#if defined (DEBUGGER)
3933 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
3934 skip the command. */
3935 if (debugging_mode && retval != EXECUTION_SUCCESS)
3936 {
3937 line_number = save_line_number;
3938 return (EXECUTION_SUCCESS);
3939 }
3940#endif
7117c2d2 3941
cce855bc
JA
3942#if 0
3943 debug_print_cond_command (cond_command);
3944#endif
b80f6443
JA
3945
3946 last_command_exit_value = retval = execute_cond_node (cond_command);
3947 line_number = save_line_number;
3948 return (retval);
cce855bc
JA
3949}
3950#endif /* COND_COMMAND */
3951
726f6388
JA
3952static void
3953bind_lastarg (arg)
3954 char *arg;
3955{
3956 SHELL_VAR *var;
3957
ccc6cda3 3958 if (arg == 0)
726f6388 3959 arg = "";
95732b49 3960 var = bind_variable ("_", arg, 0);
a0c0a00f
CR
3961 if (var)
3962 VUNSETATTR (var, att_exported);
726f6388
JA
3963}
3964
ccc6cda3
JA
3965/* Execute a null command. Fork a subshell if the command uses pipes or is
3966 to be run asynchronously. This handles all the side effects that are
3967 supposed to take place. */
3968static int
95732b49 3969execute_null_command (redirects, pipe_in, pipe_out, async)
ccc6cda3 3970 REDIRECT *redirects;
bb70624e 3971 int pipe_in, pipe_out, async;
ccc6cda3 3972{
b80f6443 3973 int r;
0001803f
CR
3974 int forcefork;
3975 REDIRECT *rd;
b80f6443 3976
0001803f 3977 for (forcefork = 0, rd = redirects; rd; rd = rd->next)
d233b485
CR
3978 {
3979 forcefork += rd->rflags & REDIR_VARASSIGN;
3980 /* Safety */
3981 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);
3982 }
0001803f
CR
3983
3984 if (forcefork || pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
ccc6cda3
JA
3985 {
3986 /* We have a null command, but we really want a subshell to take
3987 care of it. Just fork, do piping and redirections, and exit. */
3988 if (make_child ((char *)NULL, async) == 0)
3989 {
3990 /* Cancel traps, in trap.c. */
3991 restore_original_signals (); /* XXX */
3992
3993 do_piping (pipe_in, pipe_out);
3994
3185942a
JA
3995#if defined (COPROCESS_SUPPORT)
3996 coproc_closeall ();
3997#endif
3998
d233b485
CR
3999 interactive = 0; /* XXX */
4000
3185942a 4001 subshell_environment = 0;
0628567a
JA
4002 if (async)
4003 subshell_environment |= SUBSHELL_ASYNC;
4004 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4005 subshell_environment |= SUBSHELL_PIPE;
ccc6cda3 4006
b80f6443 4007 if (do_redirections (redirects, RX_ACTIVE) == 0)
ccc6cda3
JA
4008 exit (EXECUTION_SUCCESS);
4009 else
4010 exit (EXECUTION_FAILURE);
4011 }
4012 else
4013 {
4014 close_pipes (pipe_in, pipe_out);
4015#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
ac50fbac
CR
4016 if (pipe_out == NO_PIPE)
4017 unlink_fifo_list ();
ccc6cda3
JA
4018#endif
4019 return (EXECUTION_SUCCESS);
4020 }
4021 }
4022 else
4023 {
4024 /* Even if there aren't any command names, pretend to do the
4025 redirections that are specified. The user expects the side
4026 effects to take place. If the redirections fail, then return
4027 failure. Otherwise, if a command substitution took place while
4028 expanding the command or a redirection, return the value of that
4029 substitution. Otherwise, return EXECUTION_SUCCESS. */
4030
b80f6443
JA
4031 r = do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE);
4032 cleanup_redirects (redirection_undo_list);
4033 redirection_undo_list = (REDIRECT *)NULL;
4034
4035 if (r != 0)
ccc6cda3 4036 return (EXECUTION_FAILURE);
95732b49 4037 else if (last_command_subst_pid != NO_PID)
ccc6cda3
JA
4038 return (last_command_exit_value);
4039 else
4040 return (EXECUTION_SUCCESS);
4041 }
4042}
4043
4044/* This is a hack to suppress word splitting for assignment statements
4045 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
4046static void
4047fix_assignment_words (words)
4048 WORD_LIST *words;
4049{
ac50fbac 4050 WORD_LIST *w, *wcmd;
ccc6cda3 4051 struct builtin *b;
ac50fbac 4052 int assoc, global, array, integer;
ccc6cda3
JA
4053
4054 if (words == 0)
4055 return;
4056
7117c2d2 4057 b = 0;
ac50fbac 4058 assoc = global = array = integer = 0;
ccc6cda3 4059
ac50fbac
CR
4060 /* Skip over assignment statements preceding a command name */
4061 wcmd = words;
4062 for (wcmd = words; wcmd; wcmd = wcmd->next)
4063 if ((wcmd->word->flags & W_ASSIGNMENT) == 0)
4064 break;
a0c0a00f
CR
4065 /* Posix (post-2008) says that `command' doesn't change whether
4066 or not the builtin it shadows is a `declaration command', even
4067 though it removes other special builtin properties. In Posix
4068 mode, we skip over one or more instances of `command' and
4069 deal with the next word as the assignment builtin. */
4070 while (posixly_correct && wcmd && wcmd->word && wcmd->word->word && STREQ (wcmd->word->word, "command"))
4071 wcmd = wcmd->next;
ac50fbac
CR
4072
4073 for (w = wcmd; w; w = w->next)
ccc6cda3 4074 if (w->word->flags & W_ASSIGNMENT)
7117c2d2 4075 {
a0c0a00f 4076 /* Lazy builtin lookup, only do it if we find an assignment */
7117c2d2
JA
4077 if (b == 0)
4078 {
ac50fbac 4079 b = builtin_address_internal (wcmd->word->word, 0);
7117c2d2
JA
4080 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4081 return;
95732b49 4082 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
ac50fbac 4083 wcmd->word->flags |= W_ASSNBLTIN;
7117c2d2 4084 }
95732b49 4085 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP|W_ASSIGNARG);
3185942a
JA
4086#if defined (ARRAY_VARS)
4087 if (assoc)
4088 w->word->flags |= W_ASSIGNASSOC;
ac50fbac
CR
4089 if (array)
4090 w->word->flags |= W_ASSIGNARRAY;
4091#endif
6d41b715
CR
4092 if (global)
4093 w->word->flags |= W_ASSNGLOBAL;
a0c0a00f
CR
4094
4095 /* If we have an assignment builtin that does not create local variables,
4096 make sure we create global variables even if we internally call
d233b485
CR
4097 `declare'. The CHKLOCAL flag means to set attributes or values on
4098 an existing local variable, if there is one. */
a0c0a00f 4099 if (b && ((b->flags & (ASSIGNMENT_BUILTIN|LOCALVAR_BUILTIN)) == ASSIGNMENT_BUILTIN))
d233b485
CR
4100 w->word->flags |= W_ASSNGLOBAL|W_CHKLOCAL;
4101#if 0
4102 else if (b && (b->flags & ASSIGNMENT_BUILTIN) && (b->flags & LOCALVAR_BUILTIN))
4103 w->word->flags |= W_CHKLOCAL;
4104#endif
7117c2d2 4105 }
3185942a
JA
4106#if defined (ARRAY_VARS)
4107 /* Note that we saw an associative array option to a builtin that takes
4108 assignment statements. This is a bit of a kludge. */
a0c0a00f 4109 else if (w->word->word[0] == '-' && (strpbrk (w->word->word+1, "Aag") != 0))
6d41b715
CR
4110#else
4111 else if (w->word->word[0] == '-' && strchr (w->word->word+1, 'g'))
4112#endif
3185942a
JA
4113 {
4114 if (b == 0)
4115 {
ac50fbac 4116 b = builtin_address_internal (wcmd->word->word, 0);
3185942a
JA
4117 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
4118 return;
4119 else if (b && (b->flags & ASSIGNMENT_BUILTIN))
ac50fbac 4120 wcmd->word->flags |= W_ASSNBLTIN;
3185942a 4121 }
ac50fbac 4122 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'A'))
3185942a 4123 assoc = 1;
ac50fbac
CR
4124 else if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'a'))
4125 array = 1;
4126 if ((wcmd->word->flags & W_ASSNBLTIN) && strchr (w->word->word+1, 'g'))
6d41b715 4127 global = 1;
3185942a 4128 }
3185942a
JA
4129}
4130
4131/* Return 1 if the file found by searching $PATH for PATHNAME, defaulting
4132 to PATHNAME, is a directory. Used by the autocd code below. */
4133static int
4134is_dirname (pathname)
4135 char *pathname;
4136{
4137 char *temp;
ac50fbac
CR
4138 int ret;
4139
4140 temp = search_for_command (pathname, 0);
a0c0a00f 4141 ret = temp ? file_isdir (temp) : file_isdir (pathname);
ac50fbac
CR
4142 free (temp);
4143 return ret;
ccc6cda3
JA
4144}
4145
726f6388
JA
4146/* The meaty part of all the executions. We have to start hacking the
4147 real execution of commands here. Fork a process, set things up,
4148 execute the command. */
ccc6cda3 4149static int
726f6388
JA
4150execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
4151 SIMPLE_COM *simple_command;
4152 int pipe_in, pipe_out, async;
4153 struct fd_bitmap *fds_to_close;
4154{
4155 WORD_LIST *words, *lastword;
ccc6cda3 4156 char *command_line, *lastarg, *temp;
bc4cd23c 4157 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
95732b49 4158 pid_t old_last_async_pid;
f73dda09 4159 sh_builtin_func_t *builtin;
ccc6cda3 4160 SHELL_VAR *func;
495aee44 4161 volatile int old_builtin, old_command_builtin;
726f6388
JA
4162
4163 result = EXECUTION_SUCCESS;
ccc6cda3 4164 special_builtin_failed = builtin_is_special = 0;
cce855bc 4165 command_line = (char *)0;
726f6388 4166
ac50fbac
CR
4167 QUIT;
4168
ccc6cda3 4169 /* If we're in a function, update the line number information. */
0001803f 4170 if (variable_context && interactive_shell && sourcelevel == 0)
a0c0a00f 4171 {
d233b485
CR
4172 /* line numbers in a function start at 1 */
4173 line_number -= function_line_number - 1;
4174 if (line_number <= 0)
4175 line_number = 1;
a0c0a00f 4176 }
7117c2d2 4177
726f6388
JA
4178 /* Remember what this command line looks like at invocation. */
4179 command_string_index = 0;
4180 print_simple_command (simple_command);
726f6388 4181
0628567a 4182#if 0
95732b49 4183 if (signal_in_progress (DEBUG_TRAP) == 0 && (this_command_name == 0 || (STREQ (this_command_name, "trap") == 0)))
0628567a
JA
4184#else
4185 if (signal_in_progress (DEBUG_TRAP) == 0 && running_trap == 0)
4186#endif
b80f6443
JA
4187 {
4188 FREE (the_printed_command_except_trap);
95732b49 4189 the_printed_command_except_trap = the_printed_command ? savestring (the_printed_command) : (char *)0;
b80f6443
JA
4190 }
4191
4192 /* Run the debug trap before each simple command, but do it after we
4193 update the line number information. */
4194 result = run_debug_trap ();
4195#if defined (DEBUGGER)
4196 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4197 skip the command. */
4198 if (debugging_mode && result != EXECUTION_SUCCESS)
4199 return (EXECUTION_SUCCESS);
4200#endif
4201
726f6388 4202 first_word_quoted =
3185942a 4203 simple_command->words ? (simple_command->words->word->flags & W_QUOTED) : 0;
726f6388 4204
95732b49 4205 last_command_subst_pid = NO_PID;
b72432fd 4206 old_last_async_pid = last_asynchronous_pid;
726f6388 4207
d233b485 4208 already_forked = 0;
bc4cd23c
JA
4209
4210 /* If we're in a pipeline or run in the background, set DOFORK so we
4211 make the child early, before word expansion. This keeps assignment
4212 statements from affecting the parent shell's environment when they
4213 should not. */
4214 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
4215
4216 /* Something like `%2 &' should restart job 2 in the background, not cause
4217 the shell to fork here. */
4218 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
4219 simple_command->words && simple_command->words->word &&
4220 simple_command->words->word->word &&
4221 (simple_command->words->word->word[0] == '%'))
4222 dofork = 0;
4223
4224 if (dofork)
cce855bc 4225 {
d233b485
CR
4226 char *p;
4227
bb70624e
JA
4228 /* Do this now, because execute_disk_command will do it anyway in the
4229 vast majority of cases. */
4230 maybe_make_export_env ();
4231
95732b49
JA
4232 /* Don't let a DEBUG trap overwrite the command string to be saved with
4233 the process/job associated with this child. */
d233b485 4234 if (make_child (p = savestring (the_printed_command_except_trap), async) == 0)
cce855bc
JA
4235 {
4236 already_forked = 1;
4237 simple_command->flags |= CMD_NO_FORK;
4238
a0c0a00f 4239 subshell_environment = SUBSHELL_FORK; /* XXX */
95732b49
JA
4240 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
4241 subshell_environment |= SUBSHELL_PIPE;
4242 if (async)
4243 subshell_environment |= SUBSHELL_ASYNC;
28ef6c31 4244
bb70624e
JA
4245 /* We need to do this before piping to handle some really
4246 pathological cases where one of the pipe file descriptors
4247 is < 2. */
4248 if (fds_to_close)
4249 close_fd_bitmap (fds_to_close);
4250
a0c0a00f
CR
4251 /* If we fork because of an input pipe, note input pipe for later to
4252 inhibit async commands from redirecting stdin from /dev/null */
4253 stdin_redir |= pipe_in != NO_PIPE;
4254
cce855bc 4255 do_piping (pipe_in, pipe_out);
f73dda09 4256 pipe_in = pipe_out = NO_PIPE;
3185942a
JA
4257#if defined (COPROCESS_SUPPORT)
4258 coproc_closeall ();
4259#endif
cce855bc 4260
b72432fd 4261 last_asynchronous_pid = old_last_async_pid;
ac50fbac
CR
4262
4263 CHECK_SIGTERM;
a0c0a00f
CR
4264
4265 if (async)
4266 subshell_level++; /* not for pipes yet */
d233b485
CR
4267
4268#if defined (JOB_CONTROL)
4269 FREE (p); /* child doesn't use pointer */
4270#endif
cce855bc
JA
4271 }
4272 else
4273 {
495aee44
CR
4274 /* Don't let simple commands that aren't the last command in a
4275 pipeline change $? for the rest of the pipeline (or at all). */
4276 if (pipe_out != NO_PIPE)
4277 result = last_command_exit_value;
cce855bc
JA
4278 close_pipes (pipe_in, pipe_out);
4279#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
d233b485 4280#if 0
ac50fbac
CR
4281 /* Close /dev/fd file descriptors in the parent after forking the
4282 last child in a (possibly one-element) pipeline. Defer this
4283 until any running shell function completes. */
4284 if (pipe_out == NO_PIPE && variable_context == 0) /* XXX */
4285 unlink_fifo_list (); /* XXX */
d233b485 4286#endif
cce855bc
JA
4287#endif
4288 command_line = (char *)NULL; /* don't free this. */
d233b485 4289#if 0
cce855bc 4290 bind_lastarg ((char *)NULL);
d233b485 4291#endif
cce855bc
JA
4292 return (result);
4293 }
4294 }
4295
a0c0a00f
CR
4296 QUIT; /* XXX */
4297
726f6388
JA
4298 /* If we are re-running this as the result of executing the `command'
4299 builtin, do not expand the command words a second time. */
4300 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
4301 {
4302 current_fds_to_close = fds_to_close;
ccc6cda3 4303 fix_assignment_words (simple_command->words);
3185942a
JA
4304 /* Pass the ignore return flag down to command substitutions */
4305 if (simple_command->flags & CMD_IGNORE_RETURN) /* XXX */
4306 comsub_ignore_return++;
726f6388 4307 words = expand_words (simple_command->words);
3185942a
JA
4308 if (simple_command->flags & CMD_IGNORE_RETURN)
4309 comsub_ignore_return--;
726f6388
JA
4310 current_fds_to_close = (struct fd_bitmap *)NULL;
4311 }
4312 else
4313 words = copy_word_list (simple_command->words);
4314
726f6388
JA
4315 /* It is possible for WORDS not to have anything left in it.
4316 Perhaps all the words consisted of `$foo', and there was
4317 no variable `$foo'. */
ccc6cda3 4318 if (words == 0)
726f6388 4319 {
b80f6443 4320 this_command_name = 0;
ccc6cda3 4321 result = execute_null_command (simple_command->redirects,
cce855bc 4322 pipe_in, pipe_out,
95732b49 4323 already_forked ? 0 : async);
cce855bc 4324 if (already_forked)
a0c0a00f 4325 sh_exit (result);
cce855bc
JA
4326 else
4327 {
4328 bind_lastarg ((char *)NULL);
4329 set_pipestatus_from_exit (result);
4330 return (result);
4331 }
ccc6cda3 4332 }
726f6388 4333
ccc6cda3 4334 lastarg = (char *)NULL;
726f6388 4335
ccc6cda3 4336 begin_unwind_frame ("simple-command");
726f6388 4337
ccc6cda3 4338 if (echo_command_at_execute)
b80f6443 4339 xtrace_print_word_list (words, 1);
726f6388 4340
f73dda09 4341 builtin = (sh_builtin_func_t *)NULL;
ccc6cda3
JA
4342 func = (SHELL_VAR *)NULL;
4343 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
4344 {
4345 /* Posix.2 says special builtins are found before functions. We
4346 don't set builtin_is_special anywhere other than here, because
4347 this path is followed only when the `command' builtin is *not*
4348 being used, and we don't want to exit the shell if a special
4349 builtin executed with `command builtin' fails. `command' is not
4350 a special builtin. */
4351 if (posixly_correct)
4352 {
4353 builtin = find_special_builtin (words->word->word);
4354 if (builtin)
4355 builtin_is_special = 1;
726f6388 4356 }
ccc6cda3 4357 if (builtin == 0)
726f6388 4358 func = find_function (words->word->word);
ccc6cda3 4359 }
726f6388 4360
b80f6443
JA
4361 /* In POSIX mode, assignment errors in the temporary environment cause a
4362 non-interactive shell to exit. */
ac50fbac 4363 if (posixly_correct && builtin_is_special && interactive_shell == 0 && tempenv_assign_error)
b80f6443
JA
4364 {
4365 last_command_exit_value = EXECUTION_FAILURE;
4366 jump_to_top_level (ERREXIT);
4367 }
ac50fbac 4368 tempenv_assign_error = 0; /* don't care about this any more */
b80f6443 4369
ccc6cda3
JA
4370 add_unwind_protect (dispose_words, words);
4371 QUIT;
726f6388 4372
ccc6cda3
JA
4373 /* Bind the last word in this command to "$_" after execution. */
4374 for (lastword = words; lastword->next; lastword = lastword->next)
4375 ;
4376 lastarg = lastword->word->word;
726f6388
JA
4377
4378#if defined (JOB_CONTROL)
ccc6cda3 4379 /* Is this command a job control related thing? */
cce855bc 4380 if (words->word->word[0] == '%' && already_forked == 0)
ccc6cda3
JA
4381 {
4382 this_command_name = async ? "bg" : "fg";
726f6388 4383 last_shell_builtin = this_shell_builtin;
ccc6cda3
JA
4384 this_shell_builtin = builtin_address (this_command_name);
4385 result = (*this_shell_builtin) (words);
4386 goto return_result;
4387 }
726f6388 4388
ac50fbac 4389 /* One other possibililty. The user may want to resume an existing job.
ccc6cda3
JA
4390 If they do, find out whether this word is a candidate for a running
4391 job. */
cce855bc 4392 if (job_control && already_forked == 0 && async == 0 &&
ccc6cda3
JA
4393 !first_word_quoted &&
4394 !words->next &&
4395 words->word->word[0] &&
4396 !simple_command->redirects &&
4397 pipe_in == NO_PIPE &&
4398 pipe_out == NO_PIPE &&
4399 (temp = get_string_value ("auto_resume")))
4400 {
7117c2d2 4401 int job, jflags, started_status;
ccc6cda3 4402
7117c2d2
JA
4403 jflags = JM_STOPPED|JM_FIRSTMATCH;
4404 if (STREQ (temp, "exact"))
4405 jflags |= JM_EXACT;
4406 else if (STREQ (temp, "substring"))
4407 jflags |= JM_SUBSTRING;
4408 else
4409 jflags |= JM_PREFIX;
4410 job = get_job_by_name (words->word->word, jflags);
4411 if (job != NO_JOB)
726f6388 4412 {
7117c2d2
JA
4413 run_unwind_frame ("simple-command");
4414 this_command_name = "fg";
4415 last_shell_builtin = this_shell_builtin;
4416 this_shell_builtin = builtin_address ("fg");
ccc6cda3 4417
7117c2d2
JA
4418 started_status = start_job (job, 1);
4419 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
726f6388 4420 }
ccc6cda3
JA
4421 }
4422#endif /* JOB_CONTROL */
726f6388 4423
3185942a 4424run_builtin:
ccc6cda3
JA
4425 /* Remember the name of this command globally. */
4426 this_command_name = words->word->word;
726f6388 4427
ccc6cda3
JA
4428 QUIT;
4429
4430 /* This command could be a shell builtin or a user-defined function.
4431 We have already found special builtins by this time, so we do not
4432 set builtin_is_special. If this is a function or builtin, and we
4433 have pipes, then fork a subshell in here. Otherwise, just execute
4434 the command directly. */
4435 if (func == 0 && builtin == 0)
4436 builtin = find_shell_builtin (this_command_name);
4437
4438 last_shell_builtin = this_shell_builtin;
4439 this_shell_builtin = builtin;
4440
4441 if (builtin || func)
726f6388 4442 {
3185942a 4443 if (builtin)
495aee44
CR
4444 {
4445 old_builtin = executing_builtin;
4446 old_command_builtin = executing_command_builtin;
4447 unwind_protect_int (executing_builtin); /* modified in execute_builtin */
4448 unwind_protect_int (executing_command_builtin); /* ditto */
4449 }
28ef6c31 4450 if (already_forked)
726f6388 4451 {
cce855bc 4452 /* reset_terminating_signals (); */ /* XXX */
495aee44
CR
4453 /* Reset the signal handlers in the child, but don't free the
4454 trap strings. Set a flag noting that we have to free the
4455 trap strings if we run trap to change a signal disposition. */
4456 reset_signal_handlers ();
4457 subshell_environment |= SUBSHELL_RESETTRAP;
726f6388 4458
cce855bc 4459 if (async)
ccc6cda3 4460 {
cce855bc
JA
4461 if ((simple_command->flags & CMD_STDIN_REDIR) &&
4462 pipe_in == NO_PIPE &&
4463 (stdin_redirects (simple_command->redirects) == 0))
4464 async_redirect_stdin ();
4465 setup_async_signals ();
ccc6cda3 4466 }
cce855bc 4467
a0c0a00f
CR
4468 if (async == 0)
4469 subshell_level++;
cce855bc
JA
4470 execute_subshell_builtin_or_function
4471 (words, simple_command->redirects, builtin, func,
4472 pipe_in, pipe_out, async, fds_to_close,
4473 simple_command->flags);
b80f6443 4474 subshell_level--;
726f6388
JA
4475 }
4476 else
4477 {
ccc6cda3
JA
4478 result = execute_builtin_or_function
4479 (words, builtin, func, simple_command->redirects, fds_to_close,
4480 simple_command->flags);
4481 if (builtin)
4482 {
4483 if (result > EX_SHERRBASE)
4484 {
ac50fbac
CR
4485 switch (result)
4486 {
4487 case EX_REDIRFAIL:
4488 case EX_BADASSIGN:
4489 case EX_EXPFAIL:
4490 /* These errors cause non-interactive posix mode shells to exit */
4491 if (posixly_correct && builtin_is_special && interactive_shell == 0)
4492 {
4493 last_command_exit_value = EXECUTION_FAILURE;
4494 jump_to_top_level (ERREXIT);
4495 }
d233b485
CR
4496 break;
4497 case EX_DISKFALLBACK:
4498 /* XXX - experimental */
4499 executing_builtin = old_builtin;
4500 executing_command_builtin = old_command_builtin;
4501 builtin = 0;
4502 /* XXX - redirections will have to be performed again */
4503 goto execute_from_filesystem;
ac50fbac 4504 }
cce855bc
JA
4505 result = builtin_status (result);
4506 if (builtin_is_special)
d233b485 4507 special_builtin_failed = 1; /* XXX - take command builtin into account? */
ccc6cda3
JA
4508 }
4509 /* In POSIX mode, if there are assignment statements preceding
4510 a special builtin, they persist after the builtin
4511 completes. */
4512 if (posixly_correct && builtin_is_special && temporary_env)
4513 merge_temporary_env ();
4514 }
4515 else /* function */
4516 {
4517 if (result == EX_USAGE)
4518 result = EX_BADUSAGE;
4519 else if (result > EX_SHERRBASE)
cce855bc 4520 result = EXECUTION_FAILURE;
ccc6cda3
JA
4521 }
4522
cce855bc
JA
4523 set_pipestatus_from_exit (result);
4524
726f6388
JA
4525 goto return_result;
4526 }
4527 }
726f6388 4528
3185942a
JA
4529 if (autocd && interactive && words->word && is_dirname (words->word->word))
4530 {
a0c0a00f 4531 words = make_word_list (make_word ("--"), words);
3185942a
JA
4532 words = make_word_list (make_word ("cd"), words);
4533 xtrace_print_word_list (words, 0);
a0c0a00f 4534 func = find_function ("cd");
3185942a
JA
4535 goto run_builtin;
4536 }
4537
d233b485 4538execute_from_filesystem:
cce855bc 4539 if (command_line == 0)
ac50fbac 4540 command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
cce855bc 4541
f1be666c 4542#if defined (PROCESS_SUBSTITUTION)
a0c0a00f
CR
4543 /* The old code did not test already_forked and only did this if
4544 subshell_environment&SUBSHELL_COMSUB != 0 (comsubs and procsubs). Other
4545 uses of the no-fork optimization left FIFOs in $TMPDIR */
4546 if (already_forked == 0 && (simple_command->flags & CMD_NO_FORK) && fifos_pending() > 0)
f1be666c
JA
4547 simple_command->flags &= ~CMD_NO_FORK;
4548#endif
495aee44 4549 result = execute_disk_command (words, simple_command->redirects, command_line,
ccc6cda3 4550 pipe_in, pipe_out, async, fds_to_close,
d166f048 4551 simple_command->flags);
726f6388
JA
4552
4553 return_result:
4554 bind_lastarg (lastarg);
ccc6cda3 4555 FREE (command_line);
b80f6443 4556 dispose_words (words);
495aee44
CR
4557 if (builtin)
4558 {
4559 executing_builtin = old_builtin;
4560 executing_command_builtin = old_command_builtin;
4561 }
b80f6443
JA
4562 discard_unwind_frame ("simple-command");
4563 this_command_name = (char *)NULL; /* points to freed memory now */
726f6388
JA
4564 return (result);
4565}
4566
ccc6cda3
JA
4567/* Translate the special builtin exit statuses. We don't really need a
4568 function for this; it's a placeholder for future work. */
4569static int
4570builtin_status (result)
4571 int result;
4572{
4573 int r;
4574
4575 switch (result)
4576 {
4577 case EX_USAGE:
4578 r = EX_BADUSAGE;
4579 break;
4580 case EX_REDIRFAIL:
4581 case EX_BADSYNTAX:
4582 case EX_BADASSIGN:
4583 case EX_EXPFAIL:
4584 r = EXECUTION_FAILURE;
4585 break;
4586 default:
4587 r = EXECUTION_SUCCESS;
4588 break;
4589 }
4590 return (r);
4591}
4592
726f6388
JA
4593static int
4594execute_builtin (builtin, words, flags, subshell)
f73dda09 4595 sh_builtin_func_t *builtin;
726f6388
JA
4596 WORD_LIST *words;
4597 int flags, subshell;
4598{
d233b485
CR
4599 int result, eval_unwind, ignexit_flag;
4600 int isbltinenv, should_keep;
0001803f 4601 char *error_trap;
726f6388 4602
0001803f 4603 error_trap = 0;
d233b485 4604 should_keep = 0;
a0c0a00f 4605
726f6388
JA
4606 /* The eval builtin calls parse_and_execute, which does not know about
4607 the setting of flags, and always calls the execution functions with
4608 flags that will exit the shell on an error if -e is set. If the
4609 eval builtin is being called, and we're supposed to ignore the exit
0001803f
CR
4610 value of the command, we turn the -e flag off ourselves and disable
4611 the ERR trap, then restore them when the command completes. This is
4612 also a problem (as below) for the command and source/. builtins. */
3185942a
JA
4613 if (subshell == 0 && (flags & CMD_IGNORE_RETURN) &&
4614 (builtin == eval_builtin || builtin == command_builtin || builtin == source_builtin))
726f6388
JA
4615 {
4616 begin_unwind_frame ("eval_builtin");
4617 unwind_protect_int (exit_immediately_on_error);
ac50fbac 4618 unwind_protect_int (builtin_ignoring_errexit);
0001803f
CR
4619 error_trap = TRAP_STRING (ERROR_TRAP);
4620 if (error_trap)
4621 {
4622 error_trap = savestring (error_trap);
4623 add_unwind_protect (xfree, error_trap);
4624 add_unwind_protect (set_error_trap, error_trap);
4625 restore_default_signal (ERROR_TRAP);
4626 }
726f6388 4627 exit_immediately_on_error = 0;
a0c0a00f 4628 ignexit_flag = builtin_ignoring_errexit;
ac50fbac 4629 builtin_ignoring_errexit = 1;
d166f048 4630 eval_unwind = 1;
726f6388 4631 }
d166f048
JA
4632 else
4633 eval_unwind = 0;
726f6388
JA
4634
4635 /* The temporary environment for a builtin is supposed to apply to
4636 all commands executed by that builtin. Currently, this is a
ac50fbac
CR
4637 problem only with the `unset', `source' and `eval' builtins.
4638 `mapfile' is a special case because it uses evalstring (same as
4639 eval or source) to run its callbacks. */
d233b485
CR
4640 /* SHOULD_KEEP is for the pop_scope call below; it only matters when
4641 posixly_correct is set, but we should propagate the temporary environment
4642 to the enclosing environment only for special builtins. */
ac50fbac 4643 isbltinenv = (builtin == source_builtin || builtin == eval_builtin || builtin == unset_builtin || builtin == mapfile_builtin);
d233b485
CR
4644 should_keep = isbltinenv && builtin != mapfile_builtin;
4645#if defined (HISTORY) && defined (READLINE)
4646 if (builtin == fc_builtin || builtin == read_builtin)
4647 {
4648 isbltinenv = 1;
4649 should_keep = 0;
4650 }
4651#endif
95732b49 4652
7117c2d2 4653 if (isbltinenv)
726f6388
JA
4654 {
4655 if (subshell == 0)
4656 begin_unwind_frame ("builtin_env");
4657
4658 if (temporary_env)
4659 {
7117c2d2 4660 push_scope (VC_BLTNENV, temporary_env);
d233b485
CR
4661 if (flags & CMD_COMMAND_BUILTIN)
4662 should_keep = 0;
726f6388 4663 if (subshell == 0)
d233b485 4664 add_unwind_protect (pop_scope, should_keep ? "1" : 0);
7117c2d2 4665 temporary_env = (HASH_TABLE *)NULL;
726f6388 4666 }
28ef6c31
JA
4667 }
4668
a0c0a00f
CR
4669 if (subshell == 0 && builtin == eval_builtin)
4670 {
4671 if (evalnest_max > 0 && evalnest >= evalnest_max)
4672 {
4673 internal_error (_("eval: maximum eval nesting level exceeded (%d)"), evalnest);
4674 evalnest = 0;
4675 jump_to_top_level (DISCARD);
4676 }
4677 unwind_protect_int (evalnest);
4678 /* The test for subshell == 0 above doesn't make a difference */
4679 evalnest++; /* execute_subshell_builtin_or_function sets this to 0 */
4680 }
4681 else if (subshell == 0 && builtin == source_builtin)
4682 {
4683 if (sourcenest_max > 0 && sourcenest >= sourcenest_max)
4684 {
4685 internal_error (_("%s: maximum source nesting level exceeded (%d)"), this_command_name, sourcenest);
4686 sourcenest = 0;
4687 jump_to_top_level (DISCARD);
4688 }
4689 unwind_protect_int (sourcenest);
4690 /* The test for subshell == 0 above doesn't make a difference */
4691 sourcenest++; /* execute_subshell_builtin_or_function sets this to 0 */
4692 }
4693
28ef6c31
JA
4694 /* `return' does a longjmp() back to a saved environment in execute_function.
4695 If a variable assignment list preceded the command, and the shell is
4696 running in POSIX mode, we need to merge that into the shell_variables
d233b485
CR
4697 table, since `return' is a POSIX special builtin. We don't do this if
4698 it's being run by the `command' builtin, since that's supposed to inhibit
4699 the special builtin properties. */
4700 if (posixly_correct && subshell == 0 && builtin == return_builtin && (flags & CMD_COMMAND_BUILTIN) == 0 && temporary_env)
28ef6c31
JA
4701 {
4702 begin_unwind_frame ("return_temp_env");
4703 add_unwind_protect (merge_temporary_env, (char *)NULL);
726f6388
JA
4704 }
4705
3185942a 4706 executing_builtin++;
495aee44 4707 executing_command_builtin |= builtin == command_builtin;
726f6388
JA
4708 result = ((*builtin) (words->next));
4709
28ef6c31
JA
4710 /* This shouldn't happen, but in case `return' comes back instead of
4711 longjmp'ing, we need to unwind. */
4712 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
4713 discard_unwind_frame ("return_temp_env");
4714
7117c2d2
JA
4715 if (subshell == 0 && isbltinenv)
4716 run_unwind_frame ("builtin_env");
726f6388 4717
d166f048 4718 if (eval_unwind)
726f6388 4719 {
a0c0a00f
CR
4720 builtin_ignoring_errexit = ignexit_flag;
4721 exit_immediately_on_error = builtin_ignoring_errexit ? 0 : errexit_flag;
0001803f
CR
4722 if (error_trap)
4723 {
4724 set_error_trap (error_trap);
d233b485 4725 free (error_trap);
0001803f 4726 }
726f6388
JA
4727 discard_unwind_frame ("eval_builtin");
4728 }
4729
4730 return (result);
4731}
4732
a0c0a00f
CR
4733static void
4734maybe_restore_getopt_state (gs)
4735 sh_getopt_state_t *gs;
4736{
a0c0a00f
CR
4737 /* If we have a local copy of OPTIND and it's at the right (current)
4738 context, then we restore getopt's internal state. If not, we just
4739 let it go. We know there is a local OPTIND if gs->gs_flags & 1.
4740 This is set below in execute_function() before the context is run. */
4741 if (gs->gs_flags & 1)
4742 sh_getopt_restore_istate (gs);
4743 else
4744 free (gs);
4745}
4746
4747#if defined (ARRAY_VARS)
4748void
4749restore_funcarray_state (fa)
4750 struct func_array_state *fa;
4751{
4752 SHELL_VAR *nfv;
4753 ARRAY *funcname_a;
4754
4755 array_pop (fa->source_a);
4756 array_pop (fa->lineno_a);
4757
4758 GET_ARRAY_FROM_VAR ("FUNCNAME", nfv, funcname_a);
4759 if (nfv == fa->funcname_v)
4760 array_pop (funcname_a);
4761
4762 free (fa);
4763}
4764#endif
4765
726f6388
JA
4766static int
4767execute_function (var, words, flags, fds_to_close, async, subshell)
4768 SHELL_VAR *var;
4769 WORD_LIST *words;
f73dda09 4770 int flags;
726f6388 4771 struct fd_bitmap *fds_to_close;
f73dda09 4772 int async, subshell;
726f6388
JA
4773{
4774 int return_val, result;
b80f6443
JA
4775 COMMAND *tc, *fc, *save_current;
4776 char *debug_trap, *error_trap, *return_trap;
4777#if defined (ARRAY_VARS)
a0c0a00f 4778 SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
495aee44
CR
4779 ARRAY *funcname_a;
4780 volatile ARRAY *bash_source_a;
4781 volatile ARRAY *bash_lineno_a;
a0c0a00f 4782 struct func_array_state *fa;
b80f6443
JA
4783#endif
4784 FUNCTION_DEF *shell_fn;
4785 char *sfile, *t;
a0c0a00f
CR
4786 sh_getopt_state_t *gs;
4787 SHELL_VAR *gv;
f73dda09
JA
4788
4789 USE_VAR(fc);
726f6388 4790
0001803f
CR
4791 if (funcnest_max > 0 && funcnest >= funcnest_max)
4792 {
ac50fbac 4793 internal_error (_("%s: maximum function nesting level exceeded (%d)"), var->name, funcnest);
495aee44 4794 funcnest = 0; /* XXX - should we reset it somewhere else? */
0001803f
CR
4795 jump_to_top_level (DISCARD);
4796 }
0001803f 4797
b80f6443
JA
4798#if defined (ARRAY_VARS)
4799 GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
4800 GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
4801 GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
4802#endif
4803
726f6388
JA
4804 tc = (COMMAND *)copy_command (function_cell (var));
4805 if (tc && (flags & CMD_IGNORE_RETURN))
4806 tc->flags |= CMD_IGNORE_RETURN;
4807
a0c0a00f 4808 gs = sh_getopt_save_istate ();
726f6388
JA
4809 if (subshell == 0)
4810 {
ccc6cda3 4811 begin_unwind_frame ("function_calling");
d233b485
CR
4812 /* If the shell is in posix mode, this will push the variables in
4813 the temporary environment to the "current shell environment" (the
4814 global scope), and dispose the temporary env before setting it to
4815 NULL later. This behavior has disappeared from the latest edition
4816 of the standard, so I will eventually remove it from variables.c:
4817 push_var_context. */
7117c2d2 4818 push_context (var->name, subshell, temporary_env);
a0c0a00f
CR
4819 /* This has to be before the pop_context(), because the unwinding of
4820 local variables may cause the restore of a local declaration of
4821 OPTIND to force a getopts state reset. */
4822 add_unwind_protect (maybe_restore_getopt_state, gs);
726f6388
JA
4823 add_unwind_protect (pop_context, (char *)NULL);
4824 unwind_protect_int (line_number);
a0c0a00f
CR
4825 unwind_protect_int (line_number_for_err_trap);
4826 unwind_protect_int (function_line_number);
ccc6cda3
JA
4827 unwind_protect_int (return_catch_flag);
4828 unwind_protect_jmp_buf (return_catch);
4829 add_unwind_protect (dispose_command, (char *)tc);
bb70624e 4830 unwind_protect_pointer (this_shell_function);
0001803f 4831 unwind_protect_int (funcnest);
a0c0a00f 4832 unwind_protect_int (loop_level);
726f6388 4833 }
7117c2d2
JA
4834 else
4835 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
4836
4837 temporary_env = (HASH_TABLE *)NULL;
726f6388 4838
bb70624e
JA
4839 this_shell_function = var;
4840 make_funcname_visible (1);
4841
f73dda09
JA
4842 debug_trap = TRAP_STRING(DEBUG_TRAP);
4843 error_trap = TRAP_STRING(ERROR_TRAP);
b80f6443 4844 return_trap = TRAP_STRING(RETURN_TRAP);
f73dda09 4845
b80f6443
JA
4846 /* The order of the unwind protects for debug_trap, error_trap and
4847 return_trap is important here! unwind-protect commands are run
4848 in reverse order of registration. If this causes problems, take
4849 out the xfree unwind-protect calls and live with the small memory leak. */
4850
4851 /* function_trace_mode != 0 means that all functions inherit the DEBUG trap.
4852 if the function has the trace attribute set, it inherits the DEBUG trap */
4853 if (debug_trap && ((trace_p (var) == 0) && function_trace_mode == 0))
ccc6cda3
JA
4854 {
4855 if (subshell == 0)
4856 {
4857 debug_trap = savestring (debug_trap);
cce855bc 4858 add_unwind_protect (xfree, debug_trap);
a0c0a00f 4859 add_unwind_protect (maybe_set_debug_trap, debug_trap);
ccc6cda3
JA
4860 }
4861 restore_default_signal (DEBUG_TRAP);
4862 }
726f6388 4863
b80f6443
JA
4864 /* error_trace_mode != 0 means that functions inherit the ERR trap. */
4865 if (error_trap && error_trace_mode == 0)
f73dda09
JA
4866 {
4867 if (subshell == 0)
4868 {
4869 error_trap = savestring (error_trap);
4870 add_unwind_protect (xfree, error_trap);
a0c0a00f 4871 add_unwind_protect (maybe_set_error_trap, error_trap);
f73dda09
JA
4872 }
4873 restore_default_signal (ERROR_TRAP);
4874 }
4875
95732b49
JA
4876 /* Shell functions inherit the RETURN trap if function tracing is on
4877 globally or on individually for this function. */
95732b49 4878 if (return_trap && (signal_in_progress (DEBUG_TRAP) || ((trace_p (var) == 0) && function_trace_mode == 0)))
b80f6443
JA
4879 {
4880 if (subshell == 0)
4881 {
4882 return_trap = savestring (return_trap);
4883 add_unwind_protect (xfree, return_trap);
a0c0a00f 4884 add_unwind_protect (maybe_set_return_trap, return_trap);
b80f6443
JA
4885 }
4886 restore_default_signal (RETURN_TRAP);
4887 }
4888
4889 funcnest++;
4890#if defined (ARRAY_VARS)
4891 /* This is quite similar to the code in shell.c and elsewhere. */
4892 shell_fn = find_function_def (this_shell_function->name);
4893 sfile = shell_fn ? shell_fn->source_file : "";
ac50fbac 4894 array_push ((ARRAY *)funcname_a, this_shell_function->name);
b80f6443 4895
ac50fbac 4896 array_push ((ARRAY *)bash_source_a, sfile);
b80f6443 4897 t = itos (executing_line_number ());
ac50fbac 4898 array_push ((ARRAY *)bash_lineno_a, t);
b80f6443
JA
4899 free (t);
4900#endif
4901
a0c0a00f
CR
4902#if defined (ARRAY_VARS)
4903 fa = (struct func_array_state *)xmalloc (sizeof (struct func_array_state));
4904 fa->source_a = (ARRAY *)bash_source_a;
4905 fa->source_v = bash_source_v;
4906 fa->lineno_a = (ARRAY *)bash_lineno_a;
4907 fa->lineno_v = bash_lineno_v;
4908 fa->funcname_a = (ARRAY *)funcname_a;
4909 fa->funcname_v = funcname_v;
4910 if (subshell == 0)
4911 add_unwind_protect (restore_funcarray_state, fa);
4912#endif
4913
726f6388
JA
4914 /* The temporary environment for a function is supposed to apply to
4915 all commands executed within the function body. */
726f6388 4916
d233b485
CR
4917 /* Initialize BASH_ARGC and BASH_ARGV before we blow away the positional
4918 parameters */
4919 if (debugging_mode || shell_compatibility_level <= 44)
4920 init_bash_argv ();
4921
726f6388
JA
4922 remember_args (words->next, 1);
4923
b80f6443
JA
4924 /* Update BASH_ARGV and BASH_ARGC */
4925 if (debugging_mode)
a0c0a00f
CR
4926 {
4927 push_args (words->next);
4928 if (subshell == 0)
4929 add_unwind_protect (pop_args, 0);
4930 }
b80f6443 4931
ccc6cda3 4932 /* Number of the line on which the function body starts. */
b80f6443 4933 line_number = function_line_number = tc->line;
726f6388 4934
726f6388 4935#if defined (JOB_CONTROL)
95732b49
JA
4936 if (subshell)
4937 stop_pipeline (async, (COMMAND *)NULL);
726f6388 4938#endif
726f6388 4939
a0c0a00f
CR
4940 if (shell_compatibility_level > 43)
4941 loop_level = 0;
4942
95732b49 4943 fc = tc;
726f6388 4944
a0c0a00f
CR
4945 from_return_trap = 0;
4946
726f6388 4947 return_catch_flag++;
ac50fbac 4948 return_val = setjmp_nosigs (return_catch);
726f6388
JA
4949
4950 if (return_val)
95732b49
JA
4951 {
4952 result = return_catch_value;
4953 /* Run the RETURN trap in the function's context. */
4954 save_current = currently_executing_command;
a0c0a00f
CR
4955 if (from_return_trap == 0)
4956 run_return_trap ();
95732b49
JA
4957 currently_executing_command = save_current;
4958 }
726f6388 4959 else
b80f6443
JA
4960 {
4961 /* Run the debug trap here so we can trap at the start of a function's
4962 execution rather than the execution of the body's first command. */
4963 showing_function_line = 1;
4964 save_current = currently_executing_command;
4965 result = run_debug_trap ();
4966#if defined (DEBUGGER)
4967 /* In debugging mode, if the DEBUG trap returns a non-zero status, we
4968 skip the command. */
4969 if (debugging_mode == 0 || result == EXECUTION_SUCCESS)
4970 {
4971 showing_function_line = 0;
4972 currently_executing_command = save_current;
4973 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
4974
4975 /* Run the RETURN trap in the function's context */
4976 save_current = currently_executing_command;
4977 run_return_trap ();
4978 currently_executing_command = save_current;
4979 }
4980#else
4981 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
95732b49
JA
4982
4983 save_current = currently_executing_command;
4984 run_return_trap ();
4985 currently_executing_command = save_current;
b80f6443
JA
4986#endif
4987 showing_function_line = 0;
4988 }
4989
a0c0a00f
CR
4990 /* If we have a local copy of OPTIND, note it in the saved getopts state. */
4991 gv = find_variable ("OPTIND");
4992 if (gv && gv->context == variable_context)
4993 gs->gs_flags |= 1;
726f6388 4994
ccc6cda3 4995 if (subshell == 0)
726f6388 4996 run_unwind_frame ("function_calling");
b80f6443 4997#if defined (ARRAY_VARS)
a0c0a00f
CR
4998 else
4999 {
5000 restore_funcarray_state (fa);
5001 /* Restore BASH_ARGC and BASH_ARGV */
5002 if (debugging_mode)
5003 pop_args ();
5004 }
b80f6443 5005#endif
a0c0a00f 5006
bb70624e 5007 if (variable_context == 0 || this_shell_function == 0)
0001803f
CR
5008 {
5009 make_funcname_visible (0);
5010#if defined (PROCESS_SUBSTITUTION)
5011 unlink_fifo_list ();
5012#endif
5013 }
a0c0a00f 5014
726f6388
JA
5015 return (result);
5016}
5017
bb70624e
JA
5018/* A convenience routine for use by other parts of the shell to execute
5019 a particular shell function. */
5020int
5021execute_shell_function (var, words)
5022 SHELL_VAR *var;
5023 WORD_LIST *words;
5024{
5025 int ret;
5026 struct fd_bitmap *bitmap;
5027
5028 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
5029 begin_unwind_frame ("execute-shell-function");
5030 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
5031
5032 ret = execute_function (var, words, 0, bitmap, 0, 0);
5033
5034 dispose_fd_bitmap (bitmap);
5035 discard_unwind_frame ("execute-shell-function");
5036
5037 return ret;
5038}
5039
726f6388
JA
5040/* Execute a shell builtin or function in a subshell environment. This
5041 routine does not return; it only calls exit(). If BUILTIN is non-null,
5042 it points to a function to call to execute a shell builtin; otherwise
5043 VAR points at the body of a function to execute. WORDS is the arguments
5044 to the command, REDIRECTS specifies redirections to perform before the
5045 command is executed. */
5046static void
5047execute_subshell_builtin_or_function (words, redirects, builtin, var,
5048 pipe_in, pipe_out, async, fds_to_close,
5049 flags)
5050 WORD_LIST *words;
5051 REDIRECT *redirects;
f73dda09 5052 sh_builtin_func_t *builtin;
726f6388
JA
5053 SHELL_VAR *var;
5054 int pipe_in, pipe_out, async;
5055 struct fd_bitmap *fds_to_close;
5056 int flags;
5057{
0628567a 5058 int result, r, funcvalue;
bb70624e
JA
5059#if defined (JOB_CONTROL)
5060 int jobs_hack;
726f6388 5061
b72432fd
JA
5062 jobs_hack = (builtin == jobs_builtin) &&
5063 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
bb70624e
JA
5064#endif
5065
5066 /* A subshell is neither a login shell nor interactive. */
5067 login_shell = interactive = 0;
a0c0a00f
CR
5068 if (builtin == eval_builtin)
5069 evalnest = 0;
5070 else if (builtin == source_builtin)
5071 sourcenest = 0;
b72432fd 5072
0628567a
JA
5073 if (async)
5074 subshell_environment |= SUBSHELL_ASYNC;
5075 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
5076 subshell_environment |= SUBSHELL_PIPE;
726f6388 5077
ccc6cda3 5078 maybe_make_export_env (); /* XXX - is this needed? */
726f6388
JA
5079
5080#if defined (JOB_CONTROL)
5081 /* Eradicate all traces of job control after we fork the subshell, so
5082 all jobs begun by this subshell are in the same process group as
5083 the shell itself. */
5084
5085 /* Allow the output of `jobs' to be piped. */
b72432fd 5086 if (jobs_hack)
726f6388
JA
5087 kill_current_pipeline ();
5088 else
5089 without_job_control ();
5090
5091 set_sigchld_handler ();
d233b485
CR
5092#else
5093 without_job_control ();
726f6388
JA
5094#endif /* JOB_CONTROL */
5095
5096 set_sigint_handler ();
5097
726f6388
JA
5098 if (fds_to_close)
5099 close_fd_bitmap (fds_to_close);
5100
bb70624e
JA
5101 do_piping (pipe_in, pipe_out);
5102
b80f6443 5103 if (do_redirections (redirects, RX_ACTIVE) != 0)
726f6388
JA
5104 exit (EXECUTION_FAILURE);
5105
5106 if (builtin)
5107 {
726f6388
JA
5108 /* Give builtins a place to jump back to on failure,
5109 so we don't go back up to main(). */
ac50fbac 5110 result = setjmp_nosigs (top_level);
726f6388 5111
0628567a
JA
5112 /* Give the return builtin a place to jump to when executed in a subshell
5113 or pipeline */
5114 funcvalue = 0;
5115 if (return_catch_flag && builtin == return_builtin)
ac50fbac 5116 funcvalue = setjmp_nosigs (return_catch);
0628567a 5117
726f6388
JA
5118 if (result == EXITPROG)
5119 exit (last_command_exit_value);
5120 else if (result)
5121 exit (EXECUTION_FAILURE);
0628567a
JA
5122 else if (funcvalue)
5123 exit (return_catch_value);
726f6388 5124 else
cce855bc
JA
5125 {
5126 r = execute_builtin (builtin, words, flags, 1);
3185942a 5127 fflush (stdout);
cce855bc
JA
5128 if (r == EX_USAGE)
5129 r = EX_BADUSAGE;
d233b485
CR
5130 /* XXX - experimental */
5131 else if (r == EX_DISKFALLBACK)
5132 {
5133 char *command_line;
5134
5135 command_line = savestring (the_printed_command_except_trap ? the_printed_command_except_trap : "");
5136 r = execute_disk_command (words, (REDIRECT *)0, command_line,
5137 -1, -1, async, (struct fd_bitmap *)0, flags|CMD_NO_FORK);
5138 }
a0c0a00f 5139 sh_exit (r);
cce855bc 5140 }
726f6388
JA
5141 }
5142 else
3185942a
JA
5143 {
5144 r = execute_function (var, words, flags, fds_to_close, async, 1);
5145 fflush (stdout);
a0c0a00f 5146 sh_exit (r);
3185942a 5147 }
726f6388
JA
5148}
5149
5150/* Execute a builtin or function in the current shell context. If BUILTIN
5151 is non-null, it is the builtin command to execute, otherwise VAR points
5152 to the body of a function. WORDS are the command's arguments, REDIRECTS
5153 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
5154 file descriptors to close.
5155
5156 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
5157 not undone before this function returns. */
5158static int
5159execute_builtin_or_function (words, builtin, var, redirects,
5160 fds_to_close, flags)
5161 WORD_LIST *words;
f73dda09 5162 sh_builtin_func_t *builtin;
726f6388
JA
5163 SHELL_VAR *var;
5164 REDIRECT *redirects;
5165 struct fd_bitmap *fds_to_close;
5166 int flags;
5167{
ccc6cda3 5168 int result;
726f6388 5169 REDIRECT *saved_undo_list;
495aee44
CR
5170#if defined (PROCESS_SUBSTITUTION)
5171 int ofifo, nfifo, osize;
5172 char *ofifo_list;
5173#endif
5174
2fb21d75
CR
5175#if defined (PROCESS_SUBSTITUTION)
5176 begin_unwind_frame ("saved_fifos");
5177 /* If we return, we longjmp and don't get a chance to restore the old
5178 fifo list, so we add an unwind protect to free it */
495aee44
CR
5179 ofifo = num_fifos ();
5180 ofifo_list = copy_fifo_list (&osize);
2fb21d75
CR
5181 if (ofifo_list)
5182 add_unwind_protect (xfree, ofifo_list);
495aee44 5183#endif
726f6388 5184
b80f6443 5185 if (do_redirections (redirects, RX_ACTIVE|RX_UNDOABLE) != 0)
726f6388 5186 {
d233b485 5187 undo_partial_redirects ();
726f6388 5188 dispose_exec_redirects ();
495aee44
CR
5189#if defined (PROCESS_SUBSTITUTION)
5190 free (ofifo_list);
5191#endif
ccc6cda3 5192 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
726f6388
JA
5193 }
5194
5195 saved_undo_list = redirection_undo_list;
5196
5197 /* Calling the "exec" builtin changes redirections forever. */
5198 if (builtin == exec_builtin)
5199 {
5200 dispose_redirects (saved_undo_list);
5201 saved_undo_list = exec_redirection_undo_list;
5202 exec_redirection_undo_list = (REDIRECT *)NULL;
5203 }
5204 else
5205 dispose_exec_redirects ();
5206
5207 if (saved_undo_list)
5208 {
a0c0a00f 5209 begin_unwind_frame ("saved-redirects");
ccc6cda3 5210 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
726f6388
JA
5211 }
5212
5213 redirection_undo_list = (REDIRECT *)NULL;
5214
5215 if (builtin)
5216 result = execute_builtin (builtin, words, flags, 0);
5217 else
5218 result = execute_function (var, words, flags, fds_to_close, 0, 0);
5219
b80f6443 5220 /* We do this before undoing the effects of any redirections. */
3185942a
JA
5221 fflush (stdout);
5222 fpurge (stdout);
b80f6443
JA
5223 if (ferror (stdout))
5224 clearerr (stdout);
5225
28ef6c31
JA
5226 /* If we are executing the `command' builtin, but this_shell_builtin is
5227 set to `exec_builtin', we know that we have something like
5228 `command exec [redirection]', since otherwise `exec' would have
5229 overwritten the shell and we wouldn't get here. In this case, we
5230 want to behave as if the `command' builtin had not been specified
5231 and preserve the redirections. */
5232 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
5233 {
495aee44
CR
5234 int discard;
5235
5236 discard = 0;
28ef6c31 5237 if (saved_undo_list)
495aee44
CR
5238 {
5239 dispose_redirects (saved_undo_list);
5240 discard = 1;
5241 }
28ef6c31
JA
5242 redirection_undo_list = exec_redirection_undo_list;
5243 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
495aee44 5244 if (discard)
a0c0a00f 5245 discard_unwind_frame ("saved-redirects");
28ef6c31
JA
5246 }
5247
726f6388
JA
5248 if (saved_undo_list)
5249 {
5250 redirection_undo_list = saved_undo_list;
a0c0a00f 5251 discard_unwind_frame ("saved-redirects");
726f6388
JA
5252 }
5253
d233b485 5254 undo_partial_redirects ();
726f6388 5255
495aee44
CR
5256#if defined (PROCESS_SUBSTITUTION)
5257 /* Close any FIFOs created by this builtin or function. */
5258 nfifo = num_fifos ();
5259 if (nfifo > ofifo)
5260 close_new_fifos (ofifo_list, osize);
2fb21d75
CR
5261 if (ofifo_list)
5262 free (ofifo_list);
5263 discard_unwind_frame ("saved_fifos");
495aee44
CR
5264#endif
5265
726f6388
JA
5266 return (result);
5267}
5268
5269void
5270setup_async_signals ()
5271{
b72432fd
JA
5272#if defined (__BEOS__)
5273 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
5274#endif
5275
726f6388
JA
5276#if defined (JOB_CONTROL)
5277 if (job_control == 0)
5278#endif
5279 {
ac50fbac
CR
5280 /* Make sure we get the original signal dispositions now so we don't
5281 confuse the trap builtin later if the subshell tries to use it to
5282 reset SIGINT/SIGQUIT. Don't call set_signal_ignored; that sets
5283 the value of original_signals to SIG_IGN. Posix interpretation 751. */
5284 get_original_signal (SIGINT);
726f6388 5285 set_signal_handler (SIGINT, SIG_IGN);
ac50fbac
CR
5286
5287 get_original_signal (SIGQUIT);
726f6388 5288 set_signal_handler (SIGQUIT, SIG_IGN);
726f6388
JA
5289 }
5290}
5291
5292/* Execute a simple command that is hopefully defined in a disk file
5293 somewhere.
5294
5295 1) fork ()
5296 2) connect pipes
5297 3) look up the command
5298 4) do redirections
5299 5) execve ()
5300 6) If the execve failed, see if the file has executable mode set.
5301 If so, and it isn't a directory, then execute its contents as
5302 a shell script.
5303
5304 Note that the filename hashing stuff has to take place up here,
5305 in the parent. This is probably why the Bourne style shells
5306 don't handle it, since that would require them to go through
b80f6443
JA
5307 this gnarly hair, for no good reason.
5308
5309 NOTE: callers expect this to fork or exit(). */
3185942a
JA
5310
5311/* Name of a shell function to call when a command name is not found. */
5312#ifndef NOTFOUND_HOOK
5313# define NOTFOUND_HOOK "command_not_found_handle"
5314#endif
5315
495aee44 5316static int
726f6388 5317execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
d166f048 5318 async, fds_to_close, cmdflags)
726f6388
JA
5319 WORD_LIST *words;
5320 REDIRECT *redirects;
5321 char *command_line;
5322 int pipe_in, pipe_out, async;
5323 struct fd_bitmap *fds_to_close;
d166f048 5324 int cmdflags;
726f6388 5325{
d233b485 5326 char *pathname, *command, **args, *p;
a0c0a00f 5327 int nofork, stdpath, result;
bb70624e 5328 pid_t pid;
3185942a
JA
5329 SHELL_VAR *hookf;
5330 WORD_LIST *wl;
726f6388 5331
a0c0a00f
CR
5332 stdpath = (cmdflags & CMD_STDPATH); /* use command -p path */
5333 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
726f6388 5334 pathname = words->word->word;
ccc6cda3 5335
d233b485 5336 p = 0;
495aee44 5337 result = EXECUTION_SUCCESS;
726f6388 5338#if defined (RESTRICTED_SHELL)
b80f6443 5339 command = (char *)NULL;
0001803f 5340 if (restricted && mbschr (pathname, '/'))
726f6388 5341 {
b80f6443 5342 internal_error (_("%s: restricted: cannot specify `/' in command names"),
726f6388 5343 pathname);
495aee44 5344 result = last_command_exit_value = EXECUTION_FAILURE;
b80f6443
JA
5345
5346 /* If we're not going to fork below, we must already be in a child
5347 process or a context in which it's safe to call exit(2). */
5348 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5349 exit (last_command_exit_value);
5350 else
5351 goto parent_return;
726f6388
JA
5352 }
5353#endif /* RESTRICTED_SHELL */
5354
a0c0a00f 5355 command = search_for_command (pathname, CMDSRCH_HASH|(stdpath ? CMDSRCH_STDPATH : 0));
d233b485 5356 QUIT;
726f6388 5357
ccc6cda3 5358 if (command)
726f6388 5359 {
d233b485
CR
5360 /* If we're optimizing out the fork (implicit `exec'), decrement the
5361 shell level like `exec' would do. */
5362 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5363 adjust_shell_level (-1);
5364
ccc6cda3
JA
5365 maybe_make_export_env ();
5366 put_command_name_into_env (command);
726f6388
JA
5367 }
5368
bb70624e 5369 /* We have to make the child before we check for the non-existence
726f6388
JA
5370 of COMMAND, since we want the error messages to be redirected. */
5371 /* If we can get away without forking and there are no pipes to deal with,
5372 don't bother to fork, just directly exec the command. */
5373 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
5374 pid = 0;
5375 else
d233b485 5376 pid = make_child (p = savestring (command_line), async);
726f6388
JA
5377
5378 if (pid == 0)
5379 {
5380 int old_interactive;
5381
495aee44 5382 reset_terminating_signals (); /* XXX */
726f6388
JA
5383 /* Cancel traps, in trap.c. */
5384 restore_original_signals ();
5385
ac50fbac
CR
5386 CHECK_SIGTERM;
5387
d233b485
CR
5388#if defined (JOB_CONTROL)
5389 FREE (p);
5390#endif
5391
726f6388 5392 /* restore_original_signals may have undone the work done
cce855bc
JA
5393 by make_child to ensure that SIGINT and SIGQUIT are ignored
5394 in asynchronous children. */
726f6388 5395 if (async)
d166f048
JA
5396 {
5397 if ((cmdflags & CMD_STDIN_REDIR) &&
5398 pipe_in == NO_PIPE &&
5399 (stdin_redirects (redirects) == 0))
5400 async_redirect_stdin ();
5401 setup_async_signals ();
5402 }
726f6388 5403
bb70624e
JA
5404 /* This functionality is now provided by close-on-exec of the
5405 file descriptors manipulated by redirection and piping.
5406 Some file descriptors still need to be closed in all children
5407 because of the way bash does pipes; fds_to_close is a
5408 bitmap of all such file descriptors. */
5409 if (fds_to_close)
5410 close_fd_bitmap (fds_to_close);
5411
726f6388
JA
5412 do_piping (pipe_in, pipe_out);
5413
f73dda09 5414 old_interactive = interactive;
726f6388 5415 if (async)
f73dda09 5416 interactive = 0;
726f6388 5417
a0c0a00f 5418 subshell_environment |= SUBSHELL_FORK; /* XXX - was just = */
726f6388 5419
b80f6443 5420 if (redirects && (do_redirections (redirects, RX_ACTIVE) != 0))
726f6388
JA
5421 {
5422#if defined (PROCESS_SUBSTITUTION)
5423 /* Try to remove named pipes that may have been created as the
5424 result of redirections. */
5425 unlink_fifo_list ();
5426#endif /* PROCESS_SUBSTITUTION */
5427 exit (EXECUTION_FAILURE);
5428 }
5429
5430 if (async)
5431 interactive = old_interactive;
5432
ccc6cda3 5433 if (command == 0)
726f6388 5434 {
3185942a
JA
5435 hookf = find_function (NOTFOUND_HOOK);
5436 if (hookf == 0)
5437 {
495aee44 5438 /* Make sure filenames are displayed using printable characters */
a0c0a00f 5439 pathname = printable_filename (pathname, 0);
3185942a
JA
5440 internal_error (_("%s: command not found"), pathname);
5441 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
5442 }
5443
d233b485
CR
5444 /* We don't want to manage process groups for processes we start
5445 from here, so we turn off job control and don't attempt to
5446 manipulate the terminal's process group. */
5447 without_job_control ();
5448
ac50fbac 5449#if defined (JOB_CONTROL)
d233b485 5450 set_sigchld_handler ();
ac50fbac
CR
5451#endif
5452
3185942a
JA
5453 wl = make_word_list (make_word (NOTFOUND_HOOK), words);
5454 exit (execute_shell_function (hookf, wl));
726f6388
JA
5455 }
5456
ac50fbac
CR
5457 CHECK_SIGTERM;
5458
ccc6cda3
JA
5459 /* Execve expects the command name to be in args[0]. So we
5460 leave it there, in the same format that the user used to
5461 type it in. */
7117c2d2 5462 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
726f6388
JA
5463 exit (shell_execve (command, args, export_env));
5464 }
5465 else
5466 {
b80f6443 5467parent_return:
ac50fbac
CR
5468 QUIT;
5469
726f6388
JA
5470 /* Make sure that the pipes are closed in the parent. */
5471 close_pipes (pipe_in, pipe_out);
5472#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
d233b485 5473#if 0
0001803f
CR
5474 if (variable_context == 0)
5475 unlink_fifo_list ();
d233b485 5476#endif
726f6388
JA
5477#endif
5478 FREE (command);
495aee44 5479 return (result);
726f6388
JA
5480 }
5481}
5482
28ef6c31
JA
5483/* CPP defines to decide whether a particular index into the #! line
5484 corresponds to a valid interpreter name or argument character, or
5485 whitespace. The MSDOS define is to allow \r to be treated the same
5486 as \n. */
5487
5488#if !defined (MSDOS)
5489# define STRINGCHAR(ind) \
f73dda09 5490 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
28ef6c31 5491# define WHITECHAR(ind) \
f73dda09 5492 (ind < sample_len && whitespace (sample[ind]))
28ef6c31
JA
5493#else /* MSDOS */
5494# define STRINGCHAR(ind) \
f73dda09 5495 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
28ef6c31 5496# define WHITECHAR(ind) \
f73dda09 5497 (ind < sample_len && whitespace (sample[ind]))
28ef6c31
JA
5498#endif /* MSDOS */
5499
f73dda09
JA
5500static char *
5501getinterp (sample, sample_len, endp)
5502 char *sample;
5503 int sample_len, *endp;
726f6388
JA
5504{
5505 register int i;
f73dda09
JA
5506 char *execname;
5507 int start;
726f6388
JA
5508
5509 /* Find the name of the interpreter to exec. */
f73dda09 5510 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
726f6388
JA
5511 ;
5512
28ef6c31 5513 for (start = i; STRINGCHAR(i); i++)
726f6388
JA
5514 ;
5515
f73dda09
JA
5516 execname = substring (sample, start, i);
5517
5518 if (endp)
5519 *endp = i;
5520 return execname;
5521}
5522
5523#if !defined (HAVE_HASH_BANG_EXEC)
5524/* If the operating system on which we're running does not handle
5525 the #! executable format, then help out. SAMPLE is the text read
5526 from the file, SAMPLE_LEN characters. COMMAND is the name of
5527 the script; it and ARGS, the arguments given by the user, will
5528 become arguments to the specified interpreter. ENV is the environment
5529 to pass to the interpreter.
5530
5531 The word immediately following the #! is the interpreter to execute.
5532 A single argument to the interpreter is allowed. */
5533
5534static int
5535execute_shell_script (sample, sample_len, command, args, env)
5536 char *sample;
5537 int sample_len;
5538 char *command;
5539 char **args, **env;
5540{
5541 char *execname, *firstarg;
5542 int i, start, size_increment, larry;
5543
5544 /* Find the name of the interpreter to exec. */
5545 execname = getinterp (sample, sample_len, &i);
726f6388
JA
5546 size_increment = 1;
5547
5548 /* Now the argument, if any. */
28ef6c31 5549 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
726f6388
JA
5550 ;
5551
5552 /* If there is more text on the line, then it is an argument for the
5553 interpreter. */
28ef6c31
JA
5554
5555 if (STRINGCHAR(i))
726f6388 5556 {
28ef6c31 5557 for (start = i; STRINGCHAR(i); i++)
726f6388 5558 ;
bb70624e 5559 firstarg = substring ((char *)sample, start, i);
726f6388
JA
5560 size_increment = 2;
5561 }
5562
7117c2d2
JA
5563 larry = strvec_len (args) + size_increment;
5564 args = strvec_resize (args, larry + 1);
726f6388
JA
5565
5566 for (i = larry - 1; i; i--)
5567 args[i] = args[i - size_increment];
5568
5569 args[0] = execname;
5570 if (firstarg)
5571 {
5572 args[1] = firstarg;
5573 args[2] = command;
5574 }
5575 else
5576 args[1] = command;
5577
5578 args[larry] = (char *)NULL;
5579
5580 return (shell_execve (execname, args, env));
5581}
28ef6c31
JA
5582#undef STRINGCHAR
5583#undef WHITECHAR
5584
ccc6cda3
JA
5585#endif /* !HAVE_HASH_BANG_EXEC */
5586
d166f048
JA
5587static void
5588initialize_subshell ()
5589{
5590#if defined (ALIAS)
5591 /* Forget about any aliases that we knew of. We are in a subshell. */
5592 delete_all_aliases ();
5593#endif /* ALIAS */
5594
5595#if defined (HISTORY)
5596 /* Forget about the history lines we have read. This is a non-interactive
5597 subshell. */
5598 history_lines_this_session = 0;
5599#endif
5600
d166f048
JA
5601 /* Forget about the way job control was working. We are in a subshell. */
5602 without_job_control ();
a0c0a00f
CR
5603
5604#if defined (JOB_CONTROL)
d166f048 5605 set_sigchld_handler ();
95732b49 5606 init_job_stats ();
d166f048
JA
5607#endif /* JOB_CONTROL */
5608
5609 /* Reset the values of the shell flags and options. */
5610 reset_shell_flags ();
5611 reset_shell_options ();
5612 reset_shopt_options ();
5613
28ef6c31
JA
5614 /* Zero out builtin_env, since this could be a shell script run from a
5615 sourced file with a temporary environment supplied to the `source/.'
5616 builtin. Such variables are not supposed to be exported (empirical
7117c2d2
JA
5617 testing with sh and ksh). Just throw it away; don't worry about a
5618 memory leak. */
5619 if (vc_isbltnenv (shell_variables))
5620 shell_variables = shell_variables->down;
28ef6c31
JA
5621
5622 clear_unwind_protect_list (0);
f1be666c
JA
5623 /* XXX -- are there other things we should be resetting here? */
5624 parse_and_execute_level = 0; /* nothing left to restore it */
28ef6c31
JA
5625
5626 /* We're no longer inside a shell function. */
a0c0a00f 5627 variable_context = return_catch_flag = funcnest = evalnest = sourcenest = 0;
28ef6c31 5628
3185942a
JA
5629 executing_list = 0; /* XXX */
5630
d166f048
JA
5631 /* If we're not interactive, close the file descriptor from which we're
5632 reading the current shell script. */
cce855bc 5633 if (interactive_shell == 0)
b80f6443 5634 unset_bash_input (0);
d166f048
JA
5635}
5636
ccc6cda3
JA
5637#if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
5638# define SETOSTYPE(x) __setostype(x)
5639#else
5640# define SETOSTYPE(x)
5641#endif
726f6388 5642
a0c0a00f
CR
5643#define HASH_BANG_BUFSIZ 128
5644
28ef6c31
JA
5645#define READ_SAMPLE_BUF(file, buf, len) \
5646 do \
5647 { \
5648 fd = open(file, O_RDONLY); \
5649 if (fd >= 0) \
5650 { \
a0c0a00f 5651 len = read (fd, buf, HASH_BANG_BUFSIZ); \
28ef6c31
JA
5652 close (fd); \
5653 } \
5654 else \
5655 len = -1; \
5656 } \
5657 while (0)
5658
726f6388
JA
5659/* Call execve (), handling interpreting shell scripts, and handling
5660 exec failures. */
5661int
5662shell_execve (command, args, env)
5663 char *command;
5664 char **args, **env;
5665{
ccc6cda3 5666 int larray, i, fd;
a0c0a00f 5667 char sample[HASH_BANG_BUFSIZ];
28ef6c31 5668 int sample_len;
ccc6cda3
JA
5669
5670 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
726f6388 5671 execve (command, args, env);
28ef6c31 5672 i = errno; /* error from execve() */
3185942a 5673 CHECK_TERMSIG;
ccc6cda3 5674 SETOSTYPE (1);
726f6388
JA
5675
5676 /* If we get to this point, then start checking out the file.
5677 Maybe it is something we can hack ourselves. */
28ef6c31 5678 if (i != ENOEXEC)
ccc6cda3 5679 {
a0c0a00f
CR
5680 /* make sure this is set correctly for file_error/report_error */
5681 last_command_exit_value = (i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC; /* XXX Posix.2 says that exit status is 126 */
3185942a 5682 if (file_isdir (command))
495aee44
CR
5683#if defined (EISDIR)
5684 internal_error (_("%s: %s"), command, strerror (EISDIR));
5685#else
b80f6443 5686 internal_error (_("%s: is a directory"), command);
495aee44 5687#endif
7117c2d2
JA
5688 else if (executable_file (command) == 0)
5689 {
5690 errno = i;
5691 file_error (command);
5692 }
95732b49
JA
5693 /* errors not involving the path argument to execve. */
5694 else if (i == E2BIG || i == ENOMEM)
5695 {
5696 errno = i;
5697 file_error (command);
5698 }
ccc6cda3
JA
5699 else
5700 {
7117c2d2
JA
5701 /* The file has the execute bits set, but the kernel refuses to
5702 run it for some reason. See why. */
28ef6c31
JA
5703#if defined (HAVE_HASH_BANG_EXEC)
5704 READ_SAMPLE_BUF (command, sample, sample_len);
a0c0a00f
CR
5705 if (sample_len > 0)
5706 sample[sample_len - 1] = '\0';
28ef6c31
JA
5707 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5708 {
f73dda09 5709 char *interp;
95732b49 5710 int ilen;
f73dda09
JA
5711
5712 interp = getinterp (sample, sample_len, (int *)NULL);
95732b49 5713 ilen = strlen (interp);
28ef6c31 5714 errno = i;
95732b49
JA
5715 if (interp[ilen - 1] == '\r')
5716 {
5717 interp = xrealloc (interp, ilen + 2);
5718 interp[ilen - 1] = '^';
5719 interp[ilen] = 'M';
5720 interp[ilen + 1] = '\0';
5721 }
b80f6443 5722 sys_error (_("%s: %s: bad interpreter"), command, interp ? interp : "");
f73dda09 5723 FREE (interp);
28ef6c31
JA
5724 return (EX_NOEXEC);
5725 }
5726#endif
ccc6cda3 5727 errno = i;
726f6388 5728 file_error (command);
ccc6cda3 5729 }
a0c0a00f 5730 return (last_command_exit_value);
ccc6cda3 5731 }
726f6388 5732
ccc6cda3
JA
5733 /* This file is executable.
5734 If it begins with #!, then help out people with losing operating
5735 systems. Otherwise, check to see if it is a binary file by seeing
28ef6c31
JA
5736 if the contents of the first line (or up to 80 characters) are in the
5737 ASCII set. If it's a text file, execute the contents as shell commands,
5738 otherwise return 126 (EX_BINARY_FILE). */
5739 READ_SAMPLE_BUF (command, sample, sample_len);
ccc6cda3 5740
28ef6c31
JA
5741 if (sample_len == 0)
5742 return (EXECUTION_SUCCESS);
ccc6cda3 5743
28ef6c31
JA
5744 /* Is this supposed to be an executable script?
5745 If so, the format of the line is "#! interpreter [argument]".
5746 A single argument is allowed. The BSD kernel restricts
5747 the length of the entire line to 32 characters (32 bytes
5748 being the size of the BSD exec header), but we allow 80
5749 characters. */
5750 if (sample_len > 0)
5751 {
ccc6cda3 5752#if !defined (HAVE_HASH_BANG_EXEC)
28ef6c31
JA
5753 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
5754 return (execute_shell_script (sample, sample_len, command, args, env));
5755 else
ccc6cda3 5756#endif
28ef6c31
JA
5757 if (check_binary_file (sample, sample_len))
5758 {
ac50fbac 5759 internal_error (_("%s: cannot execute binary file: %s"), command, strerror (i));
a0c0a00f 5760 errno = i;
28ef6c31 5761 return (EX_BINARY_FILE);
726f6388 5762 }
ccc6cda3
JA
5763 }
5764
28ef6c31
JA
5765 /* We have committed to attempting to execute the contents of this file
5766 as shell commands. */
5767
a0c0a00f 5768 reset_parser ();
d166f048 5769 initialize_subshell ();
726f6388 5770
ccc6cda3 5771 set_sigint_handler ();
726f6388 5772
ccc6cda3 5773 /* Insert the name of this shell into the argument list. */
7117c2d2
JA
5774 larray = strvec_len (args) + 1;
5775 args = strvec_resize (args, larray + 1);
726f6388 5776
ccc6cda3
JA
5777 for (i = larray - 1; i; i--)
5778 args[i] = args[i - 1];
726f6388 5779
ccc6cda3
JA
5780 args[0] = shell_name;
5781 args[1] = command;
5782 args[larray] = (char *)NULL;
726f6388 5783
ccc6cda3
JA
5784 if (args[0][0] == '-')
5785 args[0]++;
726f6388 5786
ccc6cda3
JA
5787#if defined (RESTRICTED_SHELL)
5788 if (restricted)
5789 change_flag ('r', FLAG_OFF);
5790#endif
726f6388 5791
ccc6cda3
JA
5792 if (subshell_argv)
5793 {
5794 /* Can't free subshell_argv[0]; that is shell_name. */
5795 for (i = 1; i < subshell_argc; i++)
5796 free (subshell_argv[i]);
5797 free (subshell_argv);
5798 }
5799
5800 dispose_command (currently_executing_command); /* XXX */
5801 currently_executing_command = (COMMAND *)NULL;
5802
5803 subshell_argc = larray;
5804 subshell_argv = args;
5805 subshell_envp = env;
5806
5807 unbind_args (); /* remove the positional parameters */
5808
a0c0a00f
CR
5809#if defined (PROCESS_SUBSTITUTION)
5810 clear_fifo_list (); /* pipe fds are what they are now */
5811#endif
5812
5813 sh_longjmp (subshell_top_level, 1);
f73dda09 5814 /*NOTREACHED*/
ccc6cda3
JA
5815}
5816
5817static int
ac50fbac 5818execute_intern_function (name, funcdef)
ccc6cda3 5819 WORD_DESC *name;
ac50fbac 5820 FUNCTION_DEF *funcdef;
ccc6cda3
JA
5821{
5822 SHELL_VAR *var;
d233b485 5823 char *t;
ccc6cda3
JA
5824
5825 if (check_identifier (name, posixly_correct) == 0)
5826 {
5827 if (posixly_correct && interactive_shell == 0)
5828 {
3185942a 5829 last_command_exit_value = EX_BADUSAGE;
b80f6443 5830 jump_to_top_level (ERREXIT);
ccc6cda3
JA
5831 }
5832 return (EXECUTION_FAILURE);
5833 }
5834
d233b485
CR
5835 if (strchr (name->word, CTLESC)) /* WHY? */
5836 {
5837 t = dequote_escapes (name->word);
5838 free (name->word);
5839 name->word = t;
5840 }
5841
ac50fbac
CR
5842 /* Posix interpretation 383 */
5843 if (posixly_correct && find_special_builtin (name->word))
5844 {
5845 internal_error (_("`%s': is a special builtin"), name->word);
5846 last_command_exit_value = EX_BADUSAGE;
a0c0a00f 5847 jump_to_top_level (interactive_shell ? DISCARD : ERREXIT);
ac50fbac
CR
5848 }
5849
ccc6cda3 5850 var = find_function (name->word);
28ef6c31 5851 if (var && (readonly_p (var) || noassign_p (var)))
ccc6cda3 5852 {
28ef6c31 5853 if (readonly_p (var))
b80f6443 5854 internal_error (_("%s: readonly function"), var->name);
ccc6cda3
JA
5855 return (EXECUTION_FAILURE);
5856 }
5857
ac50fbac 5858#if defined (DEBUGGER)
d233b485 5859 bind_function_def (name->word, funcdef, 1);
ac50fbac
CR
5860#endif
5861
5862 bind_function (name->word, funcdef->command);
ccc6cda3 5863 return (EXECUTION_SUCCESS);
726f6388
JA
5864}
5865
d166f048 5866#if defined (INCLUDE_UNUSED)
726f6388 5867#if defined (PROCESS_SUBSTITUTION)
726f6388
JA
5868void
5869close_all_files ()
5870{
5871 register int i, fd_table_size;
5872
5873 fd_table_size = getdtablesize ();
5874 if (fd_table_size > 256) /* clamp to a reasonable value */
7117c2d2 5875 fd_table_size = 256;
726f6388
JA
5876
5877 for (i = 3; i < fd_table_size; i++)
5878 close (i);
5879}
5880#endif /* PROCESS_SUBSTITUTION */
d166f048 5881#endif
726f6388
JA
5882
5883static void
5884close_pipes (in, out)
5885 int in, out;
5886{
5887 if (in >= 0)
5888 close (in);
5889 if (out >= 0)
5890 close (out);
5891}
5892
b80f6443
JA
5893static void
5894dup_error (oldd, newd)
5895 int oldd, newd;
5896{
5897 sys_error (_("cannot duplicate fd %d to fd %d"), oldd, newd);
5898}
5899
726f6388
JA
5900/* Redirect input and output to be from and to the specified pipes.
5901 NO_PIPE and REDIRECT_BOTH are handled correctly. */
5902static void
5903do_piping (pipe_in, pipe_out)
5904 int pipe_in, pipe_out;
5905{
5906 if (pipe_in != NO_PIPE)
5907 {
5908 if (dup2 (pipe_in, 0) < 0)
b80f6443 5909 dup_error (pipe_in, 0);
726f6388 5910 if (pipe_in > 0)
cce855bc 5911 close (pipe_in);
495aee44
CR
5912#ifdef __CYGWIN__
5913 /* Let stdio know the fd may have changed from text to binary mode. */
5914 freopen (NULL, "r", stdin);
5915#endif /* __CYGWIN__ */
726f6388
JA
5916 }
5917 if (pipe_out != NO_PIPE)
5918 {
5919 if (pipe_out != REDIRECT_BOTH)
5920 {
5921 if (dup2 (pipe_out, 1) < 0)
b80f6443 5922 dup_error (pipe_out, 1);
726f6388
JA
5923 if (pipe_out == 0 || pipe_out > 1)
5924 close (pipe_out);
5925 }
5926 else
ccc6cda3 5927 {
cce855bc 5928 if (dup2 (1, 2) < 0)
b80f6443 5929 dup_error (1, 2);
ccc6cda3 5930 }
495aee44
CR
5931#ifdef __CYGWIN__
5932 /* Let stdio know the fd may have changed from text to binary mode, and
5933 make sure to preserve stdout line buffering. */
5934 freopen (NULL, "w", stdout);
5935 sh_setlinebuf (stdout);
5936#endif /* __CYGWIN__ */
d166f048 5937 }
726f6388 5938}