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