1 /* execute_command.c -- Execute a COMMAND structure. */
3 /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
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)
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.
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 #if defined (AIX) && defined (RISC6000) && !defined (__GNUC__)
22 #endif /* AIX && RISC6000 && !__GNUC__ */
26 #include "bashtypes.h"
29 #include "posixstat.h"
32 #if !defined (SIGABRT)
33 #define SIGABRT SIGIOT
36 #include <sys/param.h>
43 #if defined (HAVE_STRING_H)
45 #else /* !HAVE_STRING_H */
47 #endif /* !HAVE_STRING_H */
54 #include "execute_cmd.h"
57 #include "builtins/common.h"
58 #include "builtins/builtext.h" /* list of builtins */
60 #include <glob/fnmatch.h>
61 #include <tilde/tilde.h>
63 #if defined (BUFFERED_INPUT)
67 extern int posixly_correct;
68 extern int breaking, continuing, loop_level;
69 extern int interactive, interactive_shell, login_shell;
70 extern int parse_and_execute_level;
71 extern int command_string_index, variable_context, line_number;
72 extern int dot_found_in_search;
73 extern char **temporary_env, **function_env, **builtin_env;
74 extern char *the_printed_command, *shell_name;
75 extern pid_t last_command_subst_pid;
76 extern Function *last_shell_builtin, *this_shell_builtin;
77 extern jmp_buf top_level, subshell_top_level;
78 extern int subshell_argc;
79 extern char **subshell_argv, **subshell_envp;
80 extern int already_making_children;
82 extern int getdtablesize ();
85 /* Static functions defined and used in this file. */
86 static void close_pipes (), do_piping (), execute_disk_command ();
87 static void execute_subshell_builtin_or_function ();
88 static void cleanup_redirects (), cleanup_func_redirects (), bind_lastarg ();
89 static void add_undo_close_redirect (), add_exec_redirect ();
90 static int do_redirection_internal (), do_redirections ();
91 static int expandable_redirection_filename (), execute_shell_script ();
92 static int execute_builtin_or_function (), add_undo_redirect ();
93 static char *find_user_command_internal (), *find_user_command_in_path ();
95 /* The line number that the currently executing function starts on. */
96 static int function_line_number = 0;
98 /* Set to 1 if fd 0 was the subject of redirection to a subshell. */
99 static int stdin_redir = 0;
101 /* The name of the command that is currently being executed.
102 `test' needs this, for example. */
103 char *this_command_name;
105 struct stat SB; /* used for debugging */
107 static REDIRECTEE rd;
109 /* For catching RETURN in a function. */
110 int return_catch_flag = 0;
111 int return_catch_value;
112 jmp_buf return_catch;
114 /* The value returned by the last synchronous command. */
115 int last_command_exit_value = 0;
117 /* The list of redirections to perform which will undo the redirections
118 that I made in the shell. */
119 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
121 /* The list of redirections to perform which will undo the internal
122 redirections performed by the `exec' builtin. These are redirections
123 that must be undone even when exec discards redirection_undo_list. */
124 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
126 /* Non-zero if we have just forked and are currently running in a subshell
128 int subshell_environment = 0;
130 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
132 #define FD_BITMAP_DEFAULT_SIZE 32
133 /* Functions to allocate and deallocate the structures used to pass
134 information from the shell to its children about file descriptors
140 struct fd_bitmap *ret;
142 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
148 ret->bitmap = xmalloc (size);
149 bzero (ret->bitmap, size);
152 ret->bitmap = (char *)NULL;
157 dispose_fd_bitmap (fdbp)
158 struct fd_bitmap *fdbp;
165 close_fd_bitmap (fdbp)
166 struct fd_bitmap *fdbp;
172 for (i = 0; i < fdbp->size; i++)
181 /* Execute the command passed in COMMAND. COMMAND is exactly what
182 read_command () places into GLOBAL_COMMAND. See "command.h" for the
183 details of the command structure.
185 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
186 return values. Executing a command with nothing in it returns
187 EXECUTION_SUCCESS. */
188 execute_command (command)
191 struct fd_bitmap *bitmap;
194 current_fds_to_close = (struct fd_bitmap *)NULL;
195 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
196 begin_unwind_frame ("execute-command");
197 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
199 /* Just do the command, but not asynchronously. */
200 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
202 dispose_fd_bitmap (bitmap);
203 discard_unwind_frame ("execute-command");
205 #if defined (PROCESS_SUBSTITUTION)
207 #endif /* PROCESS_SUBSTITUTION */
212 /* Return 1 if TYPE is a shell control structure type. */
214 shell_control_structure (type)
215 enum command_type type;
220 #if defined (SELECT_COMMAND)
235 /* A function to use to unwind_protect the redirection undo list
238 cleanup_redirects (list)
241 do_redirections (list, 1, 0, 0);
242 dispose_redirects (list);
245 /* Function to unwind_protect the redirections for functions and builtins. */
247 cleanup_func_redirects (list)
250 do_redirections (list, 1, 0, 0);
254 dispose_exec_redirects ()
256 if (exec_redirection_undo_list)
258 dispose_redirects (exec_redirection_undo_list);
259 exec_redirection_undo_list = (REDIRECT *)NULL;
263 #if defined (JOB_CONTROL)
264 /* A function to restore the signal mask to its proper value when the shell
265 is interrupted or errors occur while creating a pipeline. */
267 restore_signal_mask (set)
270 return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
272 #endif /* JOB_CONTROL */
274 /* A debugging function that can be called from gdb, for instance. */
279 int f, fd_table_size;
281 fd_table_size = getdtablesize ();
283 fprintf (stderr, "pid %d open files:", getpid ());
284 for (i = 3; i < fd_table_size; i++)
286 if ((f = fcntl (i, F_GETFD, 0)) != -1)
287 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
289 fprintf (stderr, "\n");
292 #define DESCRIBE_PID(pid) if (interactive) describe_pid (pid)
294 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
295 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
296 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
297 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
298 from and where it goes. They can have the value of NO_PIPE, which means
300 FDS_TO_CLOSE is a list of file descriptors to close once the child has
301 been forked. This list often contains the unusable sides of pipes, etc.
303 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
304 return values. Executing a command with nothing in it returns
305 EXECUTION_SUCCESS. */
306 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
310 int pipe_in, pipe_out;
311 struct fd_bitmap *fds_to_close;
313 int exec_result = EXECUTION_SUCCESS;
314 int invert, ignore_return;
315 REDIRECT *my_undo_list, *exec_undo_list;
317 if (!command || breaking || continuing)
318 return (EXECUTION_SUCCESS);
320 run_pending_traps ();
322 invert = (command->flags & CMD_INVERT_RETURN) != 0;
324 /* If a command was being explicitly run in a subshell, or if it is
325 a shell control-structure, and it has a pipe, then we do the command
328 if ((command->flags & CMD_WANT_SUBSHELL) ||
329 (command->flags & CMD_FORCE_SUBSHELL) ||
330 (shell_control_structure (command->type) &&
331 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
335 /* Fork a subshell, turn off the subshell bit, turn off job
336 control and call execute_command () on the command again. */
337 paren_pid = make_child (savestring (make_command_string (command)),
341 int user_subshell, return_code, function_value;
343 /* Cancel traps, in trap.c. */
344 restore_original_signals ();
346 setup_async_signals ();
348 #if defined (JOB_CONTROL)
349 set_sigchld_handler ();
350 #endif /* JOB_CONTROL */
352 set_sigint_handler ();
354 user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
355 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
357 /* If a command is asynchronous in a subshell (like ( foo ) & or
358 the special case of an asynchronous GROUP command where the
359 the subshell bit is turned on down in case cm_group: below),
360 turn off `asynchronous', so that two subshells aren't spawned.
362 This seems semantically correct to me. For example,
363 ( foo ) & seems to say ``do the command `foo' in a subshell
364 environment, but don't wait for that subshell to finish'',
365 and "{ foo ; bar } &" seems to me to be like functions or
366 builtins in the background, which executed in a subshell
367 environment. I just don't see the need to fork two subshells. */
369 /* Don't fork again, we are already in a subshell. A `doubly
370 async' shell is not interactive, however. */
373 #if defined (JOB_CONTROL)
374 /* If a construct like ( exec xxx yyy ) & is given while job
375 control is active, we want to prevent exec from putting the
376 subshell back into the original process group, carefully
377 undoing all the work we just did in make_child. */
379 #endif /* JOB_CONTROL */
380 interactive_shell = 0;
384 /* Subshells are neither login nor interactive. */
385 login_shell = interactive = 0;
387 subshell_environment = 1;
389 #if defined (JOB_CONTROL)
390 /* Delete all traces that there were any jobs running. This is
391 only for subshells. */
392 without_job_control ();
393 #endif /* JOB_CONTROL */
394 do_piping (pipe_in, pipe_out);
396 /* If this is a user subshell, set a flag if stdin was redirected.
397 This is used later to decide whether to redirect fd 0 to
398 /dev/null for async commands in the subshell. This adds more
399 sh compatibility, but I'm not sure it's the right thing to do. */
404 for (r = command->redirects; r; r = r->next)
405 switch (r->instruction)
407 case r_input_direction:
408 case r_inputa_direction:
410 case r_reading_until:
411 case r_deblank_reading_until:
414 case r_duplicating_input:
415 case r_duplicating_input_word:
417 if (r->redirector == 0)
424 close_fd_bitmap (fds_to_close);
426 /* Do redirections, then dispose of them before recursive call. */
427 if (command->redirects)
429 if (do_redirections (command->redirects, 1, 0, 0) != 0)
430 exit (EXECUTION_FAILURE);
432 dispose_redirects (command->redirects);
433 command->redirects = (REDIRECT *)NULL;
436 /* If this is a simple command, tell execute_disk_command that it
437 might be able to get away without forking and simply exec.
438 This means things like ( sleep 10 ) will only cause one fork. */
439 if (user_subshell && command->type == cm_simple)
441 command->flags |= CMD_NO_FORK;
442 command->value.Simple->flags |= CMD_NO_FORK;
445 /* If we're inside a function while executing this subshell, we
446 need to handle a possible `return'. */
448 if (return_catch_flag)
449 function_value = setjmp (return_catch);
452 return_code = return_catch_value;
454 return_code = execute_command_internal
455 (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
457 /* If we were explicitly placed in a subshell with (), we need
458 to do the `shell cleanup' things, such as running traps[0]. */
459 if (user_subshell && signal_is_trapped (0))
461 last_command_exit_value = return_code;
462 return_code = run_exit_trap ();
469 close_pipes (pipe_in, pipe_out);
471 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
474 /* If we are part of a pipeline, and not the end of the pipeline,
475 then we should simply return and let the last command in the
476 pipe be waited for. If we are not in a pipeline, or are the
477 last command in the pipeline, then we wait for the subshell
478 and return its exit status as usual. */
479 if (pipe_out != NO_PIPE)
480 return (EXECUTION_SUCCESS);
482 stop_pipeline (asynchronous, (COMMAND *)NULL);
486 last_command_exit_value = wait_for (paren_pid);
488 /* If we have to, invert the return value. */
491 if (last_command_exit_value == EXECUTION_SUCCESS)
492 return (EXECUTION_FAILURE);
494 return (EXECUTION_SUCCESS);
497 return (last_command_exit_value);
501 DESCRIBE_PID (paren_pid);
503 run_pending_traps ();
505 return (EXECUTION_SUCCESS);
510 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
512 if (do_redirections (command->redirects, 1, 1, 0) != 0)
514 cleanup_redirects (redirection_undo_list);
515 redirection_undo_list = (REDIRECT *)NULL;
516 dispose_exec_redirects ();
517 return (EXECUTION_FAILURE);
520 if (redirection_undo_list)
522 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
523 dispose_redirects (redirection_undo_list);
524 redirection_undo_list = (REDIRECT *)NULL;
527 my_undo_list = (REDIRECT *)NULL;
529 if (exec_redirection_undo_list)
531 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
532 dispose_redirects (exec_redirection_undo_list);
533 exec_redirection_undo_list = (REDIRECT *)NULL;
536 exec_undo_list = (REDIRECT *)NULL;
538 if (my_undo_list || exec_undo_list)
539 begin_unwind_frame ("loop_redirections");
542 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
545 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
547 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
551 switch (command->type)
555 command->value.For->flags |= CMD_IGNORE_RETURN;
556 exec_result = execute_for_command (command->value.For);
559 #if defined (SELECT_COMMAND)
562 command->value.Select->flags |= CMD_IGNORE_RETURN;
563 exec_result = execute_select_command (command->value.Select);
569 command->value.Case->flags |= CMD_IGNORE_RETURN;
570 exec_result = execute_case_command (command->value.Case);
575 command->value.While->flags |= CMD_IGNORE_RETURN;
576 exec_result = execute_while_command (command->value.While);
581 command->value.While->flags |= CMD_IGNORE_RETURN;
582 exec_result = execute_until_command (command->value.While);
587 command->value.If->flags |= CMD_IGNORE_RETURN;
588 exec_result = execute_if_command (command->value.If);
593 /* This code can be executed from either of two paths: an explicit
594 '{}' command, or via a function call. If we are executed via a
595 function call, we have already taken care of the function being
596 executed in the background (down there in execute_simple_command ()),
597 and this command should *not* be marked as asynchronous. If we
598 are executing a regular '{}' group command, and asynchronous == 1,
599 we must want to execute the whole command in the background, so we
600 need a subshell, and we want the stuff executed in that subshell
601 (this group command) to be executed in the foreground of that
602 subshell (i.e. there will not be *another* subshell forked).
604 What we do is to force a subshell if asynchronous, and then call
605 execute_command_internal again with asynchronous still set to 1,
606 but with the original group command, so the printed command will
609 The code above that handles forking off subshells will note that
610 both subshell and async are on, and turn off async in the child
611 after forking the subshell (but leave async set in the parent, so
612 the normal call to describe_pid is made). This turning off
613 async is *crucial*; if it is not done, this will fall into an
614 infinite loop of executions through this spot in subshell after
615 subshell until the process limit is exhausted. */
619 command->flags |= CMD_FORCE_SUBSHELL;
621 execute_command_internal (command, 1, pipe_in, pipe_out,
626 if (ignore_return && command->value.Group->command)
627 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
629 execute_command_internal (command->value.Group->command,
630 asynchronous, pipe_in, pipe_out,
637 /* We can't rely on this variable retaining its value across a
638 call to execute_simple_command if a longjmp occurs as the
639 result of a `return' builtin. This is true for sure with gcc. */
640 pid_t last_pid = last_made_pid;
642 if (ignore_return && command->value.Simple)
643 command->value.Simple->flags |= CMD_IGNORE_RETURN;
645 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
646 asynchronous, fds_to_close);
648 /* The temporary environment should be used for only the simple
649 command immediately following its definition. */
650 dispose_used_env_vars ();
652 #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
653 /* Reclaim memory allocated with alloca () on machines which
654 may be using the alloca emulation code. */
656 #endif /* (Ultrix && mips) || !HAVE_ALLOCA */
658 /* If we forked to do the command, then we must wait_for ()
661 /* XXX - this is something to watch out for if there are problems
662 when the shell is compiled without job control. */
663 if (already_making_children && pipe_out == NO_PIPE &&
664 last_pid != last_made_pid)
666 stop_pipeline (asynchronous, (COMMAND *)NULL);
670 DESCRIBE_PID (last_made_pid);
673 #if !defined (JOB_CONTROL)
674 /* Do not wait for asynchronous processes started from
676 if (last_made_pid != last_asynchronous_pid)
678 /* When executing a shell function that executes other
679 commands, this causes the last simple command in
680 the function to be waited for twice. */
681 exec_result = wait_for (last_made_pid);
685 if (!ignore_return && exit_immediately_on_error && !invert &&
686 (exec_result != EXECUTION_SUCCESS))
688 last_command_exit_value = exec_result;
689 run_pending_traps ();
690 longjmp (top_level, EXITPROG);
696 switch (command->value.Connection->connector)
698 /* Do the first command asynchronously. */
701 COMMAND *tc = command->value.Connection->first;
709 if (ignore_return && tc)
710 tc->flags |= CMD_IGNORE_RETURN;
712 /* If this shell was compiled without job control support, if
713 the shell is not running interactively, if we are currently
714 in a subshell via `( xxx )', or if job control is not active
715 then the standard input for an asynchronous command is
716 forced to /dev/null. */
717 #if defined (JOB_CONTROL)
718 if ((!interactive_shell || subshell_environment || !job_control) &&
722 #endif /* JOB_CONTROL */
726 rd.filename = make_word ("/dev/null");
727 tr = make_redirection (0, r_inputa_direction, rd);
728 tr->next = tc->redirects;
732 exec_result = execute_command_internal
733 (tc, 1, pipe_in, pipe_out, fds_to_close);
735 #if defined (JOB_CONTROL)
736 if ((!interactive_shell || subshell_environment || !job_control) &&
740 #endif /* JOB_CONTROL */
742 /* Remove the redirection we added above. It matters,
743 especially for loops, which call execute_command ()
744 multiple times with the same command. */
751 tc->redirects = tc->redirects->next;
753 while (tc->redirects && tc->redirects != rp);
755 tl->next = (REDIRECT *)NULL;
756 dispose_redirects (tr);
760 register COMMAND *second;
762 second = command->value.Connection->second;
767 second->flags |= CMD_IGNORE_RETURN;
769 exec_result = execute_command_internal
770 (second, asynchronous, pipe_in, pipe_out, fds_to_close);
777 /* Just call execute command on both of them. */
780 if (command->value.Connection->first)
781 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
782 if (command->value.Connection->second)
783 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
786 execute_command (command->value.Connection->first);
789 execute_command_internal (command->value.Connection->second,
790 asynchronous, pipe_in, pipe_out,
796 int prev, fildes[2], new_bitmap_size, dummyfd;
798 struct fd_bitmap *fd_bitmap;
800 #if defined (JOB_CONTROL)
802 BLOCK_CHILD (set, oset);
803 #endif /* JOB_CONTROL */
809 cmd->type == cm_connection &&
810 cmd->value.Connection &&
811 cmd->value.Connection->connector == '|')
813 /* Make a pipeline between the two commands. */
814 if (pipe (fildes) < 0)
816 report_error ("pipe error: %s", strerror (errno));
817 #if defined (JOB_CONTROL)
818 terminate_current_pipeline ();
819 kill_current_pipeline ();
820 #endif /* JOB_CONTROL */
821 last_command_exit_value = EXECUTION_FAILURE;
822 /* The unwind-protects installed below will take care
823 of closing all of the open file descriptors. */
824 throw_to_top_level ();
828 /* Here is a problem: with the new file close-on-exec
829 code, the read end of the pipe (fildes[0]) stays open
830 in the first process, so that process will never get a
831 SIGPIPE. There is no way to signal the first process
832 that it should close fildes[0] after forking, so it
833 remains open. No SIGPIPE is ever sent because there
834 is still a file descriptor open for reading connected
835 to the pipe. We take care of that here. This passes
836 around a bitmap of file descriptors that must be
837 closed after making a child process in
838 execute_simple_command. */
840 /* We need fd_bitmap to be at least as big as fildes[0].
841 If fildes[0] is less than fds_to_close->size, then
842 use fds_to_close->size. */
843 if (fildes[0] < fds_to_close->size)
844 new_bitmap_size = fds_to_close->size;
846 new_bitmap_size = fildes[0] + 8;
848 fd_bitmap = new_fd_bitmap (new_bitmap_size);
850 /* Now copy the old information into the new bitmap. */
851 xbcopy ((char *)fds_to_close->bitmap,
852 (char *)fd_bitmap->bitmap, fds_to_close->size);
854 /* And mark the pipe file descriptors to be closed. */
855 fd_bitmap->bitmap[fildes[0]] = 1;
857 /* In case there are pipe or out-of-processes errors, we
858 want all these file descriptors to be closed when
859 unwind-protects are run, and the storage used for the
861 begin_unwind_frame ("pipe-file-descriptors");
862 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
863 add_unwind_protect (close_fd_bitmap, fd_bitmap);
865 add_unwind_protect (close, prev);
867 add_unwind_protect (close, dummyfd);
869 #if defined (JOB_CONTROL)
870 add_unwind_protect (restore_signal_mask, oset);
871 #endif /* JOB_CONTROL */
873 if (ignore_return && cmd->value.Connection->first)
874 cmd->value.Connection->first->flags |=
876 execute_command_internal
877 (cmd->value.Connection->first, asynchronous, prev,
878 fildes[1], fd_bitmap);
886 dispose_fd_bitmap (fd_bitmap);
887 discard_unwind_frame ("pipe-file-descriptors");
889 cmd = cmd->value.Connection->second;
892 /* Now execute the rightmost command in the pipeline. */
893 if (ignore_return && cmd)
894 cmd->flags |= CMD_IGNORE_RETURN;
896 execute_command_internal
897 (cmd, asynchronous, prev, pipe_out, fds_to_close);
902 #if defined (JOB_CONTROL)
903 UNBLOCK_CHILD (oset);
912 /* If we have something like `a && b &' or `a || b &', run the
913 && or || stuff in a subshell. Force a subshell and just call
914 execute_command_internal again. Leave asynchronous on
915 so that we get a report from the parent shell about the
917 command->flags |= CMD_FORCE_SUBSHELL;
918 exec_result = execute_command_internal (command, 1, pipe_in,
919 pipe_out, fds_to_close);
923 /* Execute the first command. If the result of that is successful
924 and the connector is AND_AND, or the result is not successful
925 and the connector is OR_OR, then execute the second command,
928 if (command->value.Connection->first)
929 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
931 exec_result = execute_command (command->value.Connection->first);
933 if (((command->value.Connection->connector == AND_AND) &&
934 (exec_result == EXECUTION_SUCCESS)) ||
935 ((command->value.Connection->connector == OR_OR) &&
936 (exec_result != EXECUTION_SUCCESS)))
938 if (ignore_return && command->value.Connection->second)
939 command->value.Connection->second->flags |=
943 execute_command (command->value.Connection->second);
948 programming_error ("Bad connector `%d'!",
949 command->value.Connection->connector);
950 longjmp (top_level, DISCARD);
955 case cm_function_def:
956 exec_result = intern_function (command->value.Function_def->name,
957 command->value.Function_def->command);
962 ("execute_command: Bad command type `%d'!", command->type);
967 do_redirections (my_undo_list, 1, 0, 0);
968 dispose_redirects (my_undo_list);
972 dispose_redirects (exec_undo_list);
974 if (my_undo_list || exec_undo_list)
975 discard_unwind_frame ("loop_redirections");
977 /* Invert the return value if we have to */
980 if (exec_result == EXECUTION_SUCCESS)
981 exec_result = EXECUTION_FAILURE;
983 exec_result = EXECUTION_SUCCESS;
986 last_command_exit_value = exec_result;
987 run_pending_traps ();
988 return (last_command_exit_value);
991 #if defined (JOB_CONTROL)
995 if (!interactive_shell) \
999 #else /* !JOB_CONTROL */
1003 if (!interactive_shell) \
1004 cleanup_dead_jobs (); \
1007 #endif /* !JOB_CONTROL */
1010 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1012 execute_for_command (for_command)
1013 FOR_COM *for_command;
1015 /* I just noticed that the Bourne shell leaves word_desc bound to the
1016 last name in word_list after the FOR statement is done. This seems
1017 wrong to me; I thought that the variable binding should be lexically
1018 scoped, i.e., only would last the duration of the FOR command. This
1019 behaviour can be gotten by turning on the lexical_scoping switch. */
1021 register WORD_LIST *releaser, *list;
1023 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1024 int retval = EXECUTION_SUCCESS;
1026 if (check_identifier (for_command->name, 1) == 0)
1027 return (EXECUTION_FAILURE);
1030 identifier = for_command->name->word;
1032 list = releaser = expand_words_no_vars (for_command->map_list);
1034 begin_unwind_frame ("for");
1035 add_unwind_protect (dispose_words, releaser);
1037 if (lexical_scoping)
1039 old_value = copy_variable (find_variable (identifier));
1041 add_unwind_protect (dispose_variable, old_value);
1044 if (for_command->flags & CMD_IGNORE_RETURN)
1045 for_command->action->flags |= CMD_IGNORE_RETURN;
1050 bind_variable (identifier, list->word->word);
1051 execute_command (for_command->action);
1052 retval = last_command_exit_value;
1074 if (lexical_scoping)
1077 makunbound (identifier, shell_variables);
1080 SHELL_VAR *new_value;
1082 new_value = bind_variable (identifier, value_cell(old_value));
1083 new_value->attributes = old_value->attributes;
1084 dispose_variable (old_value);
1088 dispose_words (releaser);
1089 discard_unwind_frame ("for");
1093 #if defined (SELECT_COMMAND)
1094 static int LINES, COLS, tabsize;
1096 #define RP_SPACE ") "
1097 #define RP_SPACE_LEN 2
1099 /* XXX - does not handle numbers > 1000000 at all. */
1100 #define NUMBER_LEN(s) \
1104 : ((s < 10000) ? 4 \
1105 : ((s < 100000) ? 5 \
1109 print_index_and_element (len, ind, list)
1113 register WORD_LIST *l;
1122 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1123 return (STRLEN (l->word->word));
1132 if ((to / tabsize) > (from / tabsize))
1134 putc ('\t', stderr);
1135 from += tabsize - from % tabsize;
1146 print_select_list (list, list_len, max_elem_len, indices_len)
1148 int list_len, max_elem_len, indices_len;
1150 int ind, row, elem_len, pos, cols, rows;
1151 int first_column_indices_len, other_indices_len;
1155 putc ('\n', stderr);
1159 cols = COLS / max_elem_len;
1162 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1163 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1171 first_column_indices_len = NUMBER_LEN (rows);
1172 other_indices_len = indices_len;
1174 for (row = 0; row < rows; row++)
1180 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1181 elem_len = print_index_and_element (indices_len, ind + 1, list);
1182 elem_len += indices_len + RP_SPACE_LEN;
1184 if (ind >= list_len)
1186 indent (pos + elem_len, pos + max_elem_len);
1187 pos += max_elem_len;
1189 putc ('\n', stderr);
1193 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1194 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1195 If the number is between 1 and LIST_LEN, return that selection. If EOF
1196 is read, return a null string. If a blank line is entered, the loop is
1199 select_query (list, list_len, prompt)
1204 int max_elem_len, indices_len, len, reply;
1206 char *repl_string, *t;
1208 t = get_string_value ("LINES");
1209 LINES = (t && *t) ? atoi (t) : 24;
1210 t = get_string_value ("COLUMNS");
1211 COLS = (t && *t) ? atoi (t) : 80;
1214 t = get_string_value ("TABSIZE");
1215 tabsize = (t && *t) ? atoi (t) : 8;
1223 for (l = list; l; l = l->next)
1225 len = STRLEN (l->word->word);
1226 if (len > max_elem_len)
1229 indices_len = NUMBER_LEN (list_len);
1230 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1234 print_select_list (list, list_len, max_elem_len, indices_len);
1235 printf ("%s", prompt);
1239 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1242 return ((char *)NULL);
1244 repl_string = get_string_value ("REPLY");
1245 if (*repl_string == 0)
1247 reply = atoi (repl_string);
1248 if (reply < 1 || reply > list_len)
1252 while (l && --reply)
1254 return (l->word->word);
1258 /* Execute a SELECT command. The syntax is:
1259 SELECT word IN list DO command_list DONE
1260 Only `break' or `return' in command_list will terminate
1262 execute_select_command (select_command)
1263 SELECT_COM *select_command;
1265 WORD_LIST *releaser, *list;
1266 char *identifier, *ps3_prompt, *selection;
1267 int retval, list_len, return_val;
1269 SHELL_VAR *old_value = (SHELL_VAR *)0;
1273 retval = EXECUTION_SUCCESS;
1275 if (check_identifier (select_command->name, 1) == 0)
1276 return (EXECUTION_FAILURE);
1279 identifier = select_command->name->word;
1281 /* command and arithmetic substitution, parameter and variable expansion,
1282 word splitting, pathname expansion, and quote removal. */
1283 list = releaser = expand_words_no_vars (select_command->map_list);
1284 list_len = list_length (list);
1285 if (list == 0 || list_len == 0)
1288 dispose_words (list);
1289 return (EXECUTION_SUCCESS);
1292 begin_unwind_frame ("select");
1293 add_unwind_protect (dispose_words, releaser);
1296 if (lexical_scoping)
1298 old_value = copy_variable (find_variable (identifier));
1300 add_unwind_protect (dispose_variable, old_value);
1304 if (select_command->flags & CMD_IGNORE_RETURN)
1305 select_command->action->flags |= CMD_IGNORE_RETURN;
1307 unwind_protect_int (return_catch_flag);
1308 unwind_protect_jmp_buf (return_catch);
1309 return_catch_flag++;
1313 ps3_prompt = get_string_value ("PS3");
1318 selection = select_query (list, list_len, ps3_prompt);
1323 bind_variable (identifier, selection);
1325 return_val = setjmp (return_catch);
1329 retval = return_catch_value;
1333 retval = execute_command (select_command->action);
1348 if (lexical_scoping)
1351 makunbound (identifier, shell_variables);
1354 SHELL_VAR *new_value;
1356 new_value = bind_variable (identifier, value_cell(old_value));
1357 new_value->attributes = old_value->attributes;
1358 dispose_variable (old_value);
1363 run_unwind_frame ("select");
1366 #endif /* SELECT_COMMAND */
1368 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1369 The pattern_list is a linked list of pattern clauses; each clause contains
1370 some patterns to compare word_desc against, and an associated command to
1372 execute_case_command (case_command)
1373 CASE_COM *case_command;
1375 register WORD_LIST *list;
1377 PATTERN_LIST *clauses;
1381 /* Posix.2 specifies that the WORD is tilde expanded. */
1382 if (member ('~', case_command->word->word))
1384 word = tilde_expand (case_command->word->word);
1385 free (case_command->word->word);
1386 case_command->word->word = word;
1389 wlist = expand_word_no_split (case_command->word, 0);
1390 clauses = case_command->clauses;
1391 word = (wlist) ? string_list (wlist) : savestring ("");
1392 retval = EXECUTION_SUCCESS;
1394 begin_unwind_frame ("case");
1395 add_unwind_protect (dispose_words, wlist);
1396 add_unwind_protect ((Function *)xfree, word);
1401 list = clauses->patterns;
1408 /* Posix.2 specifies to tilde expand each member of the pattern
1410 if (member ('~', list->word->word))
1412 char *expansion = tilde_expand (list->word->word);
1413 free (list->word->word);
1414 list->word->word = expansion;
1417 es = expand_word_leave_quoted (list->word, 0);
1419 if (es && es->word && es->word->word && *(es->word->word))
1420 pattern = quote_string_for_globbing (es->word->word, 1);
1422 pattern = savestring ("");
1424 /* Since the pattern does not undergo quote removal (as per
1425 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1426 to recognize backslashes as escape characters. */
1427 match = (fnmatch (pattern, word, 0) != FNM_NOMATCH);
1434 if (clauses->action &&
1435 (case_command->flags & CMD_IGNORE_RETURN))
1436 clauses->action->flags |= CMD_IGNORE_RETURN;
1437 execute_command (clauses->action);
1438 retval = last_command_exit_value;
1446 clauses = clauses->next;
1450 dispose_words (wlist);
1452 discard_unwind_frame ("case");
1460 /* The WHILE command. Syntax: WHILE test DO action; DONE.
1461 Repeatedly execute action while executing test produces
1462 EXECUTION_SUCCESS. */
1463 execute_while_command (while_command)
1464 WHILE_COM *while_command;
1466 return (execute_while_or_until (while_command, CMD_WHILE));
1469 /* UNTIL is just like WHILE except that the test result is negated. */
1470 execute_until_command (while_command)
1471 WHILE_COM *while_command;
1473 return (execute_while_or_until (while_command, CMD_UNTIL));
1476 /* The body for both while and until. The only difference between the
1477 two is that the test value is treated differently. TYPE is
1478 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1479 be EXECUTION_SUCCESS if no commands in the body are executed, and
1480 the status of the last command executed in the body otherwise. */
1481 execute_while_or_until (while_command, type)
1482 WHILE_COM *while_command;
1485 int return_value, body_status;
1487 body_status = EXECUTION_SUCCESS;
1490 while_command->test->flags |= CMD_IGNORE_RETURN;
1491 if (while_command->flags & CMD_IGNORE_RETURN)
1492 while_command->action->flags |= CMD_IGNORE_RETURN;
1496 return_value = execute_command (while_command->test);
1499 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
1501 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
1505 body_status = execute_command (while_command->action);
1523 return (body_status);
1526 /* IF test THEN command [ELSE command].
1527 IF also allows ELIF in the place of ELSE IF, but
1528 the parser makes *that* stupidity transparent. */
1529 execute_if_command (if_command)
1534 if_command->test->flags |= CMD_IGNORE_RETURN;
1535 return_value = execute_command (if_command->test);
1537 if (return_value == EXECUTION_SUCCESS)
1540 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
1541 if_command->true_case->flags |= CMD_IGNORE_RETURN;
1542 return (execute_command (if_command->true_case));
1548 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
1549 if_command->false_case->flags |= CMD_IGNORE_RETURN;
1551 return (execute_command (if_command->false_case));
1563 var = bind_variable ("_", arg);
1564 var->attributes &= ~att_exported;
1567 /* The meaty part of all the executions. We have to start hacking the
1568 real execution of commands here. Fork a process, set things up,
1569 execute the command. */
1570 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
1571 SIMPLE_COM *simple_command;
1572 int pipe_in, pipe_out, async;
1573 struct fd_bitmap *fds_to_close;
1575 WORD_LIST *words, *lastword;
1576 char *command_line, *lastarg;
1577 int first_word_quoted, result;
1578 pid_t old_last_command_subst_pid;
1580 result = EXECUTION_SUCCESS;
1582 /* If we're in a function, update the pseudo-line-number information. */
1583 if (variable_context)
1584 line_number = simple_command->line - function_line_number;
1586 /* Remember what this command line looks like at invocation. */
1587 command_string_index = 0;
1588 print_simple_command (simple_command);
1589 command_line = (char *)alloca (1 + strlen (the_printed_command));
1590 strcpy (command_line, the_printed_command);
1593 simple_command->words ? simple_command->words->word->quoted : 0;
1595 old_last_command_subst_pid = last_command_subst_pid;
1597 /* If we are re-running this as the result of executing the `command'
1598 builtin, do not expand the command words a second time. */
1599 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
1601 current_fds_to_close = fds_to_close;
1602 words = expand_words (simple_command->words);
1603 current_fds_to_close = (struct fd_bitmap *)NULL;
1606 words = copy_word_list (simple_command->words);
1608 lastarg = (char *)NULL;
1610 /* It is possible for WORDS not to have anything left in it.
1611 Perhaps all the words consisted of `$foo', and there was
1612 no variable `$foo'. */
1618 begin_unwind_frame ("simple-command");
1620 if (echo_command_at_execute)
1622 char *line = string_list (words);
1625 fprintf (stderr, "%s%s\n", indirection_level_string (), line);
1630 if (simple_command->flags & CMD_NO_FUNCTIONS)
1631 func = (SHELL_VAR *)NULL;
1633 func = find_function (words->word->word);
1635 add_unwind_protect (dispose_words, words);
1639 /* Bind the last word in this command to "$_" after execution. */
1640 for (lastword = words; lastword->next; lastword = lastword->next);
1641 lastarg = lastword->word->word;
1643 #if defined (JOB_CONTROL)
1644 /* Is this command a job control related thing? */
1645 if (words->word->word[0] == '%')
1650 this_command_name = "bg";
1652 this_command_name = "fg";
1654 last_shell_builtin = this_shell_builtin;
1655 this_shell_builtin = builtin_address (this_command_name);
1656 result = (*this_shell_builtin) (words);
1660 /* One other possiblilty. The user may want to resume an existing job.
1661 If they do, find out whether this word is a candidate for a running
1664 char *auto_resume_value = get_string_value ("auto_resume");
1666 if (auto_resume_value &&
1667 !first_word_quoted &&
1669 words->word->word[0] &&
1670 !simple_command->redirects &&
1671 pipe_in == NO_PIPE &&
1672 pipe_out == NO_PIPE &&
1675 char *word = words->word->word;
1677 int wl, cl, exact, substring, match, started_status;
1678 register PROCESS *p;
1680 exact = STREQ (auto_resume_value, "exact");
1681 substring = STREQ (auto_resume_value, "substring");
1683 for (i = job_slots - 1; i > -1; i--)
1685 if (!jobs[i] || (JOBSTATE (i) != JSTOPPED))
1693 cl = strlen (p->command);
1694 match = STREQN (p->command, word, cl);
1697 match = strindex (p->command, word) != (char *)0;
1699 match = STREQN (p->command, word, wl);
1707 run_unwind_frame ("simple-command");
1708 last_shell_builtin = this_shell_builtin;
1709 this_shell_builtin = builtin_address ("fg");
1711 started_status = start_job (i, 1);
1713 if (started_status < 0)
1714 return (EXECUTION_FAILURE);
1716 return (started_status);
1718 while (p != jobs[i]->pipe);
1722 #endif /* JOB_CONTROL */
1724 /* Remember the name of this command globally. */
1725 this_command_name = words->word->word;
1729 /* This command could be a shell builtin or a user-defined function.
1730 If so, and we have pipes, then fork a subshell in here. Else, just
1734 builtin = (Function *)NULL;
1736 builtin = find_shell_builtin (this_command_name);
1738 last_shell_builtin = this_shell_builtin;
1739 this_shell_builtin = builtin;
1741 if (builtin || func)
1743 if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
1745 if (make_child (savestring (command_line), async) == 0)
1747 /* Cancel traps, in trap.c. */
1748 restore_original_signals ();
1751 setup_async_signals ();
1753 execute_subshell_builtin_or_function
1754 (words, simple_command->redirects, builtin, func,
1755 pipe_in, pipe_out, async, fds_to_close,
1756 simple_command->flags);
1760 close_pipes (pipe_in, pipe_out);
1761 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1762 unlink_fifo_list ();
1769 result = execute_builtin_or_function
1770 (words, builtin, func, simple_command->redirects, fds_to_close,
1771 simple_command->flags);
1777 execute_disk_command (words, simple_command->redirects, command_line,
1778 pipe_in, pipe_out, async, fds_to_close,
1779 (simple_command->flags & CMD_NO_FORK));
1783 else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
1785 /* We have a null command, but we really want a subshell to take
1786 care of it. Just fork, do piping and redirections, and exit. */
1787 if (make_child (savestring (""), async) == 0)
1789 /* Cancel traps, in trap.c. */
1790 restore_original_signals ();
1792 do_piping (pipe_in, pipe_out);
1794 subshell_environment = 1;
1796 if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
1797 exit (EXECUTION_SUCCESS);
1799 exit (EXECUTION_FAILURE);
1803 close_pipes (pipe_in, pipe_out);
1804 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
1805 unlink_fifo_list ();
1807 result = EXECUTION_SUCCESS;
1813 /* Even if there aren't any command names, pretend to do the
1814 redirections that are specified. The user expects the side
1815 effects to take place. If the redirections fail, then return
1816 failure. Otherwise, if a command substitution took place while
1817 expanding the command or a redirection, return the value of that
1818 substitution. Otherwise, return EXECUTION_SUCCESS. */
1820 if (do_redirections (simple_command->redirects, 0, 0, 0) != 0)
1821 result = EXECUTION_FAILURE;
1822 else if (old_last_command_subst_pid != last_command_subst_pid)
1823 result = last_command_exit_value;
1825 result = EXECUTION_SUCCESS;
1829 bind_lastarg (lastarg);
1830 /* The unwind-protect frame is set up only if WORDS is not empty. */
1832 run_unwind_frame ("simple-command");
1837 execute_builtin (builtin, words, flags, subshell)
1840 int flags, subshell;
1842 int old_e_flag = exit_immediately_on_error;
1845 /* The eval builtin calls parse_and_execute, which does not know about
1846 the setting of flags, and always calls the execution functions with
1847 flags that will exit the shell on an error if -e is set. If the
1848 eval builtin is being called, and we're supposed to ignore the exit
1849 value of the command, we turn the -e flag off ourselves, then
1850 restore it when the command completes. */
1851 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
1853 begin_unwind_frame ("eval_builtin");
1854 unwind_protect_int (exit_immediately_on_error);
1855 exit_immediately_on_error = 0;
1858 /* The temporary environment for a builtin is supposed to apply to
1859 all commands executed by that builtin. Currently, this is a
1860 problem only with the `source' builtin. */
1861 if (builtin == source_builtin)
1864 begin_unwind_frame ("builtin_env");
1868 builtin_env = copy_array (temporary_env);
1870 add_unwind_protect (dispose_builtin_env, (char *)NULL);
1871 dispose_used_env_vars ();
1875 builtin_env = (char **)NULL;
1879 result = ((*builtin) (words->next));
1881 if (subshell == 0 && builtin == source_builtin)
1883 dispose_builtin_env ();
1884 discard_unwind_frame ("builtin_env");
1887 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
1889 exit_immediately_on_error += old_e_flag;
1890 discard_unwind_frame ("eval_builtin");
1896 /* XXX -- why do we need to set up unwind-protects for the case where
1897 subshell == 1 at all? */
1899 execute_function (var, words, flags, fds_to_close, async, subshell)
1902 int flags, subshell, async;
1903 struct fd_bitmap *fds_to_close;
1905 int return_val, result;
1908 tc = (COMMAND *)copy_command (function_cell (var));
1909 if (tc && (flags & CMD_IGNORE_RETURN))
1910 tc->flags |= CMD_IGNORE_RETURN;
1913 begin_unwind_frame ("subshell_function_calling");
1915 begin_unwind_frame ("function_calling");
1920 add_unwind_protect (pop_context, (char *)NULL);
1921 unwind_protect_int (line_number);
1924 unwind_protect_int (variable_context);
1926 unwind_protect_int (loop_level);
1927 unwind_protect_int (return_catch_flag);
1928 unwind_protect_jmp_buf (return_catch);
1929 add_unwind_protect (dispose_command, (char *)tc);
1931 /* The temporary environment for a function is supposed to apply to
1932 all commands executed within the function body. */
1935 function_env = copy_array (temporary_env);
1936 add_unwind_protect (dispose_function_env, (char *)NULL);
1937 dispose_used_env_vars ();
1941 function_env = (char **)NULL;
1944 /* Note the second argument of "1", meaning that we discard
1945 the current value of "$*"! This is apparently the right thing. */
1946 remember_args (words->next, 1);
1948 line_number = function_line_number = tc->line;
1952 #if defined (JOB_CONTROL)
1953 stop_pipeline (async, (COMMAND *)NULL);
1955 if (tc->type == cm_group)
1956 fc = tc->value.Group->command;
1960 if (fc && (flags & CMD_IGNORE_RETURN))
1961 fc->flags |= CMD_IGNORE_RETURN;
1968 return_catch_flag++;
1969 return_val = setjmp (return_catch);
1972 result = return_catch_value;
1974 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
1977 run_unwind_frame ("subshell_function_calling");
1979 run_unwind_frame ("function_calling");
1984 /* Execute a shell builtin or function in a subshell environment. This
1985 routine does not return; it only calls exit(). If BUILTIN is non-null,
1986 it points to a function to call to execute a shell builtin; otherwise
1987 VAR points at the body of a function to execute. WORDS is the arguments
1988 to the command, REDIRECTS specifies redirections to perform before the
1989 command is executed. */
1991 execute_subshell_builtin_or_function (words, redirects, builtin, var,
1992 pipe_in, pipe_out, async, fds_to_close,
1995 REDIRECT *redirects;
1998 int pipe_in, pipe_out, async;
1999 struct fd_bitmap *fds_to_close;
2002 /* A subshell is neither a login shell nor interactive. */
2003 login_shell = interactive = 0;
2005 subshell_environment = 1;
2007 maybe_make_export_env ();
2009 #if defined (JOB_CONTROL)
2010 /* Eradicate all traces of job control after we fork the subshell, so
2011 all jobs begun by this subshell are in the same process group as
2012 the shell itself. */
2014 /* Allow the output of `jobs' to be piped. */
2015 if (builtin == jobs_builtin && !async &&
2016 (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
2017 kill_current_pipeline ();
2019 without_job_control ();
2021 set_sigchld_handler ();
2022 #endif /* JOB_CONTROL */
2024 set_sigint_handler ();
2026 do_piping (pipe_in, pipe_out);
2029 close_fd_bitmap (fds_to_close);
2031 if (do_redirections (redirects, 1, 0, 0) != 0)
2032 exit (EXECUTION_FAILURE);
2038 /* Give builtins a place to jump back to on failure,
2039 so we don't go back up to main(). */
2040 result = setjmp (top_level);
2042 if (result == EXITPROG)
2043 exit (last_command_exit_value);
2045 exit (EXECUTION_FAILURE);
2047 exit (execute_builtin (builtin, words, flags, 1));
2051 exit (execute_function (var, words, flags, fds_to_close, async, 1));
2055 /* Execute a builtin or function in the current shell context. If BUILTIN
2056 is non-null, it is the builtin command to execute, otherwise VAR points
2057 to the body of a function. WORDS are the command's arguments, REDIRECTS
2058 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2059 file descriptors to close.
2061 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2062 not undone before this function returns. */
2064 execute_builtin_or_function (words, builtin, var, redirects,
2065 fds_to_close, flags)
2069 REDIRECT *redirects;
2070 struct fd_bitmap *fds_to_close;
2073 int result = EXECUTION_FAILURE;
2074 REDIRECT *saved_undo_list;
2076 if (do_redirections (redirects, 1, 1, 0) != 0)
2078 cleanup_redirects (redirection_undo_list);
2079 redirection_undo_list = (REDIRECT *)NULL;
2080 dispose_exec_redirects ();
2081 return (EXECUTION_FAILURE);
2084 saved_undo_list = redirection_undo_list;
2086 /* Calling the "exec" builtin changes redirections forever. */
2087 if (builtin == exec_builtin)
2089 dispose_redirects (saved_undo_list);
2090 saved_undo_list = exec_redirection_undo_list;
2091 exec_redirection_undo_list = (REDIRECT *)NULL;
2094 dispose_exec_redirects ();
2096 if (saved_undo_list)
2098 begin_unwind_frame ("saved redirects");
2099 add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
2100 add_unwind_protect (dispose_redirects, (char *)saved_undo_list);
2103 redirection_undo_list = (REDIRECT *)NULL;
2106 result = execute_builtin (builtin, words, flags, 0);
2108 result = execute_function (var, words, flags, fds_to_close, 0, 0);
2110 if (saved_undo_list)
2112 redirection_undo_list = saved_undo_list;
2113 discard_unwind_frame ("saved redirects");
2116 if (redirection_undo_list)
2118 do_redirections (redirection_undo_list, 1, 0, 0);
2119 dispose_redirects (redirection_undo_list);
2120 redirection_undo_list = (REDIRECT *)NULL;
2127 setup_async_signals ()
2129 #if defined (JOB_CONTROL)
2130 if (job_control == 0)
2133 set_signal_handler (SIGINT, SIG_IGN);
2134 set_signal_ignored (SIGINT);
2135 set_signal_handler (SIGQUIT, SIG_IGN);
2136 set_signal_ignored (SIGQUIT);
2140 /* Execute a simple command that is hopefully defined in a disk file
2145 3) look up the command
2148 6) If the execve failed, see if the file has executable mode set.
2149 If so, and it isn't a directory, then execute its contents as
2152 Note that the filename hashing stuff has to take place up here,
2153 in the parent. This is probably why the Bourne style shells
2154 don't handle it, since that would require them to go through
2155 this gnarly hair, for no good reason. */
2157 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
2158 async, fds_to_close, nofork)
2160 REDIRECT *redirects;
2162 int pipe_in, pipe_out, async;
2163 struct fd_bitmap *fds_to_close;
2164 int nofork; /* Don't fork, just exec, if no pipes */
2166 register char *pathname;
2167 char *hashed_file, *command, **args;
2171 pathname = words->word->word;
2172 #if defined (RESTRICTED_SHELL)
2173 if (restricted && strchr (pathname, '/'))
2175 report_error ("%s: restricted: cannot specify `/' in command names",
2177 last_command_exit_value = EXECUTION_FAILURE;
2180 #endif /* RESTRICTED_SHELL */
2182 hashed_file = command = (char *)NULL;
2184 /* If PATH is in the temporary environment for this command, don't use the
2185 hash table to search for the full pathname. */
2187 path = find_tempenv_variable ("PATH");
2191 /* Don't waste time trying to find hashed data for a pathname
2192 that is already completely specified. */
2194 if (!path && !absolute_program (pathname))
2195 hashed_file = find_hashed_filename (pathname);
2197 /* If a command found in the hash table no longer exists, we need to
2198 look for it in $PATH. Thank you Posix.2. This forces us to stat
2199 every command found in the hash table. It seems pretty stupid to me,
2200 so I am basing it on the presence of POSIXLY_CORRECT. */
2202 if (hashed_file && posixly_correct)
2206 st = file_status (hashed_file);
2207 if ((st ^ (FS_EXISTS | FS_EXECABLE)) != 0)
2209 remove_hashed_filename (pathname);
2210 hashed_file = (char *)NULL;
2215 command = savestring (hashed_file);
2216 else if (absolute_program (pathname))
2217 /* A command containing a slash is not looked up in PATH or saved in
2219 command = savestring (pathname);
2222 command = find_user_command (pathname);
2223 if (command && !hashing_disabled && !temp_path)
2224 remember_filename (pathname, command, dot_found_in_search, 1);
2227 maybe_make_export_env ();
2230 put_command_name_into_env (command);
2232 /* We have to make the child before we check for the non-existance
2233 of COMMAND, since we want the error messages to be redirected. */
2234 /* If we can get away without forking and there are no pipes to deal with,
2235 don't bother to fork, just directly exec the command. */
2236 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
2239 pid = make_child (savestring (command_line), async);
2243 int old_interactive;
2245 /* Cancel traps, in trap.c. */
2246 restore_original_signals ();
2248 /* restore_original_signals may have undone the work done
2249 by make_child to ensure that SIGINT and SIGQUIT are ignored
2250 in asynchronous children. */
2252 setup_async_signals ();
2254 do_piping (pipe_in, pipe_out);
2256 /* Execve expects the command name to be in args[0]. So we
2257 leave it there, in the same format that the user used to
2259 args = make_word_array (words);
2263 old_interactive = interactive;
2267 subshell_environment = 1;
2269 /* This functionality is now provided by close-on-exec of the
2270 file descriptors manipulated by redirection and piping.
2271 Some file descriptors still need to be closed in all children
2272 because of the way bash does pipes; fds_to_close is a
2273 bitmap of all such file descriptors. */
2275 close_fd_bitmap (fds_to_close);
2277 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
2279 #if defined (PROCESS_SUBSTITUTION)
2280 /* Try to remove named pipes that may have been created as the
2281 result of redirections. */
2282 unlink_fifo_list ();
2283 #endif /* PROCESS_SUBSTITUTION */
2284 exit (EXECUTION_FAILURE);
2288 interactive = old_interactive;
2292 report_error ("%s: command not found", args[0]);
2293 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
2296 exit (shell_execve (command, args, export_env));
2300 /* Make sure that the pipes are closed in the parent. */
2301 close_pipes (pipe_in, pipe_out);
2302 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2303 unlink_fifo_list ();
2309 /* If the operating system on which we're running does not handle
2310 the #! executable format, then help out. SAMPLE is the text read
2311 from the file, SAMPLE_LEN characters. COMMAND is the name of
2312 the script; it and ARGS, the arguments given by the user, will
2313 become arguments to the specified interpreter. ENV is the environment
2314 to pass to the interpreter.
2316 The word immediately following the #! is the interpreter to execute.
2317 A single argument to the interpreter is allowed. */
2319 execute_shell_script (sample, sample_len, command, args, env)
2320 unsigned char *sample;
2326 char *execname, *firstarg;
2327 int start, size_increment, larry;
2329 /* Find the name of the interpreter to exec. */
2330 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
2334 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2338 execname = xmalloc (1 + (i - start));
2339 strncpy (execname, (char *) (sample + start), i - start);
2340 execname[i - start] = '\0';
2343 /* Now the argument, if any. */
2344 firstarg = (char *)NULL;
2346 whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2350 /* If there is more text on the line, then it is an argument for the
2352 if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
2355 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2358 firstarg = xmalloc (1 + (i - start));
2359 strncpy (firstarg, (char *)(sample + start), i - start);
2360 firstarg[i - start] = '\0';
2365 larry = array_len (args) + size_increment;
2367 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
2369 for (i = larry - 1; i; i--)
2370 args[i] = args[i - size_increment];
2381 args[larry] = (char *)NULL;
2383 return (shell_execve (execname, args, env));
2386 /* Call execve (), handling interpreting shell scripts, and handling
2389 shell_execve (command, args, env)
2393 #if defined (isc386) && defined (_POSIX_SOURCE)
2394 __setostype (0); /* Turn on USGr3 semantics. */
2395 execve (command, args, env);
2396 __setostype (1); /* Turn the POSIX semantics back on. */
2398 execve (command, args, env);
2399 #endif /* !(isc386 && _POSIX_SOURCE) */
2401 /* If we get to this point, then start checking out the file.
2402 Maybe it is something we can hack ourselves. */
2406 if (errno != ENOEXEC)
2408 if ((stat (command, &finfo) == 0) &&
2409 (S_ISDIR (finfo.st_mode)))
2410 report_error ("%s: is a directory", args[0]);
2412 file_error (command);
2414 return (EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
2418 /* This file is executable.
2419 If it begins with #!, then help out people with losing operating
2420 systems. Otherwise, check to see if it is a binary file by seeing
2421 if the first line (or up to 30 characters) are in the ASCII set.
2422 Execute the contents as shell commands. */
2423 int larray = array_len (args) + 1;
2424 int i, should_exec = 0;
2427 int fd = open (command, O_RDONLY);
2430 unsigned char sample[80];
2431 int sample_len = read (fd, &sample[0], 80);
2435 if (sample_len == 0)
2436 return (EXECUTION_SUCCESS);
2438 /* Is this supposed to be an executable script?
2439 If so, the format of the line is "#! interpreter [argument]".
2440 A single argument is allowed. The BSD kernel restricts
2441 the length of the entire line to 32 characters (32 bytes
2442 being the size of the BSD exec header), but we allow 80
2445 if (sample_len > 0 && sample[0] == '#' && sample[1] == '!')
2446 return (execute_shell_script
2447 (sample, sample_len, command, args, env));
2448 else if ((sample_len != -1) &&
2449 check_binary_file (sample, sample_len))
2451 report_error ("%s: cannot execute binary file", command);
2452 return (EX_BINARY_FILE);
2456 #if defined (JOB_CONTROL)
2457 /* Forget about the way that job control was working. We are
2459 without_job_control ();
2460 #endif /* JOB_CONTROL */
2462 /* Forget about any aliases that we knew of. We are in a subshell. */
2463 delete_all_aliases ();
2466 #if defined (JOB_CONTROL)
2467 set_sigchld_handler ();
2468 #endif /* JOB_CONTROL */
2469 set_sigint_handler ();
2471 /* Insert the name of this shell into the argument list. */
2472 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
2474 for (i = larray - 1; i; i--)
2475 args[i] = args[i - 1];
2477 args[0] = shell_name;
2479 args[larray] = (char *)NULL;
2481 if (args[0][0] == '-')
2488 #if defined (isc386) && defined (_POSIX_SOURCE)
2489 __setostype (0); /* Turn on USGr3 semantics. */
2490 execve (shell_name, args, env);
2491 __setostype (1); /* Turn the POSIX semantics back on. */
2493 execve (shell_name, args, env);
2494 #endif /* isc386 && _POSIX_SOURCE */
2496 /* Oh, no! We couldn't even exec this! */
2497 if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
2498 report_error ("%s: is a directory", args[0]);
2500 file_error (args[0]);
2502 return (EXECUTION_FAILURE);
2506 subshell_argc = larray;
2507 subshell_argv = args;
2508 subshell_envp = env;
2509 longjmp (subshell_top_level, 1);
2515 #if defined (PROCESS_SUBSTITUTION)
2516 /* Currently unused */
2520 register int i, fd_table_size;
2522 fd_table_size = getdtablesize ();
2523 if (fd_table_size > 256) /* clamp to a reasonable value */
2524 fd_table_size = 256;
2526 for (i = 3; i < fd_table_size; i++)
2529 #endif /* PROCESS_SUBSTITUTION */
2532 close_pipes (in, out)
2541 /* Redirect input and output to be from and to the specified pipes.
2542 NO_PIPE and REDIRECT_BOTH are handled correctly. */
2544 do_piping (pipe_in, pipe_out)
2545 int pipe_in, pipe_out;
2547 if (pipe_in != NO_PIPE)
2549 if (dup2 (pipe_in, 0) < 0)
2550 internal_error ("cannot duplicate fd %d to fd 0: %s",
2551 pipe_in, strerror (errno));
2555 if (pipe_out != NO_PIPE)
2557 if (pipe_out != REDIRECT_BOTH)
2559 if (dup2 (pipe_out, 1) < 0)
2560 internal_error ("cannot duplicate fd %d to fd 1: %s",
2561 pipe_out, strerror (errno));
2562 if (pipe_out == 0 || pipe_out > 1)
2570 #define AMBIGUOUS_REDIRECT -1
2571 #define NOCLOBBER_REDIRECT -2
2572 #define RESTRICTED_REDIRECT -3 /* Only can happen in restricted shells. */
2574 /* Perform the redirections on LIST. If FOR_REAL, then actually make
2575 input and output file descriptors, otherwise just do whatever is
2576 neccessary for side effecting. INTERNAL says to remember how to
2577 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
2578 file descriptors opened in do_redirection () have their close-on-exec
2581 do_redirections (list, for_real, internal, set_clexec)
2583 int for_real, internal, set_clexec;
2586 register REDIRECT *temp = list;
2590 if (redirection_undo_list)
2592 dispose_redirects (redirection_undo_list);
2593 redirection_undo_list = (REDIRECT *)NULL;
2595 if (exec_redirection_undo_list)
2596 dispose_exec_redirects ();
2601 error = do_redirection_internal (temp, for_real, internal, set_clexec);
2607 if (expandable_redirection_filename (temp))
2609 if (posixly_correct && !interactive_shell)
2610 disallow_filename_globbing++;
2611 filename = redirection_expand (temp->redirectee.filename);
2612 if (posixly_correct && !interactive_shell)
2613 disallow_filename_globbing--;
2616 filename = savestring ("");
2619 filename = itos (temp->redirectee.dest);
2623 case AMBIGUOUS_REDIRECT:
2624 report_error ("%s: Ambiguous redirect", filename);
2627 case NOCLOBBER_REDIRECT:
2628 report_error ("%s: Cannot clobber existing file", filename);
2631 #if defined (RESTRICTED_SHELL)
2632 case RESTRICTED_REDIRECT:
2633 report_error ("%s: output redirection restricted", filename);
2635 #endif /* RESTRICTED_SHELL */
2638 report_error ("%s: %s", filename, strerror (error));
2651 /* Return non-zero if the redirection pointed to by REDIRECT has a
2652 redirectee.filename that can be expanded. */
2654 expandable_redirection_filename (redirect)
2659 switch (redirect->instruction)
2661 case r_output_direction:
2662 case r_appending_to:
2663 case r_input_direction:
2664 case r_inputa_direction:
2666 case r_input_output:
2667 case r_output_force:
2668 case r_duplicating_input_word:
2669 case r_duplicating_output_word:
2679 /* Expand the word in WORD returning a string. If WORD expands to
2680 multiple words (or no words), then return NULL. */
2682 redirection_expand (word)
2686 WORD_LIST *tlist1, *tlist2;
2688 tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
2689 tlist2 = expand_words_no_vars (tlist1);
2690 dispose_words (tlist1);
2692 if (!tlist2 || tlist2->next)
2694 /* We expanded to no words, or to more than a single word.
2695 Dispose of the word list and return NULL. */
2697 dispose_words (tlist2);
2698 return ((char *)NULL);
2700 result = string_list (tlist2);
2701 dispose_words (tlist2);
2705 /* Do the specific redirection requested. Returns errno in case of error.
2706 If FOR_REAL is zero, then just do whatever is neccessary to produce the
2707 appropriate side effects. REMEMBERING, if non-zero, says to remember
2708 how to undo each redirection. If SET_CLEXEC is non-zero, then
2709 we set all file descriptors > 2 that we open to be close-on-exec. */
2711 do_redirection_internal (redirect, for_real, remembering, set_clexec)
2713 int for_real, remembering, set_clexec;
2715 WORD_DESC *redirectee = redirect->redirectee.filename;
2716 int redir_fd = redirect->redirectee.dest;
2717 int fd, redirector = redirect->redirector;
2718 char *redirectee_word;
2719 enum r_instruction ri = redirect->instruction;
2720 REDIRECT *new_redirect;
2722 if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
2724 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
2725 the redirection into a new one and continue. */
2726 redirectee_word = redirection_expand (redirectee);
2728 if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
2731 new_redirect = make_redirection (redirector, r_close_this, rd);
2733 else if (all_digits (redirectee_word))
2735 if (ri == r_duplicating_input_word)
2737 rd.dest = atol (redirectee_word);
2738 new_redirect = make_redirection (redirector, r_duplicating_input, rd);
2742 rd.dest = atol (redirectee_word);
2743 new_redirect = make_redirection (redirector, r_duplicating_output, rd);
2746 else if (ri == r_duplicating_output_word && redirector == 1)
2748 if (!posixly_correct)
2750 rd.filename = make_word (redirectee_word);
2751 new_redirect = make_redirection (1, r_err_and_out, rd);
2754 new_redirect = copy_redirect (redirect);
2758 free (redirectee_word);
2759 return (AMBIGUOUS_REDIRECT);
2762 free (redirectee_word);
2764 /* Set up the variables needed by the rest of the function from the
2766 if (new_redirect->instruction == r_err_and_out)
2770 /* Copy the word without allocating any memory that must be
2771 explicitly freed. */
2772 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
2773 xbcopy ((char *)new_redirect->redirectee.filename,
2774 (char *)redirectee, sizeof (WORD_DESC));
2776 alloca_hack = (char *)
2777 alloca (1 + strlen (new_redirect->redirectee.filename->word));
2778 redirectee->word = alloca_hack;
2779 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
2782 /* It's guaranteed to be an integer, and shouldn't be freed. */
2783 redirectee = new_redirect->redirectee.filename;
2785 redir_fd = new_redirect->redirectee.dest;
2786 redirector = new_redirect->redirector;
2787 ri = new_redirect->instruction;
2789 /* Overwrite the flags element of the old redirect with the new value. */
2790 redirect->flags = new_redirect->flags;
2791 dispose_redirects (new_redirect);
2796 case r_output_direction:
2797 case r_appending_to:
2798 case r_input_direction:
2799 case r_inputa_direction:
2800 case r_err_and_out: /* command &>filename */
2801 case r_input_output:
2802 case r_output_force:
2804 if (posixly_correct && !interactive_shell)
2805 disallow_filename_globbing++;
2806 redirectee_word = redirection_expand (redirectee);
2807 if (posixly_correct && !interactive_shell)
2808 disallow_filename_globbing--;
2810 if (!redirectee_word)
2811 return (AMBIGUOUS_REDIRECT);
2813 #if defined (RESTRICTED_SHELL)
2814 if (restricted && (ri == r_output_direction ||
2815 ri == r_input_output ||
2816 ri == r_err_and_out ||
2817 ri == r_appending_to ||
2818 ri == r_output_force))
2820 free (redirectee_word);
2821 return (RESTRICTED_REDIRECT);
2823 #endif /* RESTRICTED_SHELL */
2825 /* If we are in noclobber mode, you are not allowed to overwrite
2826 existing files. Check first. */
2827 if (noclobber && (ri == r_output_direction ||
2828 ri == r_input_output ||
2829 ri == r_err_and_out))
2834 stat_result = stat (redirectee_word, &finfo);
2836 if ((stat_result == 0) && (S_ISREG (finfo.st_mode)))
2838 free (redirectee_word);
2839 return (NOCLOBBER_REDIRECT);
2842 /* If the file was not present, make sure we open it exclusively
2843 so that if it is created before we open it, our open will fail. */
2844 if (stat_result != 0)
2845 redirect->flags |= O_EXCL;
2847 fd = open (redirectee_word, redirect->flags, 0666);
2849 if ((fd < 0) && (errno == EEXIST))
2851 free (redirectee_word);
2852 return (NOCLOBBER_REDIRECT);
2857 fd = open (redirectee_word, redirect->flags, 0666);
2858 #if defined (AFS_CREATE_BUG)
2859 if ((fd < 0) && (errno == EACCES))
2860 fd = open (redirectee_word, (redirect->flags & ~O_CREAT), 0666);
2861 #endif /* AFS_CREATE_BUG */
2863 free (redirectee_word);
2871 /* Only setup to undo it if the thing to undo is active. */
2872 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
2873 add_undo_redirect (redirector);
2875 add_undo_close_redirect (redirector);
2877 #if defined (BUFFERED_INPUT)
2878 check_bash_input (redirector);
2881 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
2884 #if defined (BUFFERED_INPUT)
2885 /* Do not change the buffered stream for an implicit redirection
2886 of /dev/null to fd 0 for asynchronous commands without job
2887 control (r_inputa_direction). */
2888 if (ri == r_input_direction || ri == r_input_output)
2889 duplicate_buffered_stream (fd, redirector);
2890 #endif /* BUFFERED_INPUT */
2893 * If we're remembering, then this is the result of a while, for
2894 * or until loop with a loop redirection, or a function/builtin
2895 * executing in the parent shell with a redirection. In the
2896 * function/builtin case, we want to set all file descriptors > 2
2897 * to be close-on-exec to duplicate the effect of the old
2898 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
2899 * both sh and ksh leave the file descriptors open across execs.
2900 * The Posix standard mentions only the exec builtin.
2902 if (set_clexec && (redirector > 2))
2903 SET_CLOSE_ON_EXEC (redirector);
2906 if (fd != redirector)
2908 #if defined (BUFFERED_INPUT)
2909 if (ri == r_input_direction || ri == r_inputa_direction ||
2910 ri == r_input_output)
2911 close_buffered_fd (fd);
2913 #endif /* !BUFFERED_INPUT */
2914 close (fd); /* Don't close what we just opened! */
2917 /* If we are hacking both stdout and stderr, do the stderr
2918 redirection here. */
2919 if (ri == r_err_and_out)
2924 add_undo_redirect (2);
2925 if (dup2 (1, 2) < 0)
2931 case r_reading_until:
2932 case r_deblank_reading_until:
2933 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
2934 the new input. Place it in a temporary file. */
2938 pid_t pid = getpid ();
2940 /* Make the filename for the temp file. */
2941 sprintf (filename, "/tmp/t%d-sh", pid);
2943 fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
2947 errno = 0; /* XXX */
2948 if (redirectee->word)
2953 /* Expand the text if the word that was specified had
2954 no quoting. The text that we expand is treated
2955 exactly as if it were surrounded by double quotes. */
2957 if (redirectee->quoted)
2959 document = redirectee->word;
2960 document_len = strlen (document);
2961 /* Set errno to something reasonable if the write fails. */
2962 if (write (fd, document, document_len) < document_len)
2973 tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
2978 register WORD_LIST *t;
2980 /* Try using buffered I/O (stdio) and writing a word
2981 at a time, letting stdio do the work of buffering
2982 for us rather than managing our own strings. Most
2983 stdios are not particularly fast, however -- this
2984 may need to be reconsidered later. */
2985 if ((fd2 = dup (fd)) < 0 ||
2986 (fp = fdopen (fd2, "w")) == NULL)
2993 errno = 0; /* XXX */
2994 for (t = tlist; t; t = t->next)
2996 /* This is essentially the body of
2997 string_list_internal expanded inline. */
2998 document = t->word->word;
2999 document_len = strlen (document);
3001 putc (' ', fp); /* separator */
3002 fwrite (document, document_len, 1, fp);
3011 dispose_words (tlist);
3020 /* Make the document really temporary. Also make it the input. */
3021 fd = open (filename, O_RDONLY, 0666);
3023 if (unlink (filename) < 0 || fd < 0)
3033 /* Only setup to undo it if the thing to undo is active. */
3034 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3035 add_undo_redirect (redirector);
3037 add_undo_close_redirect (redirector);
3039 #if defined (BUFFERED_INPUT)
3040 check_bash_input (redirector);
3042 if (dup2 (fd, redirector) < 0)
3048 #if defined (BUFFERED_INPUT)
3049 duplicate_buffered_stream (fd, redirector);
3052 if (set_clexec && (redirector > 2))
3053 SET_CLOSE_ON_EXEC (redirector);
3056 #if defined (BUFFERED_INPUT)
3057 close_buffered_fd (fd);
3064 case r_duplicating_input:
3065 case r_duplicating_output:
3066 if (for_real && (redir_fd != redirector))
3069 /* Only setup to undo it if the thing to undo is active. */
3070 if (fcntl (redirector, F_GETFD, 0) != -1)
3071 add_undo_redirect (redirector);
3073 add_undo_close_redirect (redirector);
3075 #if defined (BUFFERED_INPUT)
3076 check_bash_input (redirector);
3078 /* This is correct. 2>&1 means dup2 (1, 2); */
3079 if (dup2 (redir_fd, redirector) < 0)
3082 #if defined (BUFFERED_INPUT)
3083 if (ri == r_duplicating_input)
3084 duplicate_buffered_stream (redir_fd, redirector);
3085 #endif /* BUFFERED_INPUT */
3087 /* First duplicate the close-on-exec state of redirectee. dup2
3088 leaves the flag unset on the new descriptor, which means it
3089 stays open. Only set the close-on-exec bit for file descriptors
3090 greater than 2 in any case, since 0-2 should always be open
3091 unless closed by something like `exec 2<&-'. */
3092 /* if ((already_set || set_unconditionally) && (ok_to_set))
3094 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
3096 SET_CLOSE_ON_EXEC (redirector);
3103 if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
3104 add_undo_redirect (redirector);
3106 #if defined (BUFFERED_INPUT)
3107 check_bash_input (redirector);
3108 close_buffered_fd (redirector);
3109 #else /* !BUFFERED_INPUT */
3111 #endif /* !BUFFERED_INPUT */
3118 #define SHELL_FD_BASE 10
3120 /* Remember the file descriptor associated with the slot FD,
3121 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
3122 before it is executed. Any redirections that need to be undone
3123 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3124 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3126 add_undo_redirect (fd)
3129 int new_fd, clexec_flag;
3130 REDIRECT *new_redirect, *closer;
3132 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
3136 file_error ("redirection error");
3141 REDIRECT *dummy_redirect;
3143 clexec_flag = fcntl (fd, F_GETFD, 0);
3146 closer = make_redirection (new_fd, r_close_this, rd);
3147 dummy_redirect = copy_redirects (closer);
3149 rd.dest = (long)new_fd;
3150 new_redirect = make_redirection (fd, r_duplicating_output, rd);
3151 new_redirect->next = closer;
3153 closer->next = redirection_undo_list;
3154 redirection_undo_list = new_redirect;
3156 /* Save redirections that need to be undone even if the undo list
3157 is thrown away by the `exec' builtin. */
3158 add_exec_redirect (dummy_redirect);
3160 /* File descriptors used only for saving others should always be
3161 marked close-on-exec. Unfortunately, we have to preserve the
3162 close-on-exec state of the file descriptor we are saving, since
3163 fcntl (F_DUPFD) sets the new file descriptor to remain open
3164 across execs. If, however, the file descriptor whose state we
3165 are saving is <= 2, we can just set the close-on-exec flag,
3166 because file descriptors 0-2 should always be open-on-exec,
3167 and the restore above in do_redirection() will take care of it. */
3168 if (clexec_flag || fd < 3)
3169 SET_CLOSE_ON_EXEC (new_fd);
3174 /* Set up to close FD when we are finished with the current command
3175 and its redirections. */
3177 add_undo_close_redirect (fd)
3183 closer = make_redirection (fd, r_close_this, rd);
3184 closer->next = redirection_undo_list;
3185 redirection_undo_list = closer;
3189 add_exec_redirect (dummy_redirect)
3190 REDIRECT *dummy_redirect;
3192 dummy_redirect->next = exec_redirection_undo_list;
3193 exec_redirection_undo_list = dummy_redirect;
3196 intern_function (name, function)
3202 if (!check_identifier (name, posixly_correct))
3203 return (EXECUTION_FAILURE);
3205 var = find_function (name->word);
3206 if (var && readonly_p (var))
3208 report_error ("%s: readonly function", var->name);
3209 return (EXECUTION_FAILURE);
3212 bind_function (name->word, function);
3213 return (EXECUTION_SUCCESS);
3216 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3217 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3218 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3219 #define X_BIT(x) ((x) & 1)
3221 /* Return some flags based on information about this file.
3222 The EXISTS bit is non-zero if the file is found.
3223 The EXECABLE bit is non-zero the file is executble.
3224 Zero is returned if the file is not found. */
3230 static int user_id = -1;
3232 /* Determine whether this file exists or not. */
3233 if (stat (name, &finfo) < 0)
3236 /* If the file is a directory, then it is not "executable" in the
3237 sense of the shell. */
3238 if (S_ISDIR (finfo.st_mode))
3242 /* We have to use access(2) to determine access because AFS does not
3243 support Unix file system semantics. This may produce wrong
3244 answers for non-AFS files when ruid != euid. I hate AFS. */
3245 if (access (name, X_OK) == 0)
3246 return (FS_EXISTS | FS_EXECABLE);
3251 /* Find out if the file is actually executable. By definition, the
3252 only other criteria is that the file has an execute bit set that
3255 user_id = current_user.euid;
3257 /* Root only requires execute permission for any of owner, group or
3258 others to be able to exec a file. */
3263 bits = (u_mode_bits (finfo.st_mode) |
3264 g_mode_bits (finfo.st_mode) |
3265 o_mode_bits (finfo.st_mode));
3268 return (FS_EXISTS | FS_EXECABLE);
3271 /* If we are the owner of the file, the owner execute bit applies. */
3272 if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
3273 return (FS_EXISTS | FS_EXECABLE);
3275 /* If we are in the owning group, the group permissions apply. */
3276 if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
3277 return (FS_EXISTS | FS_EXECABLE);
3279 /* If `others' have execute permission to the file, then so do we,
3280 since we are also `others'. */
3281 if (X_BIT (o_mode_bits (finfo.st_mode)))
3282 return (FS_EXISTS | FS_EXECABLE);
3288 /* Return non-zero if FILE exists and is executable.
3289 Note that this function is the definition of what an
3290 executable file is; do not change this unless YOU know
3291 what an executable file is. */
3293 executable_file (file)
3296 return (file_status (file) & FS_EXECABLE);
3299 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
3300 encounters a `.' as the directory pathname while scanning the
3301 list of possible pathnames; i.e., if `.' comes before the directory
3302 containing the file of interest. */
3303 int dot_found_in_search = 0;
3305 /* Locate the executable file referenced by NAME, searching along
3306 the contents of the shell PATH variable. Return a new string
3307 which is the full pathname to the file, or NULL if the file
3308 couldn't be found. If a file is found that isn't executable,
3309 and that is the only match, then return that. */
3311 find_user_command (name)
3314 return (find_user_command_internal (name, FS_EXEC_PREFERRED));
3317 /* Locate the file referenced by NAME, searching along the contents
3318 of the shell PATH variable. Return a new string which is the full
3319 pathname to the file, or NULL if the file couldn't be found. This
3320 returns the first file found. */
3322 find_path_file (name)
3325 return (find_user_command_internal (name, FS_EXISTS));
3329 find_user_command_internal (name, flags)
3336 /* Search for the value of PATH in both the temporary environment, and
3337 in the regular list of variables. */
3338 if (var = find_variable_internal ("PATH", 1))
3339 path_list = value_cell (var);
3341 path_list = (char *)NULL;
3343 if (path_list == 0 || *path_list == '\0')
3344 return (savestring (name));
3346 return (find_user_command_in_path (name, path_list, flags));
3349 /* Return the next element from PATH_LIST, a colon separated list of
3350 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
3351 the index is modified by this function.
3352 Return the next element of PATH_LIST or NULL if there are no more. */
3354 get_next_path_element (path_list, path_index_pointer)
3356 int *path_index_pointer;
3360 path = extract_colon_unit (path_list, path_index_pointer);
3368 path = savestring (".");
3375 user_command_matches (name, flags, state)
3384 static char **match_list = NULL;
3385 static int match_list_size = 0;
3386 static int match_index = 0;
3390 /* Create the list of matches. */
3394 (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
3396 for (i = 0; i < match_list_size; i++)
3400 /* Clear out the old match list. */
3401 for (i = 0; i < match_list_size; i++)
3402 match_list[i] = NULL;
3404 /* We haven't found any files yet. */
3407 path_list = get_string_value ("PATH");
3410 while (path_list && path_list[path_index])
3412 path_element = get_next_path_element (path_list, &path_index);
3417 match = find_user_command_in_path (name, path_element, flags);
3419 free (path_element);
3424 if (match_index + 1 == match_list_size)
3425 match_list = (char **)xrealloc
3426 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
3427 match_list[match_index++] = match;
3428 match_list[match_index] = (char *)NULL;
3431 /* We haven't returned any strings yet. */
3435 match = match_list[match_index];
3443 /* Return 1 if PATH1 and PATH2 are the same file. This is kind of
3444 expensive. If non-NULL STP1 and STP2 point to stat structures
3445 corresponding to PATH1 and PATH2, respectively. */
3447 same_file (path1, path2, stp1, stp2)
3448 char *path1, *path2;
3449 struct stat *stp1, *stp2;
3451 struct stat st1, st2;
3455 if (stat (path1, &st1) != 0)
3462 if (stat (path2, &st2) != 0)
3467 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
3470 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
3471 This allocates new memory and returns it. */
3473 make_full_pathname (path, name, name_len)
3480 path_len = strlen (path);
3481 full_path = xmalloc (2 + path_len + name_len);
3482 strcpy (full_path, path);
3483 full_path[path_len] = '/';
3484 strcpy (full_path + path_len + 1, name);
3488 /* This does the dirty work for find_path_file () and find_user_command ().
3489 NAME is the name of the file to search for.
3490 PATH_LIST is a colon separated list of directories to search.
3491 FLAGS contains bit fields which control the files which are eligible.
3493 FS_EXEC_ONLY: The file must be an executable to be found.
3494 FS_EXEC_PREFERRED: If we can't find an executable, then the
3495 the first file matching NAME will do.
3496 FS_EXISTS: The first file found will do.
3499 find_user_command_in_path (name, path_list, flags)
3504 char *full_path, *path, *file_to_lose_on;
3505 int status, path_index, name_len;
3508 name_len = strlen (name);
3510 /* The file name which we would try to execute, except that it isn't
3511 possible to execute it. This is the first file that matches the
3512 name that we are looking for while we are searching $PATH for a
3513 suitable one to execute. If we cannot find a suitable executable
3514 file, then we use this one. */
3515 file_to_lose_on = (char *)NULL;
3517 /* We haven't started looking, so we certainly haven't seen
3518 a `.' as the directory path yet. */
3519 dot_found_in_search = 0;
3521 if (absolute_program (name))
3523 full_path = xmalloc (1 + name_len);
3524 strcpy (full_path, name);
3526 status = file_status (full_path);
3528 /* If the file doesn't exist, quit now. */
3529 if (!(status & FS_EXISTS))
3532 return ((char *)NULL);
3535 /* If we only care about whether the file exists or not, return
3537 if (flags & FS_EXISTS)
3540 /* Otherwise, maybe we care about whether this file is executable.
3541 If it is, and that is what we want, return it. */
3542 if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
3547 return ((char *)NULL);
3551 /* Find out the location of the current working directory. */
3555 while (path_list && path_list[path_index])
3557 /* Allow the user to interrupt out of a lengthy path search. */
3560 path = get_next_path_element (path_list, &path_index);
3567 char *t = tilde_expand (path);
3572 /* Remember the location of "." in the path, in all its forms
3573 (as long as they begin with a `.', e.g. `./.') */
3574 if (!dot_found_in_search && (*path == '.') &&
3575 same_file (".", path, &finfo, (struct stat *)NULL))
3576 dot_found_in_search = 1;
3578 full_path = make_full_pathname (path, name, name_len);
3581 status = file_status (full_path);
3583 if (!(status & FS_EXISTS))
3586 /* The file exists. If the caller simply wants the first file,
3588 if (flags & FS_EXISTS)
3591 /* If the file is executable, then it satisfies the cases of
3592 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
3593 if (status & FS_EXECABLE)
3595 FREE (file_to_lose_on);
3600 /* The file is not executable, but it does exist. If we prefer
3601 an executable, then remember this one if it is the first one
3603 if (flags & FS_EXEC_PREFERRED)
3605 if (!file_to_lose_on)
3606 file_to_lose_on = savestring (full_path);
3613 /* We didn't find exactly what the user was looking for. Return
3614 the contents of FILE_TO_LOSE_ON which is NULL when the search
3615 required an executable, or non-NULL if a file was found and the
3616 search would accept a non-executable as a last resort. */
3617 return (file_to_lose_on);
3620 /* Given a string containing units of information separated by colons,
3621 return the next one pointed to by (P_INDEX), or NULL if there are no more.
3622 Advance (P_INDEX) to the character after the colon. */
3624 extract_colon_unit (string, p_index)
3632 if (!string || (i >= (int)strlen (string)))
3633 return ((char *)NULL);
3635 /* Each call to this routine leaves the index pointing at a colon if
3636 there is more to the path. If I is > 0, then increment past the
3637 `:'. If I is 0, then the path has a leading colon. Trailing colons
3638 are handled OK by the `else' part of the if statement; an empty
3639 string is returned in that case. */
3640 if (i && string[i] == ':')
3645 while (string[i] && string[i] != ':') i++;
3654 /* Return "" in the case of a trailing `:'. */
3655 return (savestring (""));
3661 value = xmalloc (1 + i - start);
3662 strncpy (value, string + start, i - start);
3663 value [i - start] = '\0';
3669 /* Return non-zero if the characters from SAMPLE are not all valid
3670 characters to be found in the first line of a shell script. We
3671 check up to the first newline, or SAMPLE_LEN, whichever comes first.
3672 All of the characters must be printable or whitespace. */
3674 #if !defined (isspace)
3675 #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
3678 #if !defined (isprint)
3679 #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
3683 check_binary_file (sample, sample_len)
3684 unsigned char *sample;
3689 for (i = 0; i < sample_len; i++)
3691 if (sample[i] == '\n')
3694 if (!isspace (sample[i]) && !isprint (sample[i]))