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