]> git.ipfire.org Git - thirdparty/bash.git/blame - execute_cmd.c
Imported from ../bash-2.05b.tar.gz.
[thirdparty/bash.git] / execute_cmd.c
CommitLineData
726f6388
JA
1/* execute_command.c -- Execute a COMMAND structure. */
2
7117c2d2 3/* Copyright (C) 1987-2002 Free Software Foundation, Inc.
726f6388
JA
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
bb70624e 9 the Free Software Foundation; either version 2, or (at your option)
726f6388
JA
10 any later version.
11
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
bb70624e 19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
ccc6cda3
JA
20#include "config.h"
21
22#if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
726f6388 23 #pragma alloca
ccc6cda3 24#endif /* _AIX && RISC6000 && !__GNUC__ */
726f6388
JA
25
26#include <stdio.h>
f73dda09 27#include "chartypes.h"
726f6388 28#include "bashtypes.h"
cce855bc
JA
29#ifndef _MINIX
30# include <sys/file.h>
31#endif
726f6388
JA
32#include "filecntl.h"
33#include "posixstat.h"
34#include <signal.h>
cce855bc
JA
35#ifndef _MINIX
36# include <sys/param.h>
37#endif
726f6388 38
ccc6cda3
JA
39#if defined (HAVE_UNISTD_H)
40# include <unistd.h>
41#endif
42
bb70624e 43#include "posixtime.h"
ccc6cda3 44
cce855bc 45#if defined (HAVE_SYS_RESOURCE_H) && !defined (RLIMTYPE)
ccc6cda3
JA
46# include <sys/resource.h>
47#endif
48
49#if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
50# include <sys/times.h>
726f6388
JA
51#endif
52
726f6388
JA
53#include <errno.h>
54
55#if !defined (errno)
56extern int errno;
57#endif
58
ccc6cda3 59#include "bashansi.h"
726f6388 60
ccc6cda3 61#include "memalloc.h"
726f6388 62#include "shell.h"
d166f048 63#include <y.tab.h> /* use <...> so we pick it up from the build directory */
726f6388 64#include "flags.h"
ccc6cda3
JA
65#include "builtins.h"
66#include "hashlib.h"
726f6388
JA
67#include "jobs.h"
68#include "execute_cmd.h"
cce855bc
JA
69#include "findcmd.h"
70#include "redir.h"
ccc6cda3
JA
71#include "trap.h"
72#include "pathexp.h"
d166f048 73#include "hashcmd.h"
726f6388 74
cce855bc
JA
75#if defined (COND_COMMAND)
76# include "test.h"
77#endif
78
726f6388
JA
79#include "builtins/common.h"
80#include "builtins/builtext.h" /* list of builtins */
81
f73dda09 82#include <glob/strmatch.h>
726f6388
JA
83#include <tilde/tilde.h>
84
85#if defined (BUFFERED_INPUT)
86# include "input.h"
87#endif
88
ccc6cda3
JA
89#if defined (ALIAS)
90# include "alias.h"
91#endif
92
93#if defined (HISTORY)
94# include "bashhist.h"
95#endif
96
726f6388 97extern int posixly_correct;
f73dda09
JA
98extern int breaking, continuing, loop_level;
99extern int expand_aliases;
d166f048 100extern int parse_and_execute_level, running_trap, trap_line_number;
f73dda09 101extern int command_string_index, line_number;
726f6388 102extern int dot_found_in_search;
ccc6cda3 103extern int already_making_children;
726f6388
JA
104extern char *the_printed_command, *shell_name;
105extern pid_t last_command_subst_pid;
f73dda09 106extern sh_builtin_func_t *last_shell_builtin, *this_shell_builtin;
726f6388 107extern char **subshell_argv, **subshell_envp;
ccc6cda3 108extern int subshell_argc;
f73dda09 109#if 0
ccc6cda3 110extern char *glob_argv_flags;
f73dda09 111#endif
726f6388 112
f73dda09 113extern int close __P((int));
726f6388
JA
114
115/* Static functions defined and used in this file. */
f73dda09
JA
116static void close_pipes __P((int, int));
117static void do_piping __P((int, int));
118static void bind_lastarg __P((char *));
119static int shell_control_structure __P((enum command_type));
120static void cleanup_redirects __P((REDIRECT *));
121
122#if defined (JOB_CONTROL)
123static int restore_signal_mask __P((sigset_t *));
124#endif
ccc6cda3 125
f73dda09
JA
126static void async_redirect_stdin __P((void));
127
128static int builtin_status __P((int));
129
130static int execute_for_command __P((FOR_COM *));
ccc6cda3 131#if defined (SELECT_COMMAND)
f73dda09
JA
132static int print_index_and_element __P((int, int, WORD_LIST *));
133static void indent __P((int, int));
134static void print_select_list __P((WORD_LIST *, int, int, int));
7117c2d2 135static char *select_query __P((WORD_LIST *, int, char *, int));
f73dda09 136static int execute_select_command __P((SELECT_COM *));
ccc6cda3 137#endif
cce855bc 138#if defined (DPAREN_ARITHMETIC)
f73dda09 139static int execute_arith_command __P((ARITH_COM *));
cce855bc
JA
140#endif
141#if defined (COND_COMMAND)
f73dda09
JA
142static int execute_cond_node __P((COND_COM *));
143static int execute_cond_command __P((COND_COM *));
cce855bc 144#endif
d166f048 145#if defined (COMMAND_TIMING)
f73dda09
JA
146static int mkfmt __P((char *, int, int, time_t, int));
147static void print_formatted_time __P((FILE *, char *,
148 time_t, int, time_t, int,
149 time_t, int, int));
150static int time_command __P((COMMAND *, int, int, int, struct fd_bitmap *));
d166f048 151#endif
bb70624e 152#if defined (ARITH_FOR_COMMAND)
7117c2d2 153static intmax_t eval_arith_for_expr __P((WORD_LIST *, int *));
f73dda09 154static int execute_arith_for_command __P((ARITH_FOR_COM *));
bb70624e 155#endif
f73dda09
JA
156static int execute_case_command __P((CASE_COM *));
157static int execute_while_command __P((WHILE_COM *));
158static int execute_until_command __P((WHILE_COM *));
159static int execute_while_or_until __P((WHILE_COM *, int));
160static int execute_if_command __P((IF_COM *));
161static int execute_null_command __P((REDIRECT *, int, int, int, pid_t));
162static void fix_assignment_words __P((WORD_LIST *));
163static int execute_simple_command __P((SIMPLE_COM *, int, int, int, struct fd_bitmap *));
164static int execute_builtin __P((sh_builtin_func_t *, WORD_LIST *, int, int));
165static int execute_function __P((SHELL_VAR *, WORD_LIST *, int, struct fd_bitmap *, int, int));
166static int execute_builtin_or_function __P((WORD_LIST *, sh_builtin_func_t *,
167 SHELL_VAR *,
168 REDIRECT *, struct fd_bitmap *, int));
169static void execute_subshell_builtin_or_function __P((WORD_LIST *, REDIRECT *,
170 sh_builtin_func_t *,
171 SHELL_VAR *,
172 int, int, int,
173 struct fd_bitmap *,
174 int));
175static void execute_disk_command __P((WORD_LIST *, REDIRECT *, char *,
176 int, int, int, struct fd_bitmap *, int));
177
178static char *getinterp __P((char *, int, int *));
179static void initialize_subshell __P((void));
180static int execute_in_subshell __P((COMMAND *, int, int, int, struct fd_bitmap *));
181
182static int execute_pipeline __P((COMMAND *, int, int, int, struct fd_bitmap *));
183
184static int execute_connection __P((COMMAND *, int, int, int, struct fd_bitmap *));
185
186static int execute_intern_function __P((WORD_DESC *, COMMAND *));
187
726f6388 188/* The line number that the currently executing function starts on. */
ccc6cda3 189static int function_line_number;
726f6388 190
d166f048
JA
191/* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
192 so that reader_loop can set it to zero before executing a command. */
193int stdin_redir;
726f6388
JA
194
195/* The name of the command that is currently being executed.
196 `test' needs this, for example. */
197char *this_command_name;
198
ccc6cda3
JA
199static COMMAND *currently_executing_command;
200
726f6388
JA
201struct stat SB; /* used for debugging */
202
ccc6cda3 203static int special_builtin_failed;
d166f048 204
726f6388 205/* For catching RETURN in a function. */
ccc6cda3 206int return_catch_flag;
726f6388 207int return_catch_value;
ccc6cda3 208procenv_t return_catch;
726f6388
JA
209
210/* The value returned by the last synchronous command. */
ccc6cda3 211int last_command_exit_value;
726f6388
JA
212
213/* The list of redirections to perform which will undo the redirections
214 that I made in the shell. */
215REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
216
217/* The list of redirections to perform which will undo the internal
218 redirections performed by the `exec' builtin. These are redirections
219 that must be undone even when exec discards redirection_undo_list. */
220REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
221
222/* Non-zero if we have just forked and are currently running in a subshell
223 environment. */
ccc6cda3
JA
224int subshell_environment;
225
bb70624e
JA
226/* Currently-executing shell function. */
227SHELL_VAR *this_shell_function;
228
726f6388
JA
229struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
230
f73dda09 231#define FD_BITMAP_DEFAULT_SIZE 32
d166f048 232
726f6388
JA
233/* Functions to allocate and deallocate the structures used to pass
234 information from the shell to its children about file descriptors
235 to close. */
236struct fd_bitmap *
237new_fd_bitmap (size)
f73dda09 238 int size;
726f6388
JA
239{
240 struct fd_bitmap *ret;
241
242 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
243
244 ret->size = size;
245
246 if (size)
247 {
f73dda09 248 ret->bitmap = (char *)xmalloc (size);
7117c2d2 249 memset (ret->bitmap, '\0', size);
726f6388
JA
250 }
251 else
252 ret->bitmap = (char *)NULL;
253 return (ret);
254}
255
256void
257dispose_fd_bitmap (fdbp)
258 struct fd_bitmap *fdbp;
259{
260 FREE (fdbp->bitmap);
261 free (fdbp);
262}
263
264void
265close_fd_bitmap (fdbp)
266 struct fd_bitmap *fdbp;
267{
268 register int i;
269
270 if (fdbp)
271 {
272 for (i = 0; i < fdbp->size; i++)
273 if (fdbp->bitmap[i])
274 {
275 close (i);
276 fdbp->bitmap[i] = 0;
277 }
278 }
279}
280
ccc6cda3
JA
281/* Return the line number of the currently executing command. */
282int
283executing_line_number ()
284{
7117c2d2
JA
285 if (executing && (variable_context == 0 || interactive_shell == 0) && currently_executing_command)
286 {
287 if (currently_executing_command->type == cm_simple)
288 return currently_executing_command->value.Simple->line;
289 else if (currently_executing_command->type == cm_cond)
290 return currently_executing_command->value.Cond->line;
291 else if (currently_executing_command->type == cm_arith)
292 return currently_executing_command->value.Arith->line;
293 else if (currently_executing_command->type == cm_arith_for)
294 return currently_executing_command->value.ArithFor->line;
295 else
296 return line_number;
297 }
d166f048
JA
298 else if (running_trap)
299 return trap_line_number;
300 else
301 return line_number;
ccc6cda3
JA
302}
303
726f6388
JA
304/* Execute the command passed in COMMAND. COMMAND is exactly what
305 read_command () places into GLOBAL_COMMAND. See "command.h" for the
306 details of the command structure.
307
308 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
309 return values. Executing a command with nothing in it returns
310 EXECUTION_SUCCESS. */
ccc6cda3 311int
726f6388
JA
312execute_command (command)
313 COMMAND *command;
314{
315 struct fd_bitmap *bitmap;
316 int result;
317
318 current_fds_to_close = (struct fd_bitmap *)NULL;
319 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
320 begin_unwind_frame ("execute-command");
321 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
322
323 /* Just do the command, but not asynchronously. */
324 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
325
326 dispose_fd_bitmap (bitmap);
327 discard_unwind_frame ("execute-command");
328
329#if defined (PROCESS_SUBSTITUTION)
bb70624e
JA
330 /* don't unlink fifos if we're in a shell function; wait until the function
331 returns. */
332 if (variable_context == 0)
333 unlink_fifo_list ();
726f6388
JA
334#endif /* PROCESS_SUBSTITUTION */
335
336 return (result);
337}
338
339/* Return 1 if TYPE is a shell control structure type. */
340static int
341shell_control_structure (type)
342 enum command_type type;
343{
344 switch (type)
345 {
346 case cm_for:
bb70624e
JA
347#if defined (ARITH_FOR_COMMAND)
348 case cm_arith_for:
349#endif
726f6388
JA
350#if defined (SELECT_COMMAND)
351 case cm_select:
cce855bc
JA
352#endif
353#if defined (DPAREN_ARITHMETIC)
354 case cm_arith:
355#endif
356#if defined (COND_COMMAND)
357 case cm_cond:
726f6388
JA
358#endif
359 case cm_case:
360 case cm_while:
361 case cm_until:
362 case cm_if:
363 case cm_group:
364 return (1);
365
366 default:
367 return (0);
368 }
369}
370
371/* A function to use to unwind_protect the redirection undo list
372 for loops. */
373static void
374cleanup_redirects (list)
375 REDIRECT *list;
376{
377 do_redirections (list, 1, 0, 0);
378 dispose_redirects (list);
379}
380
ccc6cda3 381#if 0
726f6388
JA
382/* Function to unwind_protect the redirections for functions and builtins. */
383static void
384cleanup_func_redirects (list)
385 REDIRECT *list;
386{
387 do_redirections (list, 1, 0, 0);
388}
ccc6cda3 389#endif
726f6388 390
cce855bc 391void
726f6388
JA
392dispose_exec_redirects ()
393{
394 if (exec_redirection_undo_list)
395 {
396 dispose_redirects (exec_redirection_undo_list);
397 exec_redirection_undo_list = (REDIRECT *)NULL;
398 }
399}
400
401#if defined (JOB_CONTROL)
402/* A function to restore the signal mask to its proper value when the shell
403 is interrupted or errors occur while creating a pipeline. */
404static int
405restore_signal_mask (set)
f73dda09 406 sigset_t *set;
726f6388 407{
f73dda09 408 return (sigprocmask (SIG_SETMASK, set, (sigset_t *)NULL));
726f6388
JA
409}
410#endif /* JOB_CONTROL */
411
f73dda09 412#ifdef DEBUG
726f6388
JA
413/* A debugging function that can be called from gdb, for instance. */
414void
415open_files ()
416{
417 register int i;
418 int f, fd_table_size;
419
420 fd_table_size = getdtablesize ();
421
f73dda09 422 fprintf (stderr, "pid %ld open files:", (long)getpid ());
726f6388
JA
423 for (i = 3; i < fd_table_size; i++)
424 {
425 if ((f = fcntl (i, F_GETFD, 0)) != -1)
426 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
427 }
428 fprintf (stderr, "\n");
429}
f73dda09 430#endif
726f6388 431
d166f048
JA
432static void
433async_redirect_stdin ()
434{
435 int fd;
436
437 fd = open ("/dev/null", O_RDONLY);
438 if (fd > 0)
439 {
440 dup2 (fd, 0);
441 close (fd);
442 }
443 else if (fd < 0)
444 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno));
445}
446
ccc6cda3 447#define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
726f6388
JA
448
449/* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
450 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
451 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
452 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
453 from and where it goes. They can have the value of NO_PIPE, which means
454 I/O is stdin/stdout.
455 FDS_TO_CLOSE is a list of file descriptors to close once the child has
456 been forked. This list often contains the unusable sides of pipes, etc.
457
458 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
459 return values. Executing a command with nothing in it returns
460 EXECUTION_SUCCESS. */
ccc6cda3
JA
461int
462execute_command_internal (command, asynchronous, pipe_in, pipe_out,
726f6388
JA
463 fds_to_close)
464 COMMAND *command;
465 int asynchronous;
466 int pipe_in, pipe_out;
467 struct fd_bitmap *fds_to_close;
468{
7117c2d2 469 int exec_result, invert, ignore_return, was_error_trap;
d166f048 470 REDIRECT *my_undo_list, *exec_undo_list;
cce855bc 471 volatile pid_t last_pid;
726f6388 472
ccc6cda3 473 if (command == 0 || breaking || continuing || read_but_dont_execute)
726f6388
JA
474 return (EXECUTION_SUCCESS);
475
476 run_pending_traps ();
477
ccc6cda3
JA
478 if (running_trap == 0)
479 currently_executing_command = command;
480
726f6388 481 invert = (command->flags & CMD_INVERT_RETURN) != 0;
d166f048
JA
482
483 /* If we're inverting the return value and `set -e' has been executed,
484 we don't want a failing command to inadvertently cause the shell
485 to exit. */
486 if (exit_immediately_on_error && invert) /* XXX */
487 command->flags |= CMD_IGNORE_RETURN; /* XXX */
488
ccc6cda3 489 exec_result = EXECUTION_SUCCESS;
726f6388
JA
490
491 /* If a command was being explicitly run in a subshell, or if it is
492 a shell control-structure, and it has a pipe, then we do the command
493 in a subshell. */
bb70624e
JA
494 if (command->type == cm_subshell && (command->flags & CMD_NO_FORK))
495 return (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
726f6388 496
bb70624e
JA
497 if (command->type == cm_subshell ||
498 (command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
726f6388
JA
499 (shell_control_structure (command->type) &&
500 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
501 {
502 pid_t paren_pid;
503
504 /* Fork a subshell, turn off the subshell bit, turn off job
505 control and call execute_command () on the command again. */
506 paren_pid = make_child (savestring (make_command_string (command)),
507 asynchronous);
508 if (paren_pid == 0)
28ef6c31
JA
509 exit (execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close));
510 /* NOTREACHED */
726f6388
JA
511 else
512 {
513 close_pipes (pipe_in, pipe_out);
514
515#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
516 unlink_fifo_list ();
517#endif
518 /* If we are part of a pipeline, and not the end of the pipeline,
519 then we should simply return and let the last command in the
520 pipe be waited for. If we are not in a pipeline, or are the
ccc6cda3 521 last command in the pipeline, then we wait for the subshell
726f6388
JA
522 and return its exit status as usual. */
523 if (pipe_out != NO_PIPE)
524 return (EXECUTION_SUCCESS);
525
526 stop_pipeline (asynchronous, (COMMAND *)NULL);
527
ccc6cda3 528 if (asynchronous == 0)
726f6388
JA
529 {
530 last_command_exit_value = wait_for (paren_pid);
531
532 /* If we have to, invert the return value. */
533 if (invert)
bb70624e
JA
534 exec_result = ((last_command_exit_value == EXECUTION_SUCCESS)
535 ? EXECUTION_FAILURE
536 : EXECUTION_SUCCESS);
726f6388 537 else
bb70624e
JA
538 exec_result = last_command_exit_value;
539
540 return (last_command_exit_value = exec_result);
726f6388
JA
541 }
542 else
543 {
544 DESCRIBE_PID (paren_pid);
545
546 run_pending_traps ();
547
548 return (EXECUTION_SUCCESS);
549 }
550 }
551 }
552
d166f048
JA
553#if defined (COMMAND_TIMING)
554 if (command->flags & CMD_TIME_PIPELINE)
555 {
556 if (asynchronous)
557 {
558 command->flags |= CMD_FORCE_SUBSHELL;
559 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
560 }
561 else
562 {
563 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
564 if (running_trap == 0)
565 currently_executing_command = (COMMAND *)NULL;
566 }
567 return (exec_result);
568 }
569#endif /* COMMAND_TIMING */
570
571 if (shell_control_structure (command->type) && command->redirects)
572 stdin_redir = stdin_redirects (command->redirects);
573
726f6388
JA
574 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
575 redirection.) */
576 if (do_redirections (command->redirects, 1, 1, 0) != 0)
577 {
578 cleanup_redirects (redirection_undo_list);
579 redirection_undo_list = (REDIRECT *)NULL;
580 dispose_exec_redirects ();
581 return (EXECUTION_FAILURE);
582 }
583
584 if (redirection_undo_list)
585 {
586 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
587 dispose_redirects (redirection_undo_list);
588 redirection_undo_list = (REDIRECT *)NULL;
589 }
590 else
591 my_undo_list = (REDIRECT *)NULL;
592
593 if (exec_redirection_undo_list)
594 {
595 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
596 dispose_redirects (exec_redirection_undo_list);
597 exec_redirection_undo_list = (REDIRECT *)NULL;
598 }
599 else
600 exec_undo_list = (REDIRECT *)NULL;
601
602 if (my_undo_list || exec_undo_list)
603 begin_unwind_frame ("loop_redirections");
604
605 if (my_undo_list)
606 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
607
608 if (exec_undo_list)
609 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
610
611 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
612
613 QUIT;
614
615 switch (command->type)
616 {
ccc6cda3
JA
617 case cm_simple:
618 {
619 /* We can't rely on this variable retaining its value across a
620 call to execute_simple_command if a longjmp occurs as the
621 result of a `return' builtin. This is true for sure with gcc. */
622 last_pid = last_made_pid;
f73dda09 623 was_error_trap = signal_is_trapped (ERROR_TRAP) && signal_is_ignored (ERROR_TRAP) == 0;
ccc6cda3
JA
624
625 if (ignore_return && command->value.Simple)
626 command->value.Simple->flags |= CMD_IGNORE_RETURN;
d166f048
JA
627 if (command->flags & CMD_STDIN_REDIR)
628 command->value.Simple->flags |= CMD_STDIN_REDIR;
ccc6cda3
JA
629 exec_result =
630 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
631 asynchronous, fds_to_close);
632
633 /* The temporary environment should be used for only the simple
634 command immediately following its definition. */
635 dispose_used_env_vars ();
636
637#if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
638 /* Reclaim memory allocated with alloca () on machines which
639 may be using the alloca emulation code. */
640 (void) alloca (0);
641#endif /* (ultrix && mips) || C_ALLOCA */
642
643 /* If we forked to do the command, then we must wait_for ()
644 the child. */
645
646 /* XXX - this is something to watch out for if there are problems
647 when the shell is compiled without job control. */
648 if (already_making_children && pipe_out == NO_PIPE &&
649 last_pid != last_made_pid)
650 {
651 stop_pipeline (asynchronous, (COMMAND *)NULL);
652
653 if (asynchronous)
654 {
655 DESCRIBE_PID (last_made_pid);
656 }
657 else
658#if !defined (JOB_CONTROL)
659 /* Do not wait for asynchronous processes started from
660 startup files. */
661 if (last_made_pid != last_asynchronous_pid)
662#endif
663 /* When executing a shell function that executes other
664 commands, this causes the last simple command in
665 the function to be waited for twice. */
666 exec_result = wait_for (last_made_pid);
b72432fd
JA
667#if defined (RECYCLES_PIDS)
668 /* LynxOS, for one, recycles pids very quickly -- so quickly
669 that a new process may have the same pid as the last one
670 created. This has been reported to fix the problem. */
671 if (exec_result == 0)
672 last_made_pid = NO_PID;
673#endif
ccc6cda3
JA
674 }
675 }
676
f73dda09
JA
677 if (was_error_trap && ignore_return == 0 && invert == 0 && exec_result != EXECUTION_SUCCESS)
678 {
679 last_command_exit_value = exec_result;
680 run_error_trap ();
681 }
682
ccc6cda3 683 if (ignore_return == 0 && invert == 0 &&
cce855bc 684 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
ccc6cda3
JA
685 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
686 {
687 last_command_exit_value = exec_result;
688 run_pending_traps ();
689 jump_to_top_level (EXITPROG);
690 }
691
692 break;
693
726f6388
JA
694 case cm_for:
695 if (ignore_return)
696 command->value.For->flags |= CMD_IGNORE_RETURN;
697 exec_result = execute_for_command (command->value.For);
698 break;
699
bb70624e
JA
700#if defined (ARITH_FOR_COMMAND)
701 case cm_arith_for:
702 if (ignore_return)
703 command->value.ArithFor->flags |= CMD_IGNORE_RETURN;
704 exec_result = execute_arith_for_command (command->value.ArithFor);
705 break;
706#endif
707
726f6388
JA
708#if defined (SELECT_COMMAND)
709 case cm_select:
710 if (ignore_return)
711 command->value.Select->flags |= CMD_IGNORE_RETURN;
712 exec_result = execute_select_command (command->value.Select);
713 break;
714#endif
715
716 case cm_case:
717 if (ignore_return)
718 command->value.Case->flags |= CMD_IGNORE_RETURN;
719 exec_result = execute_case_command (command->value.Case);
720 break;
721
722 case cm_while:
723 if (ignore_return)
724 command->value.While->flags |= CMD_IGNORE_RETURN;
725 exec_result = execute_while_command (command->value.While);
726 break;
727
728 case cm_until:
729 if (ignore_return)
730 command->value.While->flags |= CMD_IGNORE_RETURN;
731 exec_result = execute_until_command (command->value.While);
732 break;
733
734 case cm_if:
735 if (ignore_return)
736 command->value.If->flags |= CMD_IGNORE_RETURN;
737 exec_result = execute_if_command (command->value.If);
738 break;
739
740 case cm_group:
741
742 /* This code can be executed from either of two paths: an explicit
743 '{}' command, or via a function call. If we are executed via a
744 function call, we have already taken care of the function being
745 executed in the background (down there in execute_simple_command ()),
746 and this command should *not* be marked as asynchronous. If we
747 are executing a regular '{}' group command, and asynchronous == 1,
748 we must want to execute the whole command in the background, so we
749 need a subshell, and we want the stuff executed in that subshell
750 (this group command) to be executed in the foreground of that
751 subshell (i.e. there will not be *another* subshell forked).
752
753 What we do is to force a subshell if asynchronous, and then call
754 execute_command_internal again with asynchronous still set to 1,
755 but with the original group command, so the printed command will
756 look right.
757
758 The code above that handles forking off subshells will note that
759 both subshell and async are on, and turn off async in the child
760 after forking the subshell (but leave async set in the parent, so
761 the normal call to describe_pid is made). This turning off
762 async is *crucial*; if it is not done, this will fall into an
763 infinite loop of executions through this spot in subshell after
764 subshell until the process limit is exhausted. */
765
766 if (asynchronous)
767 {
768 command->flags |= CMD_FORCE_SUBSHELL;
769 exec_result =
770 execute_command_internal (command, 1, pipe_in, pipe_out,
771 fds_to_close);
772 }
773 else
774 {
775 if (ignore_return && command->value.Group->command)
776 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
777 exec_result =
778 execute_command_internal (command->value.Group->command,
779 asynchronous, pipe_in, pipe_out,
780 fds_to_close);
781 }
782 break;
783
ccc6cda3
JA
784 case cm_connection:
785 exec_result = execute_connection (command, asynchronous,
786 pipe_in, pipe_out, fds_to_close);
787 break;
726f6388 788
cce855bc
JA
789#if defined (DPAREN_ARITHMETIC)
790 case cm_arith:
791 if (ignore_return)
792 command->value.Arith->flags |= CMD_IGNORE_RETURN;
793 exec_result = execute_arith_command (command->value.Arith);
794 break;
795#endif
796
797#if defined (COND_COMMAND)
798 case cm_cond:
799 if (ignore_return)
800 command->value.Cond->flags |= CMD_IGNORE_RETURN;
801 exec_result = execute_cond_command (command->value.Cond);
802 break;
803#endif
804
ccc6cda3
JA
805 case cm_function_def:
806 exec_result = execute_intern_function (command->value.Function_def->name,
807 command->value.Function_def->command);
808 break;
726f6388 809
ccc6cda3 810 default:
b72432fd 811 command_error ("execute_command", CMDERR_BADTYPE, command->type, 0);
ccc6cda3 812 }
726f6388 813
ccc6cda3
JA
814 if (my_undo_list)
815 {
816 do_redirections (my_undo_list, 1, 0, 0);
817 dispose_redirects (my_undo_list);
818 }
726f6388 819
ccc6cda3
JA
820 if (exec_undo_list)
821 dispose_redirects (exec_undo_list);
726f6388 822
ccc6cda3
JA
823 if (my_undo_list || exec_undo_list)
824 discard_unwind_frame ("loop_redirections");
726f6388 825
ccc6cda3
JA
826 /* Invert the return value if we have to */
827 if (invert)
828 exec_result = (exec_result == EXECUTION_SUCCESS)
829 ? EXECUTION_FAILURE
830 : EXECUTION_SUCCESS;
726f6388 831
ccc6cda3
JA
832 last_command_exit_value = exec_result;
833 run_pending_traps ();
834 if (running_trap == 0)
835 currently_executing_command = (COMMAND *)NULL;
836 return (last_command_exit_value);
837}
726f6388 838
ccc6cda3 839#if defined (COMMAND_TIMING)
726f6388 840
bb70624e 841#if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
f73dda09
JA
842extern struct timeval *difftimeval __P((struct timeval *, struct timeval *, struct timeval *));
843extern struct timeval *addtimeval __P((struct timeval *, struct timeval *, struct timeval *));
844extern int timeval_to_cpu __P((struct timeval *, struct timeval *, struct timeval *));
bb70624e 845#endif
726f6388 846
ccc6cda3
JA
847#define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
848#define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
726f6388 849
ccc6cda3 850static int precs[] = { 0, 100, 10, 1 };
726f6388 851
ccc6cda3
JA
852/* Expand one `%'-prefixed escape sequence from a time format string. */
853static int
854mkfmt (buf, prec, lng, sec, sec_fraction)
855 char *buf;
856 int prec, lng;
f73dda09 857 time_t sec;
ccc6cda3
JA
858 int sec_fraction;
859{
f73dda09
JA
860 time_t min;
861 char abuf[INT_STRLEN_BOUND(time_t) + 1];
ccc6cda3 862 int ind, aind;
726f6388 863
ccc6cda3 864 ind = 0;
f73dda09 865 abuf[sizeof(abuf) - 1] = '\0';
726f6388 866
ccc6cda3
JA
867 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
868 if (lng)
869 {
870 min = sec / 60;
871 sec %= 60;
f73dda09 872 aind = sizeof(abuf) - 2;
ccc6cda3
JA
873 do
874 abuf[aind--] = (min % 10) + '0';
875 while (min /= 10);
876 aind++;
877 while (abuf[aind])
cce855bc 878 buf[ind++] = abuf[aind++];
ccc6cda3
JA
879 buf[ind++] = 'm';
880 }
726f6388 881
ccc6cda3 882 /* Now add the seconds. */
f73dda09 883 aind = sizeof (abuf) - 2;
ccc6cda3
JA
884 do
885 abuf[aind--] = (sec % 10) + '0';
886 while (sec /= 10);
887 aind++;
888 while (abuf[aind])
889 buf[ind++] = abuf[aind++];
890
891 /* We want to add a decimal point and PREC places after it if PREC is
892 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
893 and 999. */
894 if (prec != 0)
895 {
896 buf[ind++] = '.';
897 for (aind = 1; aind <= prec; aind++)
898 {
899 buf[ind++] = (sec_fraction / precs[aind]) + '0';
900 sec_fraction %= precs[aind];
901 }
902 }
726f6388 903
ccc6cda3
JA
904 if (lng)
905 buf[ind++] = 's';
906 buf[ind] = '\0';
726f6388 907
ccc6cda3
JA
908 return (ind);
909}
726f6388 910
ccc6cda3
JA
911/* Interpret the format string FORMAT, interpolating the following escape
912 sequences:
7117c2d2 913 %[prec][l][RUS]
ccc6cda3
JA
914
915 where the optional `prec' is a precision, meaning the number of
916 characters after the decimal point, the optional `l' means to format
917 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
918 and the last character is one of
919
7117c2d2
JA
920 R number of seconds of `real' time
921 U number of seconds of `user' time
922 S number of seconds of `system' time
ccc6cda3
JA
923
924 An occurrence of `%%' in the format string is translated to a `%'. The
925 result is printed to FP, a pointer to a FILE. The other variables are
926 the seconds and thousandths of a second of real, user, and system time,
927 resectively. */
928static void
929print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
930 FILE *fp;
931 char *format;
f73dda09
JA
932 time_t rs;
933 int rsf;
934 time_t us;
935 int usf;
936 time_t ss;
937 int ssf, cpu;
ccc6cda3
JA
938{
939 int prec, lng, len;
f73dda09
JA
940 char *str, *s, ts[INT_STRLEN_BOUND (time_t) + sizeof ("mSS.FFFF")];
941 time_t sum;
e8ce775d 942 int sum_frac;
ccc6cda3 943 int sindex, ssize;
726f6388 944
ccc6cda3
JA
945 len = strlen (format);
946 ssize = (len + 64) - (len % 64);
f73dda09 947 str = (char *)xmalloc (ssize);
ccc6cda3
JA
948 sindex = 0;
949
950 for (s = format; *s; s++)
951 {
952 if (*s != '%' || s[1] == '\0')
cce855bc
JA
953 {
954 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
955 str[sindex++] = *s;
956 }
ccc6cda3 957 else if (s[1] == '%')
cce855bc
JA
958 {
959 s++;
960 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
961 str[sindex++] = *s;
962 }
ccc6cda3
JA
963 else if (s[1] == 'P')
964 {
965 s++;
966 if (cpu > 10000)
967 cpu = 10000;
968 sum = cpu / 100;
969 sum_frac = (cpu % 100) * 10;
970 len = mkfmt (ts, 2, 0, sum, sum_frac);
971 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
972 strcpy (str + sindex, ts);
973 sindex += len;
974 }
975 else
976 {
977 prec = 3; /* default is three places past the decimal point. */
978 lng = 0; /* default is to not use minutes or append `s' */
979 s++;
f73dda09 980 if (DIGIT (*s)) /* `precision' */
726f6388 981 {
ccc6cda3
JA
982 prec = *s++ - '0';
983 if (prec > 3) prec = 3;
726f6388 984 }
ccc6cda3
JA
985 if (*s == 'l') /* `length extender' */
986 {
987 lng = 1;
988 s++;
989 }
990 if (*s == 'R' || *s == 'E')
991 len = mkfmt (ts, prec, lng, rs, rsf);
992 else if (*s == 'U')
993 len = mkfmt (ts, prec, lng, us, usf);
994 else if (*s == 'S')
995 len = mkfmt (ts, prec, lng, ss, ssf);
996 else
997 {
998 internal_error ("bad format character in time format: %c", *s);
999 free (str);
1000 return;
1001 }
1002 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1003 strcpy (str + sindex, ts);
1004 sindex += len;
1005 }
1006 }
1007
1008 str[sindex] = '\0';
1009 fprintf (fp, "%s\n", str);
1010 fflush (fp);
1011
1012 free (str);
1013}
1014
1015static int
1016time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1017 COMMAND *command;
1018 int asynchronous, pipe_in, pipe_out;
1019 struct fd_bitmap *fds_to_close;
1020{
d166f048 1021 int rv, posix_time, old_flags;
f73dda09 1022 time_t rs, us, ss;
ccc6cda3
JA
1023 int rsf, usf, ssf;
1024 int cpu;
1025 char *time_format;
1026
1027#if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1028 struct timeval real, user, sys;
1029 struct timeval before, after;
1030 struct timezone dtz;
1031 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1032#else
1033# if defined (HAVE_TIMES)
1034 clock_t tbefore, tafter, real, user, sys;
1035 struct tms before, after;
1036# endif
1037#endif
1038
1039#if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1040 gettimeofday (&before, &dtz);
1041 getrusage (RUSAGE_SELF, &selfb);
1042 getrusage (RUSAGE_CHILDREN, &kidsb);
1043#else
1044# if defined (HAVE_TIMES)
1045 tbefore = times (&before);
1046# endif
1047#endif
1048
1049 posix_time = (command->flags & CMD_TIME_POSIX);
1050
d166f048 1051 old_flags = command->flags;
ccc6cda3
JA
1052 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1053 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
d166f048 1054 command->flags = old_flags;
ccc6cda3 1055
f73dda09 1056 rs = us = ss = 0;
cce855bc
JA
1057 rsf = usf = ssf = cpu = 0;
1058
ccc6cda3
JA
1059#if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1060 gettimeofday (&after, &dtz);
1061 getrusage (RUSAGE_SELF, &selfa);
1062 getrusage (RUSAGE_CHILDREN, &kidsa);
1063
1064 difftimeval (&real, &before, &after);
1065 timeval_to_secs (&real, &rs, &rsf);
1066
1067 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1068 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1069 timeval_to_secs (&user, &us, &usf);
1070
1071 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1072 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1073 timeval_to_secs (&sys, &ss, &ssf);
1074
1075 cpu = timeval_to_cpu (&real, &user, &sys);
1076#else
1077# if defined (HAVE_TIMES)
1078 tafter = times (&after);
1079
1080 real = tafter - tbefore;
1081 clock_t_to_secs (real, &rs, &rsf);
1082
1083 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1084 clock_t_to_secs (user, &us, &usf);
1085
1086 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1087 clock_t_to_secs (sys, &ss, &ssf);
1088
d166f048 1089 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
ccc6cda3
JA
1090
1091# else
f73dda09 1092 rs = us = ss = 0;
ccc6cda3
JA
1093 rsf = usf = ssf = cpu = 0;
1094# endif
1095#endif
1096
1097 if (posix_time)
1098 time_format = POSIX_TIMEFORMAT;
1099 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1100 time_format = BASH_TIMEFORMAT;
1101
1102 if (time_format && *time_format)
1103 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1104
1105 return rv;
1106}
1107#endif /* COMMAND_TIMING */
1108
bb70624e 1109/* Execute a command that's supposed to be in a subshell. This must be
28ef6c31
JA
1110 called after make_child and we must be running in the child process.
1111 The caller will return or exit() immediately with the value this returns. */
bb70624e
JA
1112static int
1113execute_in_subshell (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1114 COMMAND *command;
1115 int asynchronous;
1116 int pipe_in, pipe_out;
1117 struct fd_bitmap *fds_to_close;
1118{
28ef6c31
JA
1119 int user_subshell, return_code, function_value, should_redir_stdin, invert;
1120 int ois;
bb70624e
JA
1121 COMMAND *tcom;
1122
f73dda09
JA
1123 USE_VAR(user_subshell);
1124 USE_VAR(invert);
1125 USE_VAR(tcom);
1126 USE_VAR(asynchronous);
1127
bb70624e
JA
1128 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
1129 pipe_in == NO_PIPE &&
1130 stdin_redirects (command->redirects) == 0);
1131
28ef6c31 1132 invert = (command->flags & CMD_INVERT_RETURN) != 0;
bb70624e 1133 user_subshell = command->type == cm_subshell || ((command->flags & CMD_WANT_SUBSHELL) != 0);
28ef6c31 1134
bb70624e
JA
1135 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
1136
1137 /* If a command is asynchronous in a subshell (like ( foo ) & or
1138 the special case of an asynchronous GROUP command where the
1139 the subshell bit is turned on down in case cm_group: below),
1140 turn off `asynchronous', so that two subshells aren't spawned.
1141
1142 This seems semantically correct to me. For example,
1143 ( foo ) & seems to say ``do the command `foo' in a subshell
1144 environment, but don't wait for that subshell to finish'',
1145 and "{ foo ; bar ; } &" seems to me to be like functions or
1146 builtins in the background, which executed in a subshell
1147 environment. I just don't see the need to fork two subshells. */
1148
1149 /* Don't fork again, we are already in a subshell. A `doubly
1150 async' shell is not interactive, however. */
1151 if (asynchronous)
1152 {
1153#if defined (JOB_CONTROL)
1154 /* If a construct like ( exec xxx yyy ) & is given while job
1155 control is active, we want to prevent exec from putting the
1156 subshell back into the original process group, carefully
1157 undoing all the work we just did in make_child. */
1158 original_pgrp = -1;
1159#endif /* JOB_CONTROL */
28ef6c31 1160 ois = interactive_shell;
bb70624e 1161 interactive_shell = 0;
28ef6c31
JA
1162 /* This test is to prevent alias expansion by interactive shells that
1163 run `(command) &' but to allow scripts that have enabled alias
1164 expansion with `shopt -s expand_alias' to continue to expand
1165 aliases. */
1166 if (ois != interactive_shell)
1167 expand_aliases = 0;
bb70624e
JA
1168 asynchronous = 0;
1169 }
1170
1171 /* Subshells are neither login nor interactive. */
1172 login_shell = interactive = 0;
1173
1174 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
1175
1176 reset_terminating_signals (); /* in sig.c */
1177 /* Cancel traps, in trap.c. */
1178 restore_original_signals ();
1179 if (asynchronous)
1180 setup_async_signals ();
1181
1182#if defined (JOB_CONTROL)
1183 set_sigchld_handler ();
1184#endif /* JOB_CONTROL */
1185
1186 set_sigint_handler ();
1187
1188#if defined (JOB_CONTROL)
1189 /* Delete all traces that there were any jobs running. This is
1190 only for subshells. */
1191 without_job_control ();
1192#endif /* JOB_CONTROL */
1193
1194 if (fds_to_close)
1195 close_fd_bitmap (fds_to_close);
1196
1197 do_piping (pipe_in, pipe_out);
1198
1199 /* If this is a user subshell, set a flag if stdin was redirected.
1200 This is used later to decide whether to redirect fd 0 to
1201 /dev/null for async commands in the subshell. This adds more
1202 sh compatibility, but I'm not sure it's the right thing to do. */
1203 if (user_subshell)
1204 {
1205 stdin_redir = stdin_redirects (command->redirects);
1206 restore_default_signal (0);
1207 }
1208
1209 /* If this is an asynchronous command (command &), we want to
1210 redirect the standard input from /dev/null in the absence of
1211 any specific redirection involving stdin. */
1212 if (should_redir_stdin && stdin_redir == 0)
1213 async_redirect_stdin ();
1214
1215 /* Do redirections, then dispose of them before recursive call. */
1216 if (command->redirects)
1217 {
1218 if (do_redirections (command->redirects, 1, 0, 0) != 0)
28ef6c31 1219 exit (invert ? EXECUTION_SUCCESS : EXECUTION_FAILURE);
bb70624e
JA
1220
1221 dispose_redirects (command->redirects);
1222 command->redirects = (REDIRECT *)NULL;
1223 }
1224
1225 tcom = (command->type == cm_subshell) ? command->value.Subshell->command : command;
1226
f73dda09
JA
1227 /* Make sure the subshell inherits any CMD_IGNORE_RETURN flag. */
1228 if ((command->flags & CMD_IGNORE_RETURN) && tcom != command)
1229 tcom->flags |= CMD_IGNORE_RETURN;
1230
bb70624e
JA
1231 /* If this is a simple command, tell execute_disk_command that it
1232 might be able to get away without forking and simply exec.
1233 This means things like ( sleep 10 ) will only cause one fork.
28ef6c31
JA
1234 If we're timing the command or inverting its return value, however,
1235 we cannot do this optimization. */
bb70624e 1236 if (user_subshell && (tcom->type == cm_simple || tcom->type == cm_subshell) &&
28ef6c31
JA
1237 ((tcom->flags & CMD_TIME_PIPELINE) == 0) &&
1238 ((tcom->flags & CMD_INVERT_RETURN) == 0))
bb70624e
JA
1239 {
1240 tcom->flags |= CMD_NO_FORK;
1241 if (tcom->type == cm_simple)
1242 tcom->value.Simple->flags |= CMD_NO_FORK;
1243 }
1244
28ef6c31
JA
1245 invert = (tcom->flags & CMD_INVERT_RETURN) != 0;
1246 tcom->flags &= ~CMD_INVERT_RETURN;
1247
bb70624e
JA
1248 /* If we're inside a function while executing this subshell, we
1249 need to handle a possible `return'. */
1250 function_value = 0;
1251 if (return_catch_flag)
1252 function_value = setjmp (return_catch);
1253
1254 if (function_value)
1255 return_code = return_catch_value;
1256 else
1257 return_code = execute_command_internal
1258 (tcom, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
1259
28ef6c31
JA
1260 /* If we are asked to, invert the return value. */
1261 if (invert)
1262 return_code = (return_code == EXECUTION_SUCCESS) ? EXECUTION_FAILURE
1263 : EXECUTION_SUCCESS;
1264
bb70624e
JA
1265 /* If we were explicitly placed in a subshell with (), we need
1266 to do the `shell cleanup' things, such as running traps[0]. */
1267 if (user_subshell && signal_is_trapped (0))
1268 {
1269 last_command_exit_value = return_code;
1270 return_code = run_exit_trap ();
1271 }
1272
1273 return (return_code);
1274 /* NOTREACHED */
1275}
1276
ccc6cda3
JA
1277static int
1278execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1279 COMMAND *command;
1280 int asynchronous, pipe_in, pipe_out;
1281 struct fd_bitmap *fds_to_close;
1282{
1283 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1284 COMMAND *cmd;
1285 struct fd_bitmap *fd_bitmap;
726f6388
JA
1286
1287#if defined (JOB_CONTROL)
ccc6cda3
JA
1288 sigset_t set, oset;
1289 BLOCK_CHILD (set, oset);
726f6388
JA
1290#endif /* JOB_CONTROL */
1291
ccc6cda3 1292 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
726f6388 1293
ccc6cda3
JA
1294 prev = pipe_in;
1295 cmd = command;
1296
1297 while (cmd && cmd->type == cm_connection &&
1298 cmd->value.Connection && cmd->value.Connection->connector == '|')
1299 {
1300 /* Make a pipeline between the two commands. */
1301 if (pipe (fildes) < 0)
1302 {
1303 sys_error ("pipe error");
726f6388 1304#if defined (JOB_CONTROL)
ccc6cda3
JA
1305 terminate_current_pipeline ();
1306 kill_current_pipeline ();
726f6388 1307#endif /* JOB_CONTROL */
ccc6cda3
JA
1308 last_command_exit_value = EXECUTION_FAILURE;
1309 /* The unwind-protects installed below will take care
1310 of closing all of the open file descriptors. */
1311 throw_to_top_level ();
1312 return (EXECUTION_FAILURE); /* XXX */
1313 }
1314
1315 /* Here is a problem: with the new file close-on-exec
1316 code, the read end of the pipe (fildes[0]) stays open
1317 in the first process, so that process will never get a
1318 SIGPIPE. There is no way to signal the first process
1319 that it should close fildes[0] after forking, so it
1320 remains open. No SIGPIPE is ever sent because there
1321 is still a file descriptor open for reading connected
1322 to the pipe. We take care of that here. This passes
1323 around a bitmap of file descriptors that must be
1324 closed after making a child process in execute_simple_command. */
1325
1326 /* We need fd_bitmap to be at least as big as fildes[0].
1327 If fildes[0] is less than fds_to_close->size, then
1328 use fds_to_close->size. */
1329 new_bitmap_size = (fildes[0] < fds_to_close->size)
1330 ? fds_to_close->size
1331 : fildes[0] + 8;
1332
1333 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1334
1335 /* Now copy the old information into the new bitmap. */
1336 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1337
1338 /* And mark the pipe file descriptors to be closed. */
1339 fd_bitmap->bitmap[fildes[0]] = 1;
1340
1341 /* In case there are pipe or out-of-processes errors, we
cce855bc 1342 want all these file descriptors to be closed when
ccc6cda3
JA
1343 unwind-protects are run, and the storage used for the
1344 bitmaps freed up. */
1345 begin_unwind_frame ("pipe-file-descriptors");
1346 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1347 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1348 if (prev >= 0)
1349 add_unwind_protect (close, prev);
1350 dummyfd = fildes[1];
1351 add_unwind_protect (close, dummyfd);
726f6388
JA
1352
1353#if defined (JOB_CONTROL)
f73dda09 1354 add_unwind_protect (restore_signal_mask, &oset);
726f6388
JA
1355#endif /* JOB_CONTROL */
1356
ccc6cda3
JA
1357 if (ignore_return && cmd->value.Connection->first)
1358 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1359 execute_command_internal (cmd->value.Connection->first, asynchronous,
1360 prev, fildes[1], fd_bitmap);
1361
1362 if (prev >= 0)
1363 close (prev);
1364
1365 prev = fildes[0];
1366 close (fildes[1]);
1367
1368 dispose_fd_bitmap (fd_bitmap);
1369 discard_unwind_frame ("pipe-file-descriptors");
726f6388 1370
ccc6cda3
JA
1371 cmd = cmd->value.Connection->second;
1372 }
1373
1374 /* Now execute the rightmost command in the pipeline. */
1375 if (ignore_return && cmd)
1376 cmd->flags |= CMD_IGNORE_RETURN;
1377 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
726f6388 1378
ccc6cda3
JA
1379 if (prev >= 0)
1380 close (prev);
726f6388
JA
1381
1382#if defined (JOB_CONTROL)
ccc6cda3 1383 UNBLOCK_CHILD (oset);
726f6388 1384#endif
726f6388 1385
ccc6cda3
JA
1386 return (exec_result);
1387}
1388
1389static int
1390execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1391 COMMAND *command;
1392 int asynchronous, pipe_in, pipe_out;
1393 struct fd_bitmap *fds_to_close;
1394{
d166f048 1395 REDIRECT *rp;
ccc6cda3
JA
1396 COMMAND *tc, *second;
1397 int ignore_return, exec_result;
1398
1399 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1400
1401 switch (command->value.Connection->connector)
1402 {
1403 /* Do the first command asynchronously. */
1404 case '&':
1405 tc = command->value.Connection->first;
1406 if (tc == 0)
1407 return (EXECUTION_SUCCESS);
1408
1409 rp = tc->redirects;
1410
d166f048 1411 if (ignore_return)
ccc6cda3 1412 tc->flags |= CMD_IGNORE_RETURN;
d166f048 1413 tc->flags |= CMD_AMPERSAND;
ccc6cda3 1414
f73dda09
JA
1415 /* If this shell was compiled without job control support,
1416 if we are currently in a subshell via `( xxx )', or if job
1417 control is not active then the standard input for an
1418 asynchronous command is forced to /dev/null. */
ccc6cda3 1419#if defined (JOB_CONTROL)
f73dda09 1420 if ((subshell_environment || !job_control) && !stdin_redir)
ccc6cda3
JA
1421#else
1422 if (!stdin_redir)
1423#endif /* JOB_CONTROL */
7117c2d2 1424 tc->flags |= CMD_STDIN_REDIR;
ccc6cda3
JA
1425
1426 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1427
d166f048 1428 if (tc->flags & CMD_STDIN_REDIR)
7117c2d2 1429 tc->flags &= ~CMD_STDIN_REDIR;
726f6388 1430
ccc6cda3
JA
1431 second = command->value.Connection->second;
1432 if (second)
1433 {
1434 if (ignore_return)
1435 second->flags |= CMD_IGNORE_RETURN;
726f6388 1436
ccc6cda3
JA
1437 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1438 }
726f6388 1439
ccc6cda3 1440 break;
726f6388 1441
ccc6cda3
JA
1442 /* Just call execute command on both sides. */
1443 case ';':
1444 if (ignore_return)
1445 {
1446 if (command->value.Connection->first)
1447 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1448 if (command->value.Connection->second)
1449 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
726f6388 1450 }
ccc6cda3
JA
1451 QUIT;
1452 execute_command (command->value.Connection->first);
1453 QUIT;
1454 exec_result = execute_command_internal (command->value.Connection->second,
1455 asynchronous, pipe_in, pipe_out,
1456 fds_to_close);
726f6388
JA
1457 break;
1458
ccc6cda3
JA
1459 case '|':
1460 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
726f6388
JA
1461 break;
1462
ccc6cda3
JA
1463 case AND_AND:
1464 case OR_OR:
1465 if (asynchronous)
1466 {
1467 /* If we have something like `a && b &' or `a || b &', run the
1468 && or || stuff in a subshell. Force a subshell and just call
1469 execute_command_internal again. Leave asynchronous on
1470 so that we get a report from the parent shell about the
1471 background job. */
1472 command->flags |= CMD_FORCE_SUBSHELL;
1473 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1474 break;
1475 }
726f6388 1476
ccc6cda3
JA
1477 /* Execute the first command. If the result of that is successful
1478 and the connector is AND_AND, or the result is not successful
1479 and the connector is OR_OR, then execute the second command,
1480 otherwise return. */
726f6388 1481
ccc6cda3
JA
1482 if (command->value.Connection->first)
1483 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
726f6388 1484
ccc6cda3
JA
1485 exec_result = execute_command (command->value.Connection->first);
1486 QUIT;
1487 if (((command->value.Connection->connector == AND_AND) &&
1488 (exec_result == EXECUTION_SUCCESS)) ||
1489 ((command->value.Connection->connector == OR_OR) &&
1490 (exec_result != EXECUTION_SUCCESS)))
1491 {
1492 if (ignore_return && command->value.Connection->second)
1493 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
726f6388 1494
ccc6cda3
JA
1495 exec_result = execute_command (command->value.Connection->second);
1496 }
1497 break;
1498
1499 default:
b72432fd 1500 command_error ("execute_connection", CMDERR_BADCONN, command->value.Connection->connector, 0);
ccc6cda3
JA
1501 jump_to_top_level (DISCARD);
1502 exec_result = EXECUTION_FAILURE;
726f6388
JA
1503 }
1504
ccc6cda3 1505 return exec_result;
726f6388
JA
1506}
1507
bb70624e
JA
1508#define REAP() \
1509 do \
1510 { \
1511 if (!interactive_shell) \
1512 reap_dead_jobs (); \
1513 } \
1514 while (0)
726f6388
JA
1515
1516/* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1517 DO command; DONE */
ccc6cda3 1518static int
726f6388
JA
1519execute_for_command (for_command)
1520 FOR_COM *for_command;
1521{
726f6388 1522 register WORD_LIST *releaser, *list;
ccc6cda3 1523 SHELL_VAR *v;
726f6388 1524 char *identifier;
ccc6cda3
JA
1525 int retval;
1526#if 0
726f6388 1527 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
ccc6cda3 1528#endif
726f6388
JA
1529
1530 if (check_identifier (for_command->name, 1) == 0)
ccc6cda3
JA
1531 {
1532 if (posixly_correct && interactive_shell == 0)
cce855bc
JA
1533 {
1534 last_command_exit_value = EX_USAGE;
1535 jump_to_top_level (EXITPROG);
1536 }
ccc6cda3
JA
1537 return (EXECUTION_FAILURE);
1538 }
726f6388
JA
1539
1540 loop_level++;
1541 identifier = for_command->name->word;
1542
1543 list = releaser = expand_words_no_vars (for_command->map_list);
1544
1545 begin_unwind_frame ("for");
1546 add_unwind_protect (dispose_words, releaser);
1547
ccc6cda3 1548#if 0
726f6388
JA
1549 if (lexical_scoping)
1550 {
1551 old_value = copy_variable (find_variable (identifier));
1552 if (old_value)
1553 add_unwind_protect (dispose_variable, old_value);
1554 }
ccc6cda3 1555#endif
726f6388
JA
1556
1557 if (for_command->flags & CMD_IGNORE_RETURN)
1558 for_command->action->flags |= CMD_IGNORE_RETURN;
1559
ccc6cda3 1560 for (retval = EXECUTION_SUCCESS; list; list = list->next)
726f6388
JA
1561 {
1562 QUIT;
ccc6cda3
JA
1563 this_command_name = (char *)NULL;
1564 v = bind_variable (identifier, list->word->word);
28ef6c31 1565 if (readonly_p (v) || noassign_p (v))
ccc6cda3 1566 {
28ef6c31 1567 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
ccc6cda3
JA
1568 {
1569 last_command_exit_value = EXECUTION_FAILURE;
1570 jump_to_top_level (FORCE_EOF);
1571 }
1572 else
1573 {
1574 run_unwind_frame ("for");
d166f048 1575 loop_level--;
ccc6cda3
JA
1576 return (EXECUTION_FAILURE);
1577 }
1578 }
1579 retval = execute_command (for_command->action);
726f6388
JA
1580 REAP ();
1581 QUIT;
1582
1583 if (breaking)
1584 {
ccc6cda3 1585 breaking--;
726f6388
JA
1586 break;
1587 }
1588
1589 if (continuing)
1590 {
1591 continuing--;
1592 if (continuing)
1593 break;
1594 }
726f6388
JA
1595 }
1596
1597 loop_level--;
1598
ccc6cda3 1599#if 0
726f6388
JA
1600 if (lexical_scoping)
1601 {
1602 if (!old_value)
7117c2d2 1603 unbind_variable (identifier);
726f6388
JA
1604 else
1605 {
1606 SHELL_VAR *new_value;
1607
1608 new_value = bind_variable (identifier, value_cell(old_value));
1609 new_value->attributes = old_value->attributes;
1610 dispose_variable (old_value);
1611 }
1612 }
ccc6cda3 1613#endif
726f6388
JA
1614
1615 dispose_words (releaser);
1616 discard_unwind_frame ("for");
1617 return (retval);
1618}
1619
bb70624e
JA
1620#if defined (ARITH_FOR_COMMAND)
1621/* Execute an arithmetic for command. The syntax is
1622
1623 for (( init ; step ; test ))
1624 do
1625 body
1626 done
1627
1628 The execution should be exactly equivalent to
1629
1630 eval \(\( init \)\)
1631 while eval \(\( test \)\) ; do
1632 body;
1633 eval \(\( step \)\)
1634 done
1635*/
7117c2d2 1636static intmax_t
bb70624e
JA
1637eval_arith_for_expr (l, okp)
1638 WORD_LIST *l;
1639 int *okp;
1640{
1641 WORD_LIST *new;
7117c2d2 1642 intmax_t expresult;
bb70624e
JA
1643
1644 new = expand_words_no_vars (l);
f73dda09
JA
1645 if (new)
1646 {
1647 if (echo_command_at_execute)
1648 xtrace_print_arith_cmd (new);
7117c2d2
JA
1649 this_command_name = "(("; /* )) for expression error messages */
1650 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
1651 run_debug_trap ();
f73dda09
JA
1652 expresult = evalexp (new->word->word, okp);
1653 dispose_words (new);
1654 }
1655 else
1656 {
1657 expresult = 0;
1658 if (okp)
1659 *okp = 1;
1660 }
bb70624e
JA
1661 return (expresult);
1662}
1663
1664static int
1665execute_arith_for_command (arith_for_command)
1666 ARITH_FOR_COM *arith_for_command;
1667{
7117c2d2
JA
1668 intmax_t expresult;
1669 int expok, body_status, arith_lineno, save_lineno;
bb70624e
JA
1670
1671 body_status = EXECUTION_SUCCESS;
1672 loop_level++;
1673
1674 if (arith_for_command->flags & CMD_IGNORE_RETURN)
1675 arith_for_command->action->flags |= CMD_IGNORE_RETURN;
1676
1677 this_command_name = "(("; /* )) for expression error messages */
1678
7117c2d2
JA
1679 /* save the starting line number of the command so we can reset
1680 line_number before executing each expression -- for $LINENO
1681 and the DEBUG trap. */
1682 arith_lineno = arith_for_command->line;
1683 if (variable_context && interactive_shell)
1684 line_number = arith_lineno -= function_line_number;
bb70624e
JA
1685
1686 /* Evaluate the initialization expression. */
1687 expresult = eval_arith_for_expr (arith_for_command->init, &expok);
1688 if (expok == 0)
1689 return (EXECUTION_FAILURE);
1690
1691 while (1)
1692 {
1693 /* Evaluate the test expression. */
7117c2d2
JA
1694 save_lineno = line_number;
1695 line_number = arith_lineno;
bb70624e 1696 expresult = eval_arith_for_expr (arith_for_command->test, &expok);
7117c2d2
JA
1697 line_number = save_lineno;
1698
bb70624e
JA
1699 if (expok == 0)
1700 {
1701 body_status = EXECUTION_FAILURE;
1702 break;
1703 }
1704 REAP ();
1705 if (expresult == 0)
28ef6c31 1706 break;
bb70624e
JA
1707
1708 /* Execute the body of the arithmetic for command. */
1709 QUIT;
1710 body_status = execute_command (arith_for_command->action);
1711 QUIT;
1712
1713 /* Handle any `break' or `continue' commands executed by the body. */
1714 if (breaking)
1715 {
1716 breaking--;
1717 break;
1718 }
1719
1720 if (continuing)
1721 {
1722 continuing--;
1723 if (continuing)
1724 break;
1725 }
1726
1727 /* Evaluate the step expression. */
7117c2d2
JA
1728 save_lineno = line_number;
1729 line_number = arith_lineno;
bb70624e 1730 expresult = eval_arith_for_expr (arith_for_command->step, &expok);
7117c2d2
JA
1731 line_number = save_lineno;
1732
bb70624e
JA
1733 if (expok == 0)
1734 {
1735 body_status = EXECUTION_FAILURE;
1736 break;
1737 }
1738 }
1739
1740 loop_level--;
1741 return (body_status);
1742}
1743#endif
1744
726f6388
JA
1745#if defined (SELECT_COMMAND)
1746static int LINES, COLS, tabsize;
1747
1748#define RP_SPACE ") "
1749#define RP_SPACE_LEN 2
1750
1751/* XXX - does not handle numbers > 1000000 at all. */
1752#define NUMBER_LEN(s) \
1753((s < 10) ? 1 \
1754 : ((s < 100) ? 2 \
1755 : ((s < 1000) ? 3 \
1756 : ((s < 10000) ? 4 \
1757 : ((s < 100000) ? 5 \
1758 : 6)))))
1759
1760static int
1761print_index_and_element (len, ind, list)
1762 int len, ind;
1763 WORD_LIST *list;
1764{
1765 register WORD_LIST *l;
1766 register int i;
1767
1768 if (list == 0)
1769 return (0);
ccc6cda3
JA
1770 for (i = ind, l = list; l && --i; l = l->next)
1771 ;
726f6388
JA
1772 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1773 return (STRLEN (l->word->word));
1774}
1775
1776static void
1777indent (from, to)
1778 int from, to;
1779{
1780 while (from < to)
1781 {
1782 if ((to / tabsize) > (from / tabsize))
1783 {
1784 putc ('\t', stderr);
1785 from += tabsize - from % tabsize;
1786 }
1787 else
1788 {
1789 putc (' ', stderr);
1790 from++;
1791 }
1792 }
1793}
1794
1795static void
1796print_select_list (list, list_len, max_elem_len, indices_len)
1797 WORD_LIST *list;
1798 int list_len, max_elem_len, indices_len;
1799{
1800 int ind, row, elem_len, pos, cols, rows;
1801 int first_column_indices_len, other_indices_len;
1802
1803 if (list == 0)
1804 {
1805 putc ('\n', stderr);
1806 return;
1807 }
1808
ccc6cda3 1809 cols = max_elem_len ? COLS / max_elem_len : 1;
726f6388
JA
1810 if (cols == 0)
1811 cols = 1;
1812 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1813 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1814
1815 if (rows == 1)
1816 {
1817 rows = cols;
1818 cols = 1;
1819 }
1820
1821 first_column_indices_len = NUMBER_LEN (rows);
1822 other_indices_len = indices_len;
1823
1824 for (row = 0; row < rows; row++)
1825 {
1826 ind = row;
1827 pos = 0;
1828 while (1)
1829 {
1830 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1831 elem_len = print_index_and_element (indices_len, ind + 1, list);
1832 elem_len += indices_len + RP_SPACE_LEN;
1833 ind += rows;
1834 if (ind >= list_len)
1835 break;
1836 indent (pos + elem_len, pos + max_elem_len);
1837 pos += max_elem_len;
1838 }
1839 putc ('\n', stderr);
1840 }
1841}
1842
1843/* Print the elements of LIST, one per line, preceded by an index from 1 to
1844 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1845 If the number is between 1 and LIST_LEN, return that selection. If EOF
e8ce775d
JA
1846 is read, return a null string. If a blank line is entered, or an invalid
1847 number is entered, the loop is executed again. */
726f6388 1848static char *
7117c2d2 1849select_query (list, list_len, prompt, print_menu)
726f6388
JA
1850 WORD_LIST *list;
1851 int list_len;
1852 char *prompt;
7117c2d2 1853 int print_menu;
726f6388 1854{
e8ce775d 1855 int max_elem_len, indices_len, len;
7117c2d2 1856 intmax_t reply;
726f6388
JA
1857 WORD_LIST *l;
1858 char *repl_string, *t;
1859
1860 t = get_string_value ("LINES");
1861 LINES = (t && *t) ? atoi (t) : 24;
1862 t = get_string_value ("COLUMNS");
1863 COLS = (t && *t) ? atoi (t) : 80;
1864
1865#if 0
1866 t = get_string_value ("TABSIZE");
1867 tabsize = (t && *t) ? atoi (t) : 8;
1868 if (tabsize <= 0)
1869 tabsize = 8;
1870#else
1871 tabsize = 8;
1872#endif
1873
1874 max_elem_len = 0;
1875 for (l = list; l; l = l->next)
1876 {
1877 len = STRLEN (l->word->word);
1878 if (len > max_elem_len)
cce855bc 1879 max_elem_len = len;
726f6388
JA
1880 }
1881 indices_len = NUMBER_LEN (list_len);
1882 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1883
1884 while (1)
1885 {
7117c2d2
JA
1886 if (print_menu)
1887 print_select_list (list, list_len, max_elem_len, indices_len);
ccc6cda3
JA
1888 fprintf (stderr, "%s", prompt);
1889 fflush (stderr);
726f6388
JA
1890 QUIT;
1891
1892 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1893 {
1894 putchar ('\n');
1895 return ((char *)NULL);
1896 }
1897 repl_string = get_string_value ("REPLY");
1898 if (*repl_string == 0)
7117c2d2
JA
1899 {
1900 print_menu = 1;
1901 continue;
1902 }
e8ce775d 1903 if (legal_number (repl_string, &reply) == 0)
cce855bc 1904 return "";
726f6388
JA
1905 if (reply < 1 || reply > list_len)
1906 return "";
1907
ccc6cda3
JA
1908 for (l = list; l && --reply; l = l->next)
1909 ;
726f6388
JA
1910 return (l->word->word);
1911 }
1912}
1913
1914/* Execute a SELECT command. The syntax is:
1915 SELECT word IN list DO command_list DONE
1916 Only `break' or `return' in command_list will terminate
1917 the command. */
ccc6cda3 1918static int
726f6388
JA
1919execute_select_command (select_command)
1920 SELECT_COM *select_command;
1921{
1922 WORD_LIST *releaser, *list;
ccc6cda3 1923 SHELL_VAR *v;
726f6388 1924 char *identifier, *ps3_prompt, *selection;
7117c2d2
JA
1925 int retval, list_len, show_menu;
1926
726f6388
JA
1927 if (check_identifier (select_command->name, 1) == 0)
1928 return (EXECUTION_FAILURE);
1929
1930 loop_level++;
1931 identifier = select_command->name->word;
1932
1933 /* command and arithmetic substitution, parameter and variable expansion,
1934 word splitting, pathname expansion, and quote removal. */
1935 list = releaser = expand_words_no_vars (select_command->map_list);
1936 list_len = list_length (list);
1937 if (list == 0 || list_len == 0)
1938 {
1939 if (list)
1940 dispose_words (list);
1941 return (EXECUTION_SUCCESS);
1942 }
1943
1944 begin_unwind_frame ("select");
1945 add_unwind_protect (dispose_words, releaser);
1946
726f6388
JA
1947 if (select_command->flags & CMD_IGNORE_RETURN)
1948 select_command->action->flags |= CMD_IGNORE_RETURN;
1949
ccc6cda3 1950 retval = EXECUTION_SUCCESS;
7117c2d2 1951 show_menu = 1;
ccc6cda3 1952
726f6388
JA
1953 while (1)
1954 {
1955 ps3_prompt = get_string_value ("PS3");
ccc6cda3 1956 if (ps3_prompt == 0)
726f6388
JA
1957 ps3_prompt = "#? ";
1958
1959 QUIT;
7117c2d2 1960 selection = select_query (list, list_len, ps3_prompt, show_menu);
726f6388
JA
1961 QUIT;
1962 if (selection == 0)
7117c2d2
JA
1963 {
1964 /* select_query returns EXECUTION_FAILURE if the read builtin
1965 fails, so we want to return failure in this case. */
1966 retval = EXECUTION_FAILURE;
1967 break;
1968 }
ccc6cda3
JA
1969
1970 v = bind_variable (identifier, selection);
28ef6c31 1971 if (readonly_p (v) || noassign_p (v))
ccc6cda3 1972 {
28ef6c31 1973 if (readonly_p (v) && interactive_shell == 0 && posixly_correct)
ccc6cda3
JA
1974 {
1975 last_command_exit_value = EXECUTION_FAILURE;
1976 jump_to_top_level (FORCE_EOF);
1977 }
1978 else
1979 {
1980 run_unwind_frame ("select");
1981 return (EXECUTION_FAILURE);
1982 }
1983 }
726f6388 1984
f73dda09 1985 retval = execute_command (select_command->action);
726f6388
JA
1986
1987 REAP ();
1988 QUIT;
1989
1990 if (breaking)
1991 {
1992 breaking--;
1993 break;
1994 }
bb70624e
JA
1995
1996 if (continuing)
1997 {
1998 continuing--;
1999 if (continuing)
2000 break;
2001 }
7117c2d2
JA
2002
2003#if defined (KSH_COMPATIBLE_SELECT)
2004 show_menu = 0;
2005 selection = get_string_value ("REPLY");
2006 if (selection && *selection == '\0')
2007 show_menu = 1;
2008#endif
726f6388
JA
2009 }
2010
2011 loop_level--;
2012
726f6388
JA
2013 run_unwind_frame ("select");
2014 return (retval);
2015}
2016#endif /* SELECT_COMMAND */
2017
2018/* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
2019 The pattern_list is a linked list of pattern clauses; each clause contains
2020 some patterns to compare word_desc against, and an associated command to
2021 execute. */
ccc6cda3 2022static int
726f6388
JA
2023execute_case_command (case_command)
2024 CASE_COM *case_command;
2025{
2026 register WORD_LIST *list;
ccc6cda3 2027 WORD_LIST *wlist, *es;
726f6388 2028 PATTERN_LIST *clauses;
ccc6cda3
JA
2029 char *word, *pattern;
2030 int retval, match, ignore_return;
726f6388
JA
2031
2032 /* Posix.2 specifies that the WORD is tilde expanded. */
2033 if (member ('~', case_command->word->word))
2034 {
7117c2d2 2035 word = bash_tilde_expand (case_command->word->word, 0);
726f6388
JA
2036 free (case_command->word->word);
2037 case_command->word->word = word;
2038 }
2039
28ef6c31 2040 wlist = expand_word_unsplit (case_command->word, 0);
ccc6cda3
JA
2041 word = wlist ? string_list (wlist) : savestring ("");
2042 dispose_words (wlist);
2043
726f6388 2044 retval = EXECUTION_SUCCESS;
ccc6cda3 2045 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
726f6388
JA
2046
2047 begin_unwind_frame ("case");
726f6388
JA
2048 add_unwind_protect ((Function *)xfree, word);
2049
ccc6cda3
JA
2050#define EXIT_CASE() goto exit_case_command
2051
2052 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
726f6388
JA
2053 {
2054 QUIT;
ccc6cda3 2055 for (list = clauses->patterns; list; list = list->next)
726f6388 2056 {
726f6388
JA
2057 /* Posix.2 specifies to tilde expand each member of the pattern
2058 list. */
2059 if (member ('~', list->word->word))
2060 {
7117c2d2 2061 pattern = bash_tilde_expand (list->word->word, 0);
726f6388 2062 free (list->word->word);
ccc6cda3 2063 list->word->word = pattern;
726f6388
JA
2064 }
2065
2066 es = expand_word_leave_quoted (list->word, 0);
2067
2068 if (es && es->word && es->word->word && *(es->word->word))
cce855bc 2069 pattern = quote_string_for_globbing (es->word->word, QGLOB_CVTNULL);
726f6388 2070 else
ccc6cda3 2071 {
f73dda09 2072 pattern = (char *)xmalloc (1);
ccc6cda3
JA
2073 pattern[0] = '\0';
2074 }
726f6388
JA
2075
2076 /* Since the pattern does not undergo quote removal (as per
f73dda09 2077 Posix.2, section 3.9.4.3), the strmatch () call must be able
726f6388 2078 to recognize backslashes as escape characters. */
f73dda09 2079 match = strmatch (pattern, word, FNMATCH_EXTFLAG) != FNM_NOMATCH;
726f6388
JA
2080 free (pattern);
2081
2082 dispose_words (es);
2083
2084 if (match)
2085 {
ccc6cda3 2086 if (clauses->action && ignore_return)
726f6388 2087 clauses->action->flags |= CMD_IGNORE_RETURN;
ccc6cda3
JA
2088 retval = execute_command (clauses->action);
2089 EXIT_CASE ();
726f6388
JA
2090 }
2091
726f6388
JA
2092 QUIT;
2093 }
726f6388
JA
2094 }
2095
ccc6cda3
JA
2096exit_case_command:
2097 free (word);
726f6388 2098 discard_unwind_frame ("case");
726f6388
JA
2099 return (retval);
2100}
2101
2102#define CMD_WHILE 0
2103#define CMD_UNTIL 1
2104
2105/* The WHILE command. Syntax: WHILE test DO action; DONE.
2106 Repeatedly execute action while executing test produces
2107 EXECUTION_SUCCESS. */
ccc6cda3 2108static int
726f6388
JA
2109execute_while_command (while_command)
2110 WHILE_COM *while_command;
2111{
2112 return (execute_while_or_until (while_command, CMD_WHILE));
2113}
2114
2115/* UNTIL is just like WHILE except that the test result is negated. */
ccc6cda3 2116static int
726f6388
JA
2117execute_until_command (while_command)
2118 WHILE_COM *while_command;
2119{
2120 return (execute_while_or_until (while_command, CMD_UNTIL));
2121}
2122
2123/* The body for both while and until. The only difference between the
2124 two is that the test value is treated differently. TYPE is
2125 CMD_WHILE or CMD_UNTIL. The return value for both commands should
2126 be EXECUTION_SUCCESS if no commands in the body are executed, and
2127 the status of the last command executed in the body otherwise. */
ccc6cda3 2128static int
726f6388
JA
2129execute_while_or_until (while_command, type)
2130 WHILE_COM *while_command;
2131 int type;
2132{
2133 int return_value, body_status;
2134
2135 body_status = EXECUTION_SUCCESS;
2136 loop_level++;
2137
2138 while_command->test->flags |= CMD_IGNORE_RETURN;
2139 if (while_command->flags & CMD_IGNORE_RETURN)
2140 while_command->action->flags |= CMD_IGNORE_RETURN;
2141
2142 while (1)
2143 {
2144 return_value = execute_command (while_command->test);
2145 REAP ();
2146
f73dda09
JA
2147 /* Need to handle `break' in the test when we would break out of the
2148 loop. The job control code will set `breaking' to loop_level
2149 when a job in a loop is stopped with SIGTSTP. If the stopped job
2150 is in the loop test, `breaking' will not be reset unless we do
2151 this, and the shell will cease to execute commands. */
726f6388 2152 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
f73dda09
JA
2153 {
2154 if (breaking)
2155 breaking--;
2156 break;
2157 }
726f6388 2158 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
f73dda09
JA
2159 {
2160 if (breaking)
2161 breaking--;
2162 break;
2163 }
726f6388
JA
2164
2165 QUIT;
2166 body_status = execute_command (while_command->action);
2167 QUIT;
2168
2169 if (breaking)
2170 {
2171 breaking--;
2172 break;
2173 }
2174
2175 if (continuing)
2176 {
2177 continuing--;
2178 if (continuing)
2179 break;
2180 }
2181 }
2182 loop_level--;
2183
2184 return (body_status);
2185}
2186
2187/* IF test THEN command [ELSE command].
2188 IF also allows ELIF in the place of ELSE IF, but
2189 the parser makes *that* stupidity transparent. */
ccc6cda3 2190static int
726f6388
JA
2191execute_if_command (if_command)
2192 IF_COM *if_command;
2193{
2194 int return_value;
2195
2196 if_command->test->flags |= CMD_IGNORE_RETURN;
2197 return_value = execute_command (if_command->test);
2198
2199 if (return_value == EXECUTION_SUCCESS)
2200 {
2201 QUIT;
ccc6cda3 2202
726f6388 2203 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
ccc6cda3
JA
2204 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2205
726f6388
JA
2206 return (execute_command (if_command->true_case));
2207 }
2208 else
2209 {
2210 QUIT;
2211
2212 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2213 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2214
2215 return (execute_command (if_command->false_case));
2216 }
2217}
2218
cce855bc
JA
2219#if defined (DPAREN_ARITHMETIC)
2220static int
2221execute_arith_command (arith_command)
2222 ARITH_COM *arith_command;
2223{
f73dda09 2224 int expok;
7117c2d2 2225 intmax_t expresult;
f73dda09 2226 WORD_LIST *new;
cce855bc 2227
f73dda09 2228 expresult = 0;
cce855bc 2229
b72432fd 2230 this_command_name = "(("; /* )) */
cce855bc 2231 /* If we're in a function, update the line number information. */
7117c2d2 2232 if (variable_context && interactive_shell)
cce855bc
JA
2233 line_number = arith_command->line - function_line_number;
2234
7117c2d2
JA
2235 /* Run the debug trap before each arithmetic command, but do it after we
2236 update the line number information and before we expand the various
2237 words in the expression. */
2238 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2239 run_debug_trap ();
2240
cce855bc
JA
2241 new = expand_words (arith_command->exp);
2242
2243 /* If we're tracing, make a new word list with `((' at the front and `))'
2244 at the back and print it. */
2245 if (echo_command_at_execute)
2246 xtrace_print_arith_cmd (new);
2247
f73dda09 2248 expresult = evalexp (new->word->word, &expok);
cce855bc
JA
2249 dispose_words (new);
2250
2251 if (expok == 0)
2252 return (EXECUTION_FAILURE);
2253
f73dda09 2254 return (expresult == 0 ? EXECUTION_FAILURE : EXECUTION_SUCCESS);
cce855bc
JA
2255}
2256#endif /* DPAREN_ARITHMETIC */
2257
2258#if defined (COND_COMMAND)
2259
2260static char *nullstr = "";
2261
2262static int
2263execute_cond_node (cond)
2264 COND_COM *cond;
2265{
f73dda09
JA
2266 int result, invert, patmatch;
2267 char *arg1, *arg2;
cce855bc
JA
2268
2269 invert = (cond->flags & CMD_INVERT_RETURN);
2270
2271 if (cond->type == COND_EXPR)
2272 result = execute_cond_node (cond->left);
2273 else if (cond->type == COND_OR)
2274 {
2275 result = execute_cond_node (cond->left);
2276 if (result != EXECUTION_SUCCESS)
2277 result = execute_cond_node (cond->right);
2278 }
2279 else if (cond->type == COND_AND)
2280 {
2281 result = execute_cond_node (cond->left);
2282 if (result == EXECUTION_SUCCESS)
2283 result = execute_cond_node (cond->right);
2284 }
2285 else if (cond->type == COND_UNARY)
2286 {
2287 arg1 = cond_expand_word (cond->left->op, 0);
2288 if (arg1 == 0)
2289 arg1 = nullstr;
2290 if (echo_command_at_execute)
2291 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, (char *)NULL);
2292 result = unary_test (cond->op->word, arg1) ? EXECUTION_SUCCESS : EXECUTION_FAILURE;
2293 if (arg1 != nullstr)
2294 free (arg1);
2295 }
2296 else if (cond->type == COND_BINARY)
2297 {
b72432fd
JA
2298 patmatch = ((cond->op->word[1] == '=') && (cond->op->word[2] == '\0') &&
2299 (cond->op->word[0] == '!' || cond->op->word[0] == '=') ||
2300 (cond->op->word[0] == '=' && cond->op->word[1] == '\0'));
cce855bc
JA
2301
2302 arg1 = cond_expand_word (cond->left->op, 0);
2303 if (arg1 == 0)
2304 arg1 = nullstr;
2305 arg2 = cond_expand_word (cond->right->op, patmatch);
2306 if (arg2 == 0)
2307 arg2 = nullstr;
2308
2309 if (echo_command_at_execute)
2310 xtrace_print_cond_term (cond->type, invert, cond->op, arg1, arg2);
2311
2312 result = binary_test (cond->op->word, arg1, arg2, TEST_PATMATCH|TEST_ARITHEXP)
2313 ? EXECUTION_SUCCESS
2314 : EXECUTION_FAILURE;
2315 if (arg1 != nullstr)
2316 free (arg1);
2317 if (arg2 != nullstr)
2318 free (arg2);
2319 }
2320 else
2321 {
b72432fd 2322 command_error ("execute_cond_node", CMDERR_BADTYPE, cond->type, 0);
cce855bc
JA
2323 jump_to_top_level (DISCARD);
2324 result = EXECUTION_FAILURE;
2325 }
2326
2327 if (invert)
2328 result = (result == EXECUTION_SUCCESS) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
2329
2330 return result;
2331}
2332
2333static int
2334execute_cond_command (cond_command)
2335 COND_COM *cond_command;
2336{
2337 int result;
2338
2339 result = EXECUTION_SUCCESS;
2340
2341 this_command_name = "[[";
2342 /* If we're in a function, update the line number information. */
7117c2d2 2343 if (variable_context && interactive_shell)
cce855bc
JA
2344 line_number = cond_command->line - function_line_number;
2345
7117c2d2
JA
2346 /* Run the debug trap before each conditional command, but do it after we
2347 update the line number information. */
2348 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2349 run_debug_trap ();
2350
cce855bc
JA
2351#if 0
2352 debug_print_cond_command (cond_command);
2353#endif
2354 last_command_exit_value = result = execute_cond_node (cond_command);
2355 return (result);
2356}
2357#endif /* COND_COMMAND */
2358
726f6388
JA
2359static void
2360bind_lastarg (arg)
2361 char *arg;
2362{
2363 SHELL_VAR *var;
2364
ccc6cda3 2365 if (arg == 0)
726f6388
JA
2366 arg = "";
2367 var = bind_variable ("_", arg);
bb70624e 2368 VUNSETATTR (var, att_exported);
726f6388
JA
2369}
2370
ccc6cda3
JA
2371/* Execute a null command. Fork a subshell if the command uses pipes or is
2372 to be run asynchronously. This handles all the side effects that are
2373 supposed to take place. */
2374static int
2375execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2376 REDIRECT *redirects;
bb70624e
JA
2377 int pipe_in, pipe_out, async;
2378 pid_t old_last_command_subst_pid;
ccc6cda3
JA
2379{
2380 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2381 {
2382 /* We have a null command, but we really want a subshell to take
2383 care of it. Just fork, do piping and redirections, and exit. */
2384 if (make_child ((char *)NULL, async) == 0)
2385 {
2386 /* Cancel traps, in trap.c. */
2387 restore_original_signals (); /* XXX */
2388
2389 do_piping (pipe_in, pipe_out);
2390
2391 subshell_environment = SUBSHELL_ASYNC;
2392
2393 if (do_redirections (redirects, 1, 0, 0) == 0)
2394 exit (EXECUTION_SUCCESS);
2395 else
2396 exit (EXECUTION_FAILURE);
2397 }
2398 else
2399 {
2400 close_pipes (pipe_in, pipe_out);
2401#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2402 unlink_fifo_list ();
2403#endif
2404 return (EXECUTION_SUCCESS);
2405 }
2406 }
2407 else
2408 {
2409 /* Even if there aren't any command names, pretend to do the
2410 redirections that are specified. The user expects the side
2411 effects to take place. If the redirections fail, then return
2412 failure. Otherwise, if a command substitution took place while
2413 expanding the command or a redirection, return the value of that
2414 substitution. Otherwise, return EXECUTION_SUCCESS. */
2415
2416 if (do_redirections (redirects, 0, 0, 0) != 0)
2417 return (EXECUTION_FAILURE);
2418 else if (old_last_command_subst_pid != last_command_subst_pid)
2419 return (last_command_exit_value);
2420 else
2421 return (EXECUTION_SUCCESS);
2422 }
2423}
2424
2425/* This is a hack to suppress word splitting for assignment statements
2426 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2427static void
2428fix_assignment_words (words)
2429 WORD_LIST *words;
2430{
2431 WORD_LIST *w;
2432 struct builtin *b;
2433
2434 if (words == 0)
2435 return;
2436
7117c2d2 2437 b = 0;
ccc6cda3
JA
2438
2439 for (w = words; w; w = w->next)
2440 if (w->word->flags & W_ASSIGNMENT)
7117c2d2
JA
2441 {
2442 if (b == 0)
2443 {
2444 b = builtin_address_internal (words->word->word, 0);
2445 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2446 return;
2447 }
2448 w->word->flags |= (W_NOSPLIT|W_NOGLOB|W_TILDEEXP);
2449 }
ccc6cda3
JA
2450}
2451
726f6388
JA
2452/* The meaty part of all the executions. We have to start hacking the
2453 real execution of commands here. Fork a process, set things up,
2454 execute the command. */
ccc6cda3 2455static int
726f6388
JA
2456execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2457 SIMPLE_COM *simple_command;
2458 int pipe_in, pipe_out, async;
2459 struct fd_bitmap *fds_to_close;
2460{
2461 WORD_LIST *words, *lastword;
ccc6cda3 2462 char *command_line, *lastarg, *temp;
bc4cd23c 2463 int first_word_quoted, result, builtin_is_special, already_forked, dofork;
b72432fd 2464 pid_t old_last_command_subst_pid, old_last_async_pid;
f73dda09 2465 sh_builtin_func_t *builtin;
ccc6cda3 2466 SHELL_VAR *func;
726f6388
JA
2467
2468 result = EXECUTION_SUCCESS;
ccc6cda3 2469 special_builtin_failed = builtin_is_special = 0;
cce855bc 2470 command_line = (char *)0;
726f6388 2471
ccc6cda3 2472 /* If we're in a function, update the line number information. */
7117c2d2 2473 if (variable_context && interactive_shell)
726f6388
JA
2474 line_number = simple_command->line - function_line_number;
2475
7117c2d2
JA
2476 /* Run the debug trap before each simple command, but do it after we
2477 update the line number information. */
2478 if (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2479 run_debug_trap ();
2480
726f6388
JA
2481 /* Remember what this command line looks like at invocation. */
2482 command_string_index = 0;
2483 print_simple_command (simple_command);
726f6388
JA
2484
2485 first_word_quoted =
ccc6cda3 2486 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
726f6388
JA
2487
2488 old_last_command_subst_pid = last_command_subst_pid;
b72432fd 2489 old_last_async_pid = last_asynchronous_pid;
726f6388 2490
bc4cd23c
JA
2491 already_forked = dofork = 0;
2492
2493 /* If we're in a pipeline or run in the background, set DOFORK so we
2494 make the child early, before word expansion. This keeps assignment
2495 statements from affecting the parent shell's environment when they
2496 should not. */
2497 dofork = pipe_in != NO_PIPE || pipe_out != NO_PIPE || async;
2498
2499 /* Something like `%2 &' should restart job 2 in the background, not cause
2500 the shell to fork here. */
2501 if (dofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE &&
2502 simple_command->words && simple_command->words->word &&
2503 simple_command->words->word->word &&
2504 (simple_command->words->word->word[0] == '%'))
2505 dofork = 0;
2506
2507 if (dofork)
cce855bc
JA
2508 {
2509 /* XXX memory leak if expand_words() error causes a jump_to_top_level */
2510 command_line = savestring (the_printed_command);
2511
bb70624e
JA
2512 /* Do this now, because execute_disk_command will do it anyway in the
2513 vast majority of cases. */
2514 maybe_make_export_env ();
2515
cce855bc
JA
2516 if (make_child (command_line, async) == 0)
2517 {
2518 already_forked = 1;
2519 simple_command->flags |= CMD_NO_FORK;
2520
28ef6c31
JA
2521 subshell_environment = (pipe_in != NO_PIPE || pipe_out != NO_PIPE)
2522 ? (SUBSHELL_PIPE|SUBSHELL_FORK)
2523 : (SUBSHELL_ASYNC|SUBSHELL_FORK);
2524
bb70624e
JA
2525 /* We need to do this before piping to handle some really
2526 pathological cases where one of the pipe file descriptors
2527 is < 2. */
2528 if (fds_to_close)
2529 close_fd_bitmap (fds_to_close);
2530
cce855bc 2531 do_piping (pipe_in, pipe_out);
f73dda09 2532 pipe_in = pipe_out = NO_PIPE;
cce855bc 2533
b72432fd 2534 last_asynchronous_pid = old_last_async_pid;
cce855bc
JA
2535 }
2536 else
2537 {
2538 close_pipes (pipe_in, pipe_out);
2539#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2540 unlink_fifo_list ();
2541#endif
2542 command_line = (char *)NULL; /* don't free this. */
2543 bind_lastarg ((char *)NULL);
2544 return (result);
2545 }
2546 }
2547
726f6388
JA
2548 /* If we are re-running this as the result of executing the `command'
2549 builtin, do not expand the command words a second time. */
2550 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2551 {
2552 current_fds_to_close = fds_to_close;
ccc6cda3 2553 fix_assignment_words (simple_command->words);
726f6388
JA
2554 words = expand_words (simple_command->words);
2555 current_fds_to_close = (struct fd_bitmap *)NULL;
2556 }
2557 else
2558 words = copy_word_list (simple_command->words);
2559
726f6388
JA
2560 /* It is possible for WORDS not to have anything left in it.
2561 Perhaps all the words consisted of `$foo', and there was
2562 no variable `$foo'. */
ccc6cda3 2563 if (words == 0)
726f6388 2564 {
ccc6cda3 2565 result = execute_null_command (simple_command->redirects,
cce855bc
JA
2566 pipe_in, pipe_out,
2567 already_forked ? 0 : async,
ccc6cda3 2568 old_last_command_subst_pid);
cce855bc
JA
2569 if (already_forked)
2570 exit (result);
2571 else
2572 {
2573 bind_lastarg ((char *)NULL);
2574 set_pipestatus_from_exit (result);
2575 return (result);
2576 }
ccc6cda3 2577 }
726f6388 2578
ccc6cda3 2579 lastarg = (char *)NULL;
726f6388 2580
ccc6cda3 2581 begin_unwind_frame ("simple-command");
726f6388 2582
ccc6cda3
JA
2583 if (echo_command_at_execute)
2584 xtrace_print_word_list (words);
726f6388 2585
f73dda09 2586 builtin = (sh_builtin_func_t *)NULL;
ccc6cda3
JA
2587 func = (SHELL_VAR *)NULL;
2588 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2589 {
2590 /* Posix.2 says special builtins are found before functions. We
2591 don't set builtin_is_special anywhere other than here, because
2592 this path is followed only when the `command' builtin is *not*
2593 being used, and we don't want to exit the shell if a special
2594 builtin executed with `command builtin' fails. `command' is not
2595 a special builtin. */
2596 if (posixly_correct)
2597 {
2598 builtin = find_special_builtin (words->word->word);
2599 if (builtin)
2600 builtin_is_special = 1;
726f6388 2601 }
ccc6cda3 2602 if (builtin == 0)
726f6388 2603 func = find_function (words->word->word);
ccc6cda3 2604 }
726f6388 2605
ccc6cda3
JA
2606 add_unwind_protect (dispose_words, words);
2607 QUIT;
726f6388 2608
ccc6cda3
JA
2609 /* Bind the last word in this command to "$_" after execution. */
2610 for (lastword = words; lastword->next; lastword = lastword->next)
2611 ;
2612 lastarg = lastword->word->word;
726f6388
JA
2613
2614#if defined (JOB_CONTROL)
ccc6cda3 2615 /* Is this command a job control related thing? */
cce855bc 2616 if (words->word->word[0] == '%' && already_forked == 0)
ccc6cda3
JA
2617 {
2618 this_command_name = async ? "bg" : "fg";
726f6388 2619 last_shell_builtin = this_shell_builtin;
ccc6cda3
JA
2620 this_shell_builtin = builtin_address (this_command_name);
2621 result = (*this_shell_builtin) (words);
2622 goto return_result;
2623 }
726f6388 2624
ccc6cda3
JA
2625 /* One other possiblilty. The user may want to resume an existing job.
2626 If they do, find out whether this word is a candidate for a running
2627 job. */
cce855bc 2628 if (job_control && already_forked == 0 && async == 0 &&
ccc6cda3
JA
2629 !first_word_quoted &&
2630 !words->next &&
2631 words->word->word[0] &&
2632 !simple_command->redirects &&
2633 pipe_in == NO_PIPE &&
2634 pipe_out == NO_PIPE &&
2635 (temp = get_string_value ("auto_resume")))
2636 {
7117c2d2 2637 int job, jflags, started_status;
ccc6cda3 2638
7117c2d2
JA
2639 jflags = JM_STOPPED|JM_FIRSTMATCH;
2640 if (STREQ (temp, "exact"))
2641 jflags |= JM_EXACT;
2642 else if (STREQ (temp, "substring"))
2643 jflags |= JM_SUBSTRING;
2644 else
2645 jflags |= JM_PREFIX;
2646 job = get_job_by_name (words->word->word, jflags);
2647 if (job != NO_JOB)
726f6388 2648 {
7117c2d2
JA
2649 run_unwind_frame ("simple-command");
2650 this_command_name = "fg";
2651 last_shell_builtin = this_shell_builtin;
2652 this_shell_builtin = builtin_address ("fg");
ccc6cda3 2653
7117c2d2
JA
2654 started_status = start_job (job, 1);
2655 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
726f6388 2656 }
ccc6cda3
JA
2657 }
2658#endif /* JOB_CONTROL */
726f6388 2659
ccc6cda3
JA
2660 /* Remember the name of this command globally. */
2661 this_command_name = words->word->word;
726f6388 2662
ccc6cda3
JA
2663 QUIT;
2664
2665 /* This command could be a shell builtin or a user-defined function.
2666 We have already found special builtins by this time, so we do not
2667 set builtin_is_special. If this is a function or builtin, and we
2668 have pipes, then fork a subshell in here. Otherwise, just execute
2669 the command directly. */
2670 if (func == 0 && builtin == 0)
2671 builtin = find_shell_builtin (this_command_name);
2672
2673 last_shell_builtin = this_shell_builtin;
2674 this_shell_builtin = builtin;
2675
2676 if (builtin || func)
726f6388 2677 {
28ef6c31 2678 if (already_forked)
726f6388 2679 {
cce855bc
JA
2680 /* reset_terminating_signals (); */ /* XXX */
2681 /* Cancel traps, in trap.c. */
2682 restore_original_signals ();
726f6388 2683
cce855bc 2684 if (async)
ccc6cda3 2685 {
cce855bc
JA
2686 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2687 pipe_in == NO_PIPE &&
2688 (stdin_redirects (simple_command->redirects) == 0))
2689 async_redirect_stdin ();
2690 setup_async_signals ();
ccc6cda3 2691 }
cce855bc
JA
2692
2693 execute_subshell_builtin_or_function
2694 (words, simple_command->redirects, builtin, func,
2695 pipe_in, pipe_out, async, fds_to_close,
2696 simple_command->flags);
726f6388
JA
2697 }
2698 else
2699 {
ccc6cda3
JA
2700 result = execute_builtin_or_function
2701 (words, builtin, func, simple_command->redirects, fds_to_close,
2702 simple_command->flags);
2703 if (builtin)
2704 {
2705 if (result > EX_SHERRBASE)
2706 {
cce855bc
JA
2707 result = builtin_status (result);
2708 if (builtin_is_special)
2709 special_builtin_failed = 1;
ccc6cda3
JA
2710 }
2711 /* In POSIX mode, if there are assignment statements preceding
2712 a special builtin, they persist after the builtin
2713 completes. */
2714 if (posixly_correct && builtin_is_special && temporary_env)
2715 merge_temporary_env ();
2716 }
2717 else /* function */
2718 {
2719 if (result == EX_USAGE)
2720 result = EX_BADUSAGE;
2721 else if (result > EX_SHERRBASE)
cce855bc 2722 result = EXECUTION_FAILURE;
ccc6cda3
JA
2723 }
2724
cce855bc
JA
2725 set_pipestatus_from_exit (result);
2726
726f6388
JA
2727 goto return_result;
2728 }
2729 }
726f6388 2730
cce855bc
JA
2731 if (command_line == 0)
2732 command_line = savestring (the_printed_command);
2733
ccc6cda3
JA
2734 execute_disk_command (words, simple_command->redirects, command_line,
2735 pipe_in, pipe_out, async, fds_to_close,
d166f048 2736 simple_command->flags);
726f6388
JA
2737
2738 return_result:
2739 bind_lastarg (lastarg);
ccc6cda3
JA
2740 FREE (command_line);
2741 run_unwind_frame ("simple-command");
726f6388
JA
2742 return (result);
2743}
2744
ccc6cda3
JA
2745/* Translate the special builtin exit statuses. We don't really need a
2746 function for this; it's a placeholder for future work. */
2747static int
2748builtin_status (result)
2749 int result;
2750{
2751 int r;
2752
2753 switch (result)
2754 {
2755 case EX_USAGE:
2756 r = EX_BADUSAGE;
2757 break;
2758 case EX_REDIRFAIL:
2759 case EX_BADSYNTAX:
2760 case EX_BADASSIGN:
2761 case EX_EXPFAIL:
2762 r = EXECUTION_FAILURE;
2763 break;
2764 default:
2765 r = EXECUTION_SUCCESS;
2766 break;
2767 }
2768 return (r);
2769}
2770
726f6388
JA
2771static int
2772execute_builtin (builtin, words, flags, subshell)
f73dda09 2773 sh_builtin_func_t *builtin;
726f6388
JA
2774 WORD_LIST *words;
2775 int flags, subshell;
2776{
d166f048 2777 int old_e_flag, result, eval_unwind;
7117c2d2 2778 int isbltinenv;
726f6388 2779
ccc6cda3 2780 old_e_flag = exit_immediately_on_error;
726f6388
JA
2781 /* The eval builtin calls parse_and_execute, which does not know about
2782 the setting of flags, and always calls the execution functions with
2783 flags that will exit the shell on an error if -e is set. If the
2784 eval builtin is being called, and we're supposed to ignore the exit
2785 value of the command, we turn the -e flag off ourselves, then
2786 restore it when the command completes. */
2787 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2788 {
2789 begin_unwind_frame ("eval_builtin");
2790 unwind_protect_int (exit_immediately_on_error);
2791 exit_immediately_on_error = 0;
d166f048 2792 eval_unwind = 1;
726f6388 2793 }
d166f048
JA
2794 else
2795 eval_unwind = 0;
726f6388
JA
2796
2797 /* The temporary environment for a builtin is supposed to apply to
2798 all commands executed by that builtin. Currently, this is a
d166f048 2799 problem only with the `source' and `eval' builtins. */
7117c2d2
JA
2800 isbltinenv = (builtin == source_builtin || builtin == eval_builtin);
2801 if (isbltinenv)
726f6388
JA
2802 {
2803 if (subshell == 0)
2804 begin_unwind_frame ("builtin_env");
2805
2806 if (temporary_env)
2807 {
7117c2d2 2808 push_scope (VC_BLTNENV, temporary_env);
726f6388 2809 if (subshell == 0)
7117c2d2
JA
2810 add_unwind_protect (pop_scope, "1");
2811 temporary_env = (HASH_TABLE *)NULL;
726f6388 2812 }
28ef6c31
JA
2813 }
2814
2815 /* `return' does a longjmp() back to a saved environment in execute_function.
2816 If a variable assignment list preceded the command, and the shell is
2817 running in POSIX mode, we need to merge that into the shell_variables
2818 table, since `return' is a POSIX special builtin. */
2819 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2820 {
2821 begin_unwind_frame ("return_temp_env");
2822 add_unwind_protect (merge_temporary_env, (char *)NULL);
726f6388
JA
2823 }
2824
2825 result = ((*builtin) (words->next));
2826
28ef6c31
JA
2827 /* This shouldn't happen, but in case `return' comes back instead of
2828 longjmp'ing, we need to unwind. */
2829 if (posixly_correct && subshell == 0 && builtin == return_builtin && temporary_env)
2830 discard_unwind_frame ("return_temp_env");
2831
7117c2d2
JA
2832 if (subshell == 0 && isbltinenv)
2833 run_unwind_frame ("builtin_env");
726f6388 2834
d166f048 2835 if (eval_unwind)
726f6388
JA
2836 {
2837 exit_immediately_on_error += old_e_flag;
2838 discard_unwind_frame ("eval_builtin");
2839 }
2840
2841 return (result);
2842}
2843
726f6388
JA
2844static int
2845execute_function (var, words, flags, fds_to_close, async, subshell)
2846 SHELL_VAR *var;
2847 WORD_LIST *words;
f73dda09 2848 int flags;
726f6388 2849 struct fd_bitmap *fds_to_close;
f73dda09 2850 int async, subshell;
726f6388
JA
2851{
2852 int return_val, result;
2853 COMMAND *tc, *fc;
f73dda09
JA
2854 char *debug_trap, *error_trap;
2855
2856 USE_VAR(fc);
726f6388
JA
2857
2858 tc = (COMMAND *)copy_command (function_cell (var));
2859 if (tc && (flags & CMD_IGNORE_RETURN))
2860 tc->flags |= CMD_IGNORE_RETURN;
2861
726f6388
JA
2862 if (subshell == 0)
2863 {
ccc6cda3 2864 begin_unwind_frame ("function_calling");
7117c2d2 2865 push_context (var->name, subshell, temporary_env);
726f6388
JA
2866 add_unwind_protect (pop_context, (char *)NULL);
2867 unwind_protect_int (line_number);
ccc6cda3
JA
2868 unwind_protect_int (return_catch_flag);
2869 unwind_protect_jmp_buf (return_catch);
2870 add_unwind_protect (dispose_command, (char *)tc);
bb70624e 2871 unwind_protect_pointer (this_shell_function);
ccc6cda3 2872 unwind_protect_int (loop_level);
726f6388 2873 }
7117c2d2
JA
2874 else
2875 push_context (var->name, subshell, temporary_env); /* don't unwind-protect for subshells */
2876
2877 temporary_env = (HASH_TABLE *)NULL;
726f6388 2878
bb70624e
JA
2879 this_shell_function = var;
2880 make_funcname_visible (1);
2881
f73dda09
JA
2882 debug_trap = TRAP_STRING(DEBUG_TRAP);
2883 error_trap = TRAP_STRING(ERROR_TRAP);
2884
2885 /* The order of the unwind protects for debug_trap and error_trap is
2886 important here! unwind-protect commands are run in reverse order
2887 of registration. If this causes problems, take out the xfree
2888 unwind-protect calls and live with the small memory leak. */
7117c2d2 2889 if (debug_trap && (trace_p (var) == 0))
ccc6cda3
JA
2890 {
2891 if (subshell == 0)
2892 {
2893 debug_trap = savestring (debug_trap);
cce855bc 2894 add_unwind_protect (xfree, debug_trap);
ccc6cda3
JA
2895 add_unwind_protect (set_debug_trap, debug_trap);
2896 }
2897 restore_default_signal (DEBUG_TRAP);
2898 }
726f6388 2899
f73dda09
JA
2900 if (error_trap)
2901 {
2902 if (subshell == 0)
2903 {
2904 error_trap = savestring (error_trap);
2905 add_unwind_protect (xfree, error_trap);
2906 add_unwind_protect (set_error_trap, error_trap);
2907 }
2908 restore_default_signal (ERROR_TRAP);
2909 }
2910
726f6388
JA
2911 /* The temporary environment for a function is supposed to apply to
2912 all commands executed within the function body. */
726f6388 2913
726f6388
JA
2914 remember_args (words->next, 1);
2915
ccc6cda3 2916 /* Number of the line on which the function body starts. */
7117c2d2
JA
2917 if (interactive_shell)
2918 line_number = function_line_number = tc->line;
726f6388
JA
2919
2920 if (subshell)
2921 {
2922#if defined (JOB_CONTROL)
2923 stop_pipeline (async, (COMMAND *)NULL);
2924#endif
ccc6cda3 2925 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
726f6388
JA
2926
2927 if (fc && (flags & CMD_IGNORE_RETURN))
2928 fc->flags |= CMD_IGNORE_RETURN;
726f6388
JA
2929 }
2930 else
2931 fc = tc;
2932
2933 return_catch_flag++;
2934 return_val = setjmp (return_catch);
2935
2936 if (return_val)
2937 result = return_catch_value;
2938 else
2939 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2940
ccc6cda3 2941 if (subshell == 0)
726f6388
JA
2942 run_unwind_frame ("function_calling");
2943
bb70624e
JA
2944 if (variable_context == 0 || this_shell_function == 0)
2945 make_funcname_visible (0);
2946
726f6388
JA
2947 return (result);
2948}
2949
bb70624e
JA
2950/* A convenience routine for use by other parts of the shell to execute
2951 a particular shell function. */
2952int
2953execute_shell_function (var, words)
2954 SHELL_VAR *var;
2955 WORD_LIST *words;
2956{
2957 int ret;
2958 struct fd_bitmap *bitmap;
2959
2960 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
2961 begin_unwind_frame ("execute-shell-function");
2962 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
2963
2964 ret = execute_function (var, words, 0, bitmap, 0, 0);
2965
2966 dispose_fd_bitmap (bitmap);
2967 discard_unwind_frame ("execute-shell-function");
2968
2969 return ret;
2970}
2971
726f6388
JA
2972/* Execute a shell builtin or function in a subshell environment. This
2973 routine does not return; it only calls exit(). If BUILTIN is non-null,
2974 it points to a function to call to execute a shell builtin; otherwise
2975 VAR points at the body of a function to execute. WORDS is the arguments
2976 to the command, REDIRECTS specifies redirections to perform before the
2977 command is executed. */
2978static void
2979execute_subshell_builtin_or_function (words, redirects, builtin, var,
2980 pipe_in, pipe_out, async, fds_to_close,
2981 flags)
2982 WORD_LIST *words;
2983 REDIRECT *redirects;
f73dda09 2984 sh_builtin_func_t *builtin;
726f6388
JA
2985 SHELL_VAR *var;
2986 int pipe_in, pipe_out, async;
2987 struct fd_bitmap *fds_to_close;
2988 int flags;
2989{
bb70624e
JA
2990 int result, r;
2991#if defined (JOB_CONTROL)
2992 int jobs_hack;
726f6388 2993
b72432fd
JA
2994 jobs_hack = (builtin == jobs_builtin) &&
2995 ((subshell_environment & SUBSHELL_ASYNC) == 0 || pipe_out != NO_PIPE);
bb70624e
JA
2996#endif
2997
2998 /* A subshell is neither a login shell nor interactive. */
2999 login_shell = interactive = 0;
b72432fd 3000
ccc6cda3 3001 subshell_environment = SUBSHELL_ASYNC;
726f6388 3002
ccc6cda3 3003 maybe_make_export_env (); /* XXX - is this needed? */
726f6388
JA
3004
3005#if defined (JOB_CONTROL)
3006 /* Eradicate all traces of job control after we fork the subshell, so
3007 all jobs begun by this subshell are in the same process group as
3008 the shell itself. */
3009
3010 /* Allow the output of `jobs' to be piped. */
b72432fd 3011 if (jobs_hack)
726f6388
JA
3012 kill_current_pipeline ();
3013 else
3014 without_job_control ();
3015
3016 set_sigchld_handler ();
3017#endif /* JOB_CONTROL */
3018
3019 set_sigint_handler ();
3020
726f6388
JA
3021 if (fds_to_close)
3022 close_fd_bitmap (fds_to_close);
3023
bb70624e
JA
3024 do_piping (pipe_in, pipe_out);
3025
726f6388
JA
3026 if (do_redirections (redirects, 1, 0, 0) != 0)
3027 exit (EXECUTION_FAILURE);
3028
3029 if (builtin)
3030 {
726f6388
JA
3031 /* Give builtins a place to jump back to on failure,
3032 so we don't go back up to main(). */
3033 result = setjmp (top_level);
3034
3035 if (result == EXITPROG)
3036 exit (last_command_exit_value);
3037 else if (result)
3038 exit (EXECUTION_FAILURE);
3039 else
cce855bc
JA
3040 {
3041 r = execute_builtin (builtin, words, flags, 1);
3042 if (r == EX_USAGE)
3043 r = EX_BADUSAGE;
3044 exit (r);
3045 }
726f6388
JA
3046 }
3047 else
ccc6cda3 3048 exit (execute_function (var, words, flags, fds_to_close, async, 1));
726f6388
JA
3049}
3050
3051/* Execute a builtin or function in the current shell context. If BUILTIN
3052 is non-null, it is the builtin command to execute, otherwise VAR points
3053 to the body of a function. WORDS are the command's arguments, REDIRECTS
3054 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
3055 file descriptors to close.
3056
3057 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
3058 not undone before this function returns. */
3059static int
3060execute_builtin_or_function (words, builtin, var, redirects,
3061 fds_to_close, flags)
3062 WORD_LIST *words;
f73dda09 3063 sh_builtin_func_t *builtin;
726f6388
JA
3064 SHELL_VAR *var;
3065 REDIRECT *redirects;
3066 struct fd_bitmap *fds_to_close;
3067 int flags;
3068{
ccc6cda3 3069 int result;
726f6388 3070 REDIRECT *saved_undo_list;
f73dda09 3071 sh_builtin_func_t *saved_this_shell_builtin;
726f6388
JA
3072
3073 if (do_redirections (redirects, 1, 1, 0) != 0)
3074 {
3075 cleanup_redirects (redirection_undo_list);
3076 redirection_undo_list = (REDIRECT *)NULL;
3077 dispose_exec_redirects ();
ccc6cda3 3078 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
726f6388
JA
3079 }
3080
28ef6c31 3081 saved_this_shell_builtin = this_shell_builtin;
726f6388
JA
3082 saved_undo_list = redirection_undo_list;
3083
3084 /* Calling the "exec" builtin changes redirections forever. */
3085 if (builtin == exec_builtin)
3086 {
3087 dispose_redirects (saved_undo_list);
3088 saved_undo_list = exec_redirection_undo_list;
3089 exec_redirection_undo_list = (REDIRECT *)NULL;
3090 }
3091 else
3092 dispose_exec_redirects ();
3093
3094 if (saved_undo_list)
3095 {
3096 begin_unwind_frame ("saved redirects");
ccc6cda3 3097 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
726f6388
JA
3098 }
3099
3100 redirection_undo_list = (REDIRECT *)NULL;
3101
3102 if (builtin)
3103 result = execute_builtin (builtin, words, flags, 0);
3104 else
3105 result = execute_function (var, words, flags, fds_to_close, 0, 0);
3106
28ef6c31
JA
3107 /* If we are executing the `command' builtin, but this_shell_builtin is
3108 set to `exec_builtin', we know that we have something like
3109 `command exec [redirection]', since otherwise `exec' would have
3110 overwritten the shell and we wouldn't get here. In this case, we
3111 want to behave as if the `command' builtin had not been specified
3112 and preserve the redirections. */
3113 if (builtin == command_builtin && this_shell_builtin == exec_builtin)
3114 {
3115 if (saved_undo_list)
3116 dispose_redirects (saved_undo_list);
3117 redirection_undo_list = exec_redirection_undo_list;
3118 saved_undo_list = exec_redirection_undo_list = (REDIRECT *)NULL;
3119 discard_unwind_frame ("saved_redirects");
3120 }
3121
726f6388
JA
3122 if (saved_undo_list)
3123 {
3124 redirection_undo_list = saved_undo_list;
3125 discard_unwind_frame ("saved redirects");
3126 }
3127
3128 if (redirection_undo_list)
3129 {
ccc6cda3 3130 cleanup_redirects (redirection_undo_list);
726f6388
JA
3131 redirection_undo_list = (REDIRECT *)NULL;
3132 }
3133
3134 return (result);
3135}
3136
3137void
3138setup_async_signals ()
3139{
b72432fd
JA
3140#if defined (__BEOS__)
3141 set_signal_handler (SIGHUP, SIG_IGN); /* they want csh-like behavior */
3142#endif
3143
726f6388
JA
3144#if defined (JOB_CONTROL)
3145 if (job_control == 0)
3146#endif
3147 {
3148 set_signal_handler (SIGINT, SIG_IGN);
3149 set_signal_ignored (SIGINT);
3150 set_signal_handler (SIGQUIT, SIG_IGN);
3151 set_signal_ignored (SIGQUIT);
3152 }
3153}
3154
3155/* Execute a simple command that is hopefully defined in a disk file
3156 somewhere.
3157
3158 1) fork ()
3159 2) connect pipes
3160 3) look up the command
3161 4) do redirections
3162 5) execve ()
3163 6) If the execve failed, see if the file has executable mode set.
3164 If so, and it isn't a directory, then execute its contents as
3165 a shell script.
3166
3167 Note that the filename hashing stuff has to take place up here,
3168 in the parent. This is probably why the Bourne style shells
3169 don't handle it, since that would require them to go through
3170 this gnarly hair, for no good reason. */
3171static void
3172execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
d166f048 3173 async, fds_to_close, cmdflags)
726f6388
JA
3174 WORD_LIST *words;
3175 REDIRECT *redirects;
3176 char *command_line;
3177 int pipe_in, pipe_out, async;
3178 struct fd_bitmap *fds_to_close;
d166f048 3179 int cmdflags;
726f6388 3180{
ccc6cda3 3181 char *pathname, *command, **args;
d166f048 3182 int nofork;
bb70624e 3183 pid_t pid;
726f6388 3184
d166f048 3185 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
726f6388 3186 pathname = words->word->word;
ccc6cda3 3187
726f6388 3188#if defined (RESTRICTED_SHELL)
7117c2d2 3189 if (restricted && xstrchr (pathname, '/'))
726f6388 3190 {
ccc6cda3 3191 internal_error ("%s: restricted: cannot specify `/' in command names",
726f6388
JA
3192 pathname);
3193 last_command_exit_value = EXECUTION_FAILURE;
3194 return;
3195 }
3196#endif /* RESTRICTED_SHELL */
3197
ccc6cda3 3198 command = search_for_command (pathname);
726f6388 3199
ccc6cda3 3200 if (command)
726f6388 3201 {
ccc6cda3
JA
3202 maybe_make_export_env ();
3203 put_command_name_into_env (command);
726f6388
JA
3204 }
3205
bb70624e 3206 /* We have to make the child before we check for the non-existence
726f6388
JA
3207 of COMMAND, since we want the error messages to be redirected. */
3208 /* If we can get away without forking and there are no pipes to deal with,
3209 don't bother to fork, just directly exec the command. */
3210 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
3211 pid = 0;
3212 else
3213 pid = make_child (savestring (command_line), async);
3214
3215 if (pid == 0)
3216 {
3217 int old_interactive;
3218
d166f048
JA
3219#if 0
3220 /* This has been disabled for the time being. */
ccc6cda3
JA
3221#if !defined (ARG_MAX) || ARG_MAX >= 10240
3222 if (posixly_correct == 0)
f73dda09 3223 put_gnu_argv_flags_into_env ((long)getpid (), glob_argv_flags);
d166f048 3224#endif
ccc6cda3
JA
3225#endif
3226
726f6388
JA
3227 /* Cancel traps, in trap.c. */
3228 restore_original_signals ();
3229
3230 /* restore_original_signals may have undone the work done
cce855bc
JA
3231 by make_child to ensure that SIGINT and SIGQUIT are ignored
3232 in asynchronous children. */
726f6388 3233 if (async)
d166f048
JA
3234 {
3235 if ((cmdflags & CMD_STDIN_REDIR) &&
3236 pipe_in == NO_PIPE &&
3237 (stdin_redirects (redirects) == 0))
3238 async_redirect_stdin ();
3239 setup_async_signals ();
3240 }
726f6388 3241
bb70624e
JA
3242 /* This functionality is now provided by close-on-exec of the
3243 file descriptors manipulated by redirection and piping.
3244 Some file descriptors still need to be closed in all children
3245 because of the way bash does pipes; fds_to_close is a
3246 bitmap of all such file descriptors. */
3247 if (fds_to_close)
3248 close_fd_bitmap (fds_to_close);
3249
726f6388
JA
3250 do_piping (pipe_in, pipe_out);
3251
f73dda09 3252 old_interactive = interactive;
726f6388 3253 if (async)
f73dda09 3254 interactive = 0;
726f6388 3255
ccc6cda3 3256 subshell_environment = SUBSHELL_FORK;
726f6388 3257
726f6388
JA
3258 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
3259 {
3260#if defined (PROCESS_SUBSTITUTION)
3261 /* Try to remove named pipes that may have been created as the
3262 result of redirections. */
3263 unlink_fifo_list ();
3264#endif /* PROCESS_SUBSTITUTION */
3265 exit (EXECUTION_FAILURE);
3266 }
3267
3268 if (async)
3269 interactive = old_interactive;
3270
ccc6cda3 3271 if (command == 0)
726f6388 3272 {
ccc6cda3 3273 internal_error ("%s: command not found", pathname);
726f6388
JA
3274 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
3275 }
3276
ccc6cda3
JA
3277 /* Execve expects the command name to be in args[0]. So we
3278 leave it there, in the same format that the user used to
3279 type it in. */
7117c2d2 3280 args = strvec_from_word_list (words, 0, 0, (int *)NULL);
726f6388
JA
3281 exit (shell_execve (command, args, export_env));
3282 }
3283 else
3284 {
3285 /* Make sure that the pipes are closed in the parent. */
3286 close_pipes (pipe_in, pipe_out);
3287#if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
3288 unlink_fifo_list ();
3289#endif
3290 FREE (command);
3291 }
3292}
3293
28ef6c31
JA
3294/* CPP defines to decide whether a particular index into the #! line
3295 corresponds to a valid interpreter name or argument character, or
3296 whitespace. The MSDOS define is to allow \r to be treated the same
3297 as \n. */
3298
3299#if !defined (MSDOS)
3300# define STRINGCHAR(ind) \
f73dda09 3301 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n')
28ef6c31 3302# define WHITECHAR(ind) \
f73dda09 3303 (ind < sample_len && whitespace (sample[ind]))
28ef6c31
JA
3304#else /* MSDOS */
3305# define STRINGCHAR(ind) \
f73dda09 3306 (ind < sample_len && !whitespace (sample[ind]) && sample[ind] != '\n' && sample[ind] != '\r')
28ef6c31 3307# define WHITECHAR(ind) \
f73dda09 3308 (ind < sample_len && whitespace (sample[ind]))
28ef6c31
JA
3309#endif /* MSDOS */
3310
f73dda09
JA
3311static char *
3312getinterp (sample, sample_len, endp)
3313 char *sample;
3314 int sample_len, *endp;
726f6388
JA
3315{
3316 register int i;
f73dda09
JA
3317 char *execname;
3318 int start;
726f6388
JA
3319
3320 /* Find the name of the interpreter to exec. */
f73dda09 3321 for (i = 2; i < sample_len && whitespace (sample[i]); i++)
726f6388
JA
3322 ;
3323
28ef6c31 3324 for (start = i; STRINGCHAR(i); i++)
726f6388
JA
3325 ;
3326
f73dda09
JA
3327 execname = substring (sample, start, i);
3328
3329 if (endp)
3330 *endp = i;
3331 return execname;
3332}
3333
3334#if !defined (HAVE_HASH_BANG_EXEC)
3335/* If the operating system on which we're running does not handle
3336 the #! executable format, then help out. SAMPLE is the text read
3337 from the file, SAMPLE_LEN characters. COMMAND is the name of
3338 the script; it and ARGS, the arguments given by the user, will
3339 become arguments to the specified interpreter. ENV is the environment
3340 to pass to the interpreter.
3341
3342 The word immediately following the #! is the interpreter to execute.
3343 A single argument to the interpreter is allowed. */
3344
3345static int
3346execute_shell_script (sample, sample_len, command, args, env)
3347 char *sample;
3348 int sample_len;
3349 char *command;
3350 char **args, **env;
3351{
3352 char *execname, *firstarg;
3353 int i, start, size_increment, larry;
3354
3355 /* Find the name of the interpreter to exec. */
3356 execname = getinterp (sample, sample_len, &i);
726f6388
JA
3357 size_increment = 1;
3358
3359 /* Now the argument, if any. */
28ef6c31 3360 for (firstarg = (char *)NULL, start = i; WHITECHAR(i); i++)
726f6388
JA
3361 ;
3362
3363 /* If there is more text on the line, then it is an argument for the
3364 interpreter. */
28ef6c31
JA
3365
3366 if (STRINGCHAR(i))
726f6388 3367 {
28ef6c31 3368 for (start = i; STRINGCHAR(i); i++)
726f6388 3369 ;
bb70624e 3370 firstarg = substring ((char *)sample, start, i);
726f6388
JA
3371 size_increment = 2;
3372 }
3373
7117c2d2
JA
3374 larry = strvec_len (args) + size_increment;
3375 args = strvec_resize (args, larry + 1);
726f6388
JA
3376
3377 for (i = larry - 1; i; i--)
3378 args[i] = args[i - size_increment];
3379
3380 args[0] = execname;
3381 if (firstarg)
3382 {
3383 args[1] = firstarg;
3384 args[2] = command;
3385 }
3386 else
3387 args[1] = command;
3388
3389 args[larry] = (char *)NULL;
3390
3391 return (shell_execve (execname, args, env));
3392}
28ef6c31
JA
3393#undef STRINGCHAR
3394#undef WHITECHAR
3395
ccc6cda3
JA
3396#endif /* !HAVE_HASH_BANG_EXEC */
3397
d166f048
JA
3398static void
3399initialize_subshell ()
3400{
3401#if defined (ALIAS)
3402 /* Forget about any aliases that we knew of. We are in a subshell. */
3403 delete_all_aliases ();
3404#endif /* ALIAS */
3405
3406#if defined (HISTORY)
3407 /* Forget about the history lines we have read. This is a non-interactive
3408 subshell. */
3409 history_lines_this_session = 0;
3410#endif
3411
3412#if defined (JOB_CONTROL)
3413 /* Forget about the way job control was working. We are in a subshell. */
3414 without_job_control ();
3415 set_sigchld_handler ();
3416#endif /* JOB_CONTROL */
3417
3418 /* Reset the values of the shell flags and options. */
3419 reset_shell_flags ();
3420 reset_shell_options ();
3421 reset_shopt_options ();
3422
28ef6c31
JA
3423 /* Zero out builtin_env, since this could be a shell script run from a
3424 sourced file with a temporary environment supplied to the `source/.'
3425 builtin. Such variables are not supposed to be exported (empirical
7117c2d2
JA
3426 testing with sh and ksh). Just throw it away; don't worry about a
3427 memory leak. */
3428 if (vc_isbltnenv (shell_variables))
3429 shell_variables = shell_variables->down;
28ef6c31
JA
3430
3431 clear_unwind_protect_list (0);
3432
3433 /* We're no longer inside a shell function. */
3434 variable_context = return_catch_flag = 0;
3435
d166f048
JA
3436 /* If we're not interactive, close the file descriptor from which we're
3437 reading the current shell script. */
cce855bc
JA
3438 if (interactive_shell == 0)
3439 unset_bash_input (1);
d166f048
JA
3440}
3441
ccc6cda3
JA
3442#if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3443# define SETOSTYPE(x) __setostype(x)
3444#else
3445# define SETOSTYPE(x)
3446#endif
726f6388 3447
28ef6c31
JA
3448#define READ_SAMPLE_BUF(file, buf, len) \
3449 do \
3450 { \
3451 fd = open(file, O_RDONLY); \
3452 if (fd >= 0) \
3453 { \
f73dda09 3454 len = read (fd, buf, 80); \
28ef6c31
JA
3455 close (fd); \
3456 } \
3457 else \
3458 len = -1; \
3459 } \
3460 while (0)
3461
726f6388
JA
3462/* Call execve (), handling interpreting shell scripts, and handling
3463 exec failures. */
3464int
3465shell_execve (command, args, env)
3466 char *command;
3467 char **args, **env;
3468{
ccc6cda3
JA
3469 struct stat finfo;
3470 int larray, i, fd;
f73dda09 3471 char sample[80];
28ef6c31 3472 int sample_len;
ccc6cda3
JA
3473
3474 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
726f6388 3475 execve (command, args, env);
28ef6c31 3476 i = errno; /* error from execve() */
ccc6cda3 3477 SETOSTYPE (1);
726f6388
JA
3478
3479 /* If we get to this point, then start checking out the file.
3480 Maybe it is something we can hack ourselves. */
28ef6c31 3481 if (i != ENOEXEC)
ccc6cda3 3482 {
ccc6cda3
JA
3483 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3484 internal_error ("%s: is a directory", command);
7117c2d2
JA
3485 else if (executable_file (command) == 0)
3486 {
3487 errno = i;
3488 file_error (command);
3489 }
ccc6cda3
JA
3490 else
3491 {
7117c2d2
JA
3492 /* The file has the execute bits set, but the kernel refuses to
3493 run it for some reason. See why. */
28ef6c31
JA
3494#if defined (HAVE_HASH_BANG_EXEC)
3495 READ_SAMPLE_BUF (command, sample, sample_len);
3496 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3497 {
f73dda09
JA
3498 char *interp;
3499
3500 interp = getinterp (sample, sample_len, (int *)NULL);
28ef6c31 3501 errno = i;
f73dda09
JA
3502 sys_error ("%s: %s: bad interpreter", command, interp ? interp : "");
3503 FREE (interp);
28ef6c31
JA
3504 return (EX_NOEXEC);
3505 }
3506#endif
ccc6cda3 3507 errno = i;
726f6388 3508 file_error (command);
ccc6cda3 3509 }
d166f048 3510 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
ccc6cda3 3511 }
726f6388 3512
ccc6cda3
JA
3513 /* This file is executable.
3514 If it begins with #!, then help out people with losing operating
3515 systems. Otherwise, check to see if it is a binary file by seeing
28ef6c31
JA
3516 if the contents of the first line (or up to 80 characters) are in the
3517 ASCII set. If it's a text file, execute the contents as shell commands,
3518 otherwise return 126 (EX_BINARY_FILE). */
3519 READ_SAMPLE_BUF (command, sample, sample_len);
ccc6cda3 3520
28ef6c31
JA
3521 if (sample_len == 0)
3522 return (EXECUTION_SUCCESS);
ccc6cda3 3523
28ef6c31
JA
3524 /* Is this supposed to be an executable script?
3525 If so, the format of the line is "#! interpreter [argument]".
3526 A single argument is allowed. The BSD kernel restricts
3527 the length of the entire line to 32 characters (32 bytes
3528 being the size of the BSD exec header), but we allow 80
3529 characters. */
3530 if (sample_len > 0)
3531 {
ccc6cda3 3532#if !defined (HAVE_HASH_BANG_EXEC)
28ef6c31
JA
3533 if (sample_len > 2 && sample[0] == '#' && sample[1] == '!')
3534 return (execute_shell_script (sample, sample_len, command, args, env));
3535 else
ccc6cda3 3536#endif
28ef6c31
JA
3537 if (check_binary_file (sample, sample_len))
3538 {
3539 internal_error ("%s: cannot execute binary file", command);
3540 return (EX_BINARY_FILE);
726f6388 3541 }
ccc6cda3
JA
3542 }
3543
28ef6c31
JA
3544 /* We have committed to attempting to execute the contents of this file
3545 as shell commands. */
3546
d166f048 3547 initialize_subshell ();
726f6388 3548
ccc6cda3 3549 set_sigint_handler ();
726f6388 3550
ccc6cda3 3551 /* Insert the name of this shell into the argument list. */
7117c2d2
JA
3552 larray = strvec_len (args) + 1;
3553 args = strvec_resize (args, larray + 1);
726f6388 3554
ccc6cda3
JA
3555 for (i = larray - 1; i; i--)
3556 args[i] = args[i - 1];
726f6388 3557
ccc6cda3
JA
3558 args[0] = shell_name;
3559 args[1] = command;
3560 args[larray] = (char *)NULL;
726f6388 3561
ccc6cda3
JA
3562 if (args[0][0] == '-')
3563 args[0]++;
726f6388 3564
ccc6cda3
JA
3565#if defined (RESTRICTED_SHELL)
3566 if (restricted)
3567 change_flag ('r', FLAG_OFF);
3568#endif
726f6388 3569
ccc6cda3
JA
3570 if (subshell_argv)
3571 {
3572 /* Can't free subshell_argv[0]; that is shell_name. */
3573 for (i = 1; i < subshell_argc; i++)
3574 free (subshell_argv[i]);
3575 free (subshell_argv);
3576 }
3577
3578 dispose_command (currently_executing_command); /* XXX */
3579 currently_executing_command = (COMMAND *)NULL;
3580
3581 subshell_argc = larray;
3582 subshell_argv = args;
3583 subshell_envp = env;
3584
3585 unbind_args (); /* remove the positional parameters */
3586
3587 longjmp (subshell_top_level, 1);
f73dda09 3588 /*NOTREACHED*/
ccc6cda3
JA
3589}
3590
3591static int
3592execute_intern_function (name, function)
3593 WORD_DESC *name;
3594 COMMAND *function;
3595{
3596 SHELL_VAR *var;
3597
3598 if (check_identifier (name, posixly_correct) == 0)
3599 {
3600 if (posixly_correct && interactive_shell == 0)
3601 {
3602 last_command_exit_value = EX_USAGE;
3603 jump_to_top_level (EXITPROG);
3604 }
3605 return (EXECUTION_FAILURE);
3606 }
3607
3608 var = find_function (name->word);
28ef6c31 3609 if (var && (readonly_p (var) || noassign_p (var)))
ccc6cda3 3610 {
28ef6c31
JA
3611 if (readonly_p (var))
3612 internal_error ("%s: readonly function", var->name);
ccc6cda3
JA
3613 return (EXECUTION_FAILURE);
3614 }
3615
3616 bind_function (name->word, function);
3617 return (EXECUTION_SUCCESS);
726f6388
JA
3618}
3619
d166f048 3620#if defined (INCLUDE_UNUSED)
726f6388 3621#if defined (PROCESS_SUBSTITUTION)
726f6388
JA
3622void
3623close_all_files ()
3624{
3625 register int i, fd_table_size;
3626
3627 fd_table_size = getdtablesize ();
3628 if (fd_table_size > 256) /* clamp to a reasonable value */
7117c2d2 3629 fd_table_size = 256;
726f6388
JA
3630
3631 for (i = 3; i < fd_table_size; i++)
3632 close (i);
3633}
3634#endif /* PROCESS_SUBSTITUTION */
d166f048 3635#endif
726f6388
JA
3636
3637static void
3638close_pipes (in, out)
3639 int in, out;
3640{
3641 if (in >= 0)
3642 close (in);
3643 if (out >= 0)
3644 close (out);
3645}
3646
3647/* Redirect input and output to be from and to the specified pipes.
3648 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3649static void
3650do_piping (pipe_in, pipe_out)
3651 int pipe_in, pipe_out;
3652{
3653 if (pipe_in != NO_PIPE)
3654 {
3655 if (dup2 (pipe_in, 0) < 0)
ccc6cda3 3656 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
726f6388 3657 if (pipe_in > 0)
cce855bc 3658 close (pipe_in);
726f6388
JA
3659 }
3660 if (pipe_out != NO_PIPE)
3661 {
3662 if (pipe_out != REDIRECT_BOTH)
3663 {
3664 if (dup2 (pipe_out, 1) < 0)
ccc6cda3 3665 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
726f6388
JA
3666 if (pipe_out == 0 || pipe_out > 1)
3667 close (pipe_out);
3668 }
3669 else
ccc6cda3 3670 {
cce855bc
JA
3671 if (dup2 (1, 2) < 0)
3672 sys_error ("cannot duplicate fd 1 to fd 2");
ccc6cda3 3673 }
d166f048 3674 }
726f6388 3675}