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