]> git.ipfire.org Git - thirdparty/bash.git/blob - execute_cmd.c
Imported from ../bash-2.01.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 #include <sys/file.h>
30 #include "filecntl.h"
31 #include "posixstat.h"
32 #include <signal.h>
33 #include <sys/param.h>
34
35 #if defined (HAVE_UNISTD_H)
36 # include <unistd.h>
37 #endif
38
39 #if defined (HAVE_LIMITS_H)
40 # include <limits.h>
41 #endif
42
43 /* Some systems require this, mostly for the definition of `struct timezone'.
44 For example, Dynix/ptx has that definition in <time.h> rather than
45 sys/time.h */
46 #if defined (TIME_WITH_SYS_TIME)
47 # include <sys/time.h>
48 # include <time.h>
49 #else
50 # if defined (HAVE_SYS_TIME_H)
51 # include <sys/time.h>
52 # else
53 # include <time.h>
54 # endif
55 #endif
56
57 #if defined (HAVE_SYS_RESOURCE_H)
58 # include <sys/resource.h>
59 #endif
60
61 #if defined (HAVE_SYS_TIMES_H) && defined (HAVE_TIMES)
62 # include <sys/times.h>
63 #endif
64
65 #include <errno.h>
66
67 #if !defined (errno)
68 extern int errno;
69 #endif
70
71 #include "bashansi.h"
72
73 #include "memalloc.h"
74 #include "shell.h"
75 #include <y.tab.h> /* use <...> so we pick it up from the build directory */
76 #include "flags.h"
77 #include "builtins.h"
78 #include "hashlib.h"
79 #include "jobs.h"
80 #include "execute_cmd.h"
81 #include "trap.h"
82 #include "pathexp.h"
83 #include "hashcmd.h"
84
85 #include "builtins/common.h"
86 #include "builtins/builtext.h" /* list of builtins */
87
88 #include <glob/fnmatch.h>
89 #include <tilde/tilde.h>
90
91 #if defined (BUFFERED_INPUT)
92 # include "input.h"
93 #endif
94
95 #if defined (ALIAS)
96 # include "alias.h"
97 #endif
98
99 #if defined (HISTORY)
100 # include "bashhist.h"
101 #endif
102
103 extern int posixly_correct;
104 extern int executing, breaking, continuing, loop_level;
105 extern int interactive, interactive_shell, login_shell, expand_aliases;
106 extern int parse_and_execute_level, running_trap, trap_line_number;
107 extern int command_string_index, variable_context, line_number;
108 extern int dot_found_in_search;
109 extern int already_making_children;
110 extern char **temporary_env, **function_env, **builtin_env;
111 extern char *the_printed_command, *shell_name;
112 extern pid_t last_command_subst_pid;
113 extern Function *last_shell_builtin, *this_shell_builtin;
114 extern char **subshell_argv, **subshell_envp;
115 extern int subshell_argc;
116 extern char *glob_argv_flags;
117
118 extern int getdtablesize ();
119 extern int close ();
120
121 /* Static functions defined and used in this file. */
122 static void close_pipes (), do_piping (), bind_lastarg ();
123 static void cleanup_redirects ();
124 static void add_undo_close_redirect (), add_exec_redirect ();
125 static int add_undo_redirect ();
126 static int do_redirection_internal (), do_redirections ();
127 static int expandable_redirection_filename ();
128 static char *find_user_command_internal (), *find_user_command_in_path ();
129 static char *find_in_path_element (), *find_absolute_program ();
130
131 static int execute_for_command ();
132 #if defined (SELECT_COMMAND)
133 static int execute_select_command ();
134 #endif
135 #if defined (COMMAND_TIMING)
136 static int time_command ();
137 #endif
138 static int execute_case_command ();
139 static int execute_while_command (), execute_until_command ();
140 static int execute_while_or_until ();
141 static int execute_if_command ();
142 static int execute_simple_command ();
143 static int execute_builtin (), execute_function ();
144 static int execute_builtin_or_function ();
145 static int builtin_status ();
146 static void execute_subshell_builtin_or_function ();
147 static void execute_disk_command ();
148 static int execute_connection ();
149 static int execute_intern_function ();
150
151 /* The line number that the currently executing function starts on. */
152 static int function_line_number;
153
154 /* Set to 1 if fd 0 was the subject of redirection to a subshell. Global
155 so that reader_loop can set it to zero before executing a command. */
156 int stdin_redir;
157
158 /* The name of the command that is currently being executed.
159 `test' needs this, for example. */
160 char *this_command_name;
161
162 static COMMAND *currently_executing_command;
163
164 struct stat SB; /* used for debugging */
165
166 static int special_builtin_failed;
167
168 /* Spare redirector used when translating [N]>&WORD or [N]<&WORD to a new
169 redirection and when creating the redirection undo list. */
170 static REDIRECTEE rd;
171
172 /* Set to errno when a here document cannot be created for some reason.
173 Used to print a reasonable error message. */
174 static int heredoc_errno;
175
176 /* The file name which we would try to execute, except that it isn't
177 possible to execute it. This is the first file that matches the
178 name that we are looking for while we are searching $PATH for a
179 suitable one to execute. If we cannot find a suitable executable
180 file, then we use this one. */
181 static char *file_to_lose_on;
182
183 /* For catching RETURN in a function. */
184 int return_catch_flag;
185 int return_catch_value;
186 procenv_t return_catch;
187
188 /* The value returned by the last synchronous command. */
189 int last_command_exit_value;
190
191 /* The list of redirections to perform which will undo the redirections
192 that I made in the shell. */
193 REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
194
195 /* The list of redirections to perform which will undo the internal
196 redirections performed by the `exec' builtin. These are redirections
197 that must be undone even when exec discards redirection_undo_list. */
198 REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
199
200 /* Non-zero if we have just forked and are currently running in a subshell
201 environment. */
202 int subshell_environment;
203
204 /* Non-zero if we should stat every command found in the hash table to
205 make sure it still exists. */
206 int check_hashed_filenames;
207
208 struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
209
210 #define FD_BITMAP_DEFAULT_SIZE 32L
211
212 /* Functions to allocate and deallocate the structures used to pass
213 information from the shell to its children about file descriptors
214 to close. */
215 struct fd_bitmap *
216 new_fd_bitmap (size)
217 long size;
218 {
219 struct fd_bitmap *ret;
220
221 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
222
223 ret->size = size;
224
225 if (size)
226 {
227 ret->bitmap = xmalloc (size);
228 bzero (ret->bitmap, size);
229 }
230 else
231 ret->bitmap = (char *)NULL;
232 return (ret);
233 }
234
235 void
236 dispose_fd_bitmap (fdbp)
237 struct fd_bitmap *fdbp;
238 {
239 FREE (fdbp->bitmap);
240 free (fdbp);
241 }
242
243 void
244 close_fd_bitmap (fdbp)
245 struct fd_bitmap *fdbp;
246 {
247 register int i;
248
249 if (fdbp)
250 {
251 for (i = 0; i < fdbp->size; i++)
252 if (fdbp->bitmap[i])
253 {
254 close (i);
255 fdbp->bitmap[i] = 0;
256 }
257 }
258 }
259
260 /* Return the line number of the currently executing command. */
261 int
262 executing_line_number ()
263 {
264 if (executing && variable_context == 0 && currently_executing_command &&
265 currently_executing_command->type == cm_simple)
266 return currently_executing_command->value.Simple->line;
267 else if (running_trap)
268 return trap_line_number;
269 else
270 return line_number;
271 }
272
273 /* Execute the command passed in COMMAND. COMMAND is exactly what
274 read_command () places into GLOBAL_COMMAND. See "command.h" for the
275 details of the command structure.
276
277 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
278 return values. Executing a command with nothing in it returns
279 EXECUTION_SUCCESS. */
280 int
281 execute_command (command)
282 COMMAND *command;
283 {
284 struct fd_bitmap *bitmap;
285 int result;
286
287 current_fds_to_close = (struct fd_bitmap *)NULL;
288 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
289 begin_unwind_frame ("execute-command");
290 add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
291
292 /* Just do the command, but not asynchronously. */
293 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
294
295 dispose_fd_bitmap (bitmap);
296 discard_unwind_frame ("execute-command");
297
298 #if defined (PROCESS_SUBSTITUTION)
299 unlink_fifo_list ();
300 #endif /* PROCESS_SUBSTITUTION */
301
302 return (result);
303 }
304
305 /* Return 1 if TYPE is a shell control structure type. */
306 static int
307 shell_control_structure (type)
308 enum command_type type;
309 {
310 switch (type)
311 {
312 case cm_for:
313 #if defined (SELECT_COMMAND)
314 case cm_select:
315 #endif
316 case cm_case:
317 case cm_while:
318 case cm_until:
319 case cm_if:
320 case cm_group:
321 return (1);
322
323 default:
324 return (0);
325 }
326 }
327
328 /* A function to use to unwind_protect the redirection undo list
329 for loops. */
330 static void
331 cleanup_redirects (list)
332 REDIRECT *list;
333 {
334 do_redirections (list, 1, 0, 0);
335 dispose_redirects (list);
336 }
337
338 #if 0
339 /* Function to unwind_protect the redirections for functions and builtins. */
340 static void
341 cleanup_func_redirects (list)
342 REDIRECT *list;
343 {
344 do_redirections (list, 1, 0, 0);
345 }
346 #endif
347
348 static void
349 dispose_exec_redirects ()
350 {
351 if (exec_redirection_undo_list)
352 {
353 dispose_redirects (exec_redirection_undo_list);
354 exec_redirection_undo_list = (REDIRECT *)NULL;
355 }
356 }
357
358 #if defined (JOB_CONTROL)
359 /* A function to restore the signal mask to its proper value when the shell
360 is interrupted or errors occur while creating a pipeline. */
361 static int
362 restore_signal_mask (set)
363 sigset_t set;
364 {
365 return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
366 }
367 #endif /* JOB_CONTROL */
368
369 /* A debugging function that can be called from gdb, for instance. */
370 void
371 open_files ()
372 {
373 register int i;
374 int f, fd_table_size;
375
376 fd_table_size = getdtablesize ();
377
378 fprintf (stderr, "pid %d open files:", (int)getpid ());
379 for (i = 3; i < fd_table_size; i++)
380 {
381 if ((f = fcntl (i, F_GETFD, 0)) != -1)
382 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
383 }
384 fprintf (stderr, "\n");
385 }
386
387 static int
388 stdin_redirects (redirs)
389 REDIRECT *redirs;
390 {
391 REDIRECT *rp;
392 int n;
393
394 for (n = 0, rp = redirs; rp; rp = rp->next)
395 switch (rp->instruction)
396 {
397 case r_input_direction:
398 case r_inputa_direction:
399 case r_input_output:
400 case r_reading_until:
401 case r_deblank_reading_until:
402 n++;
403 break;
404 case r_duplicating_input:
405 case r_duplicating_input_word:
406 case r_close_this:
407 n += (rp->redirector == 0);
408 break;
409 case r_output_direction:
410 case r_appending_to:
411 case r_duplicating_output:
412 case r_err_and_out:
413 case r_output_force:
414 case r_duplicating_output_word:
415 break;
416 }
417
418 return n;
419 }
420
421
422 static void
423 async_redirect_stdin ()
424 {
425 int fd;
426
427 fd = open ("/dev/null", O_RDONLY);
428 if (fd > 0)
429 {
430 dup2 (fd, 0);
431 close (fd);
432 }
433 else if (fd < 0)
434 internal_error ("cannot redirect standard input from /dev/null: %s", strerror (errno));
435 }
436
437 #define DESCRIBE_PID(pid) do { if (interactive) describe_pid (pid); } while (0)
438
439 /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
440 COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
441 ASYNCHROUNOUS, if non-zero, says to do this command in the background.
442 PIPE_IN and PIPE_OUT are file descriptors saying where input comes
443 from and where it goes. They can have the value of NO_PIPE, which means
444 I/O is stdin/stdout.
445 FDS_TO_CLOSE is a list of file descriptors to close once the child has
446 been forked. This list often contains the unusable sides of pipes, etc.
447
448 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
449 return values. Executing a command with nothing in it returns
450 EXECUTION_SUCCESS. */
451 int
452 execute_command_internal (command, asynchronous, pipe_in, pipe_out,
453 fds_to_close)
454 COMMAND *command;
455 int asynchronous;
456 int pipe_in, pipe_out;
457 struct fd_bitmap *fds_to_close;
458 {
459 int exec_result, invert, ignore_return, was_debug_trap;
460 REDIRECT *my_undo_list, *exec_undo_list;
461 pid_t last_pid;
462
463 if (command == 0 || breaking || continuing || read_but_dont_execute)
464 return (EXECUTION_SUCCESS);
465
466 run_pending_traps ();
467
468 if (running_trap == 0)
469 currently_executing_command = command;
470
471 invert = (command->flags & CMD_INVERT_RETURN) != 0;
472
473 /* If we're inverting the return value and `set -e' has been executed,
474 we don't want a failing command to inadvertently cause the shell
475 to exit. */
476 if (exit_immediately_on_error && invert) /* XXX */
477 command->flags |= CMD_IGNORE_RETURN; /* XXX */
478
479 exec_result = EXECUTION_SUCCESS;
480
481 /* If a command was being explicitly run in a subshell, or if it is
482 a shell control-structure, and it has a pipe, then we do the command
483 in a subshell. */
484
485 if ((command->flags & (CMD_WANT_SUBSHELL|CMD_FORCE_SUBSHELL)) ||
486 (shell_control_structure (command->type) &&
487 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
488 {
489 pid_t paren_pid;
490
491 /* Fork a subshell, turn off the subshell bit, turn off job
492 control and call execute_command () on the command again. */
493 paren_pid = make_child (savestring (make_command_string (command)),
494 asynchronous);
495 if (paren_pid == 0)
496 {
497 int user_subshell, return_code, function_value, should_redir_stdin;
498
499 should_redir_stdin = (asynchronous && (command->flags & CMD_STDIN_REDIR) &&
500 pipe_in == NO_PIPE &&
501 stdin_redirects (command->redirects) == 0);
502
503 user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
504 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
505
506 /* If a command is asynchronous in a subshell (like ( foo ) & or
507 the special case of an asynchronous GROUP command where the
508 the subshell bit is turned on down in case cm_group: below),
509 turn off `asynchronous', so that two subshells aren't spawned.
510
511 This seems semantically correct to me. For example,
512 ( foo ) & seems to say ``do the command `foo' in a subshell
513 environment, but don't wait for that subshell to finish'',
514 and "{ foo ; bar } &" seems to me to be like functions or
515 builtins in the background, which executed in a subshell
516 environment. I just don't see the need to fork two subshells. */
517
518 /* Don't fork again, we are already in a subshell. A `doubly
519 async' shell is not interactive, however. */
520 if (asynchronous)
521 {
522 #if defined (JOB_CONTROL)
523 /* If a construct like ( exec xxx yyy ) & is given while job
524 control is active, we want to prevent exec from putting the
525 subshell back into the original process group, carefully
526 undoing all the work we just did in make_child. */
527 original_pgrp = -1;
528 #endif /* JOB_CONTROL */
529 interactive_shell = 0;
530 expand_aliases = 0;
531 asynchronous = 0;
532 }
533
534 /* Subshells are neither login nor interactive. */
535 login_shell = interactive = 0;
536
537 subshell_environment = user_subshell ? SUBSHELL_PAREN : SUBSHELL_ASYNC;
538
539 reset_terminating_signals (); /* in shell.c */
540 /* Cancel traps, in trap.c. */
541 restore_original_signals ();
542 if (asynchronous)
543 setup_async_signals ();
544
545 #if defined (JOB_CONTROL)
546 set_sigchld_handler ();
547 #endif /* JOB_CONTROL */
548
549 set_sigint_handler ();
550
551 #if defined (JOB_CONTROL)
552 /* Delete all traces that there were any jobs running. This is
553 only for subshells. */
554 without_job_control ();
555 #endif /* JOB_CONTROL */
556 do_piping (pipe_in, pipe_out);
557
558 /* If this is a user subshell, set a flag if stdin was redirected.
559 This is used later to decide whether to redirect fd 0 to
560 /dev/null for async commands in the subshell. This adds more
561 sh compatibility, but I'm not sure it's the right thing to do. */
562 if (user_subshell)
563 {
564 stdin_redir = stdin_redirects (command->redirects);
565 restore_default_signal (0);
566 }
567
568 if (fds_to_close)
569 close_fd_bitmap (fds_to_close);
570
571 /* If this is an asynchronous command (command &), we want to
572 redirect the standard input from /dev/null in the absence of
573 any specific redirection involving stdin. */
574 if (should_redir_stdin && stdin_redir == 0)
575 async_redirect_stdin ();
576
577 /* Do redirections, then dispose of them before recursive call. */
578 if (command->redirects)
579 {
580 if (do_redirections (command->redirects, 1, 0, 0) != 0)
581 exit (EXECUTION_FAILURE);
582
583 dispose_redirects (command->redirects);
584 command->redirects = (REDIRECT *)NULL;
585 }
586
587 /* If this is a simple command, tell execute_disk_command that it
588 might be able to get away without forking and simply exec.
589 This means things like ( sleep 10 ) will only cause one fork. */
590 if (user_subshell && command->type == cm_simple)
591 {
592 command->flags |= CMD_NO_FORK;
593 command->value.Simple->flags |= CMD_NO_FORK;
594 }
595
596 /* If we're inside a function while executing this subshell, we
597 need to handle a possible `return'. */
598 function_value = 0;
599 if (return_catch_flag)
600 function_value = setjmp (return_catch);
601
602 if (function_value)
603 return_code = return_catch_value;
604 else
605 return_code = execute_command_internal
606 (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
607
608 /* If we were explicitly placed in a subshell with (), we need
609 to do the `shell cleanup' things, such as running traps[0]. */
610 if (user_subshell && signal_is_trapped (0))
611 {
612 last_command_exit_value = return_code;
613 return_code = run_exit_trap ();
614 }
615
616 exit (return_code);
617 }
618 else
619 {
620 close_pipes (pipe_in, pipe_out);
621
622 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
623 unlink_fifo_list ();
624 #endif
625 /* If we are part of a pipeline, and not the end of the pipeline,
626 then we should simply return and let the last command in the
627 pipe be waited for. If we are not in a pipeline, or are the
628 last command in the pipeline, then we wait for the subshell
629 and return its exit status as usual. */
630 if (pipe_out != NO_PIPE)
631 return (EXECUTION_SUCCESS);
632
633 stop_pipeline (asynchronous, (COMMAND *)NULL);
634
635 if (asynchronous == 0)
636 {
637 last_command_exit_value = wait_for (paren_pid);
638
639 /* If we have to, invert the return value. */
640 if (invert)
641 return ((last_command_exit_value == EXECUTION_SUCCESS)
642 ? EXECUTION_FAILURE
643 : EXECUTION_SUCCESS);
644 else
645 return (last_command_exit_value);
646 }
647 else
648 {
649 DESCRIBE_PID (paren_pid);
650
651 run_pending_traps ();
652
653 return (EXECUTION_SUCCESS);
654 }
655 }
656 }
657
658 #if defined (COMMAND_TIMING)
659 if (command->flags & CMD_TIME_PIPELINE)
660 {
661 if (asynchronous)
662 {
663 command->flags |= CMD_FORCE_SUBSHELL;
664 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
665 }
666 else
667 {
668 exec_result = time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close);
669 if (running_trap == 0)
670 currently_executing_command = (COMMAND *)NULL;
671 }
672 return (exec_result);
673 }
674 #endif /* COMMAND_TIMING */
675
676 if (shell_control_structure (command->type) && command->redirects)
677 stdin_redir = stdin_redirects (command->redirects);
678
679 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
680 redirection.) */
681 if (do_redirections (command->redirects, 1, 1, 0) != 0)
682 {
683 cleanup_redirects (redirection_undo_list);
684 redirection_undo_list = (REDIRECT *)NULL;
685 dispose_exec_redirects ();
686 return (EXECUTION_FAILURE);
687 }
688
689 if (redirection_undo_list)
690 {
691 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
692 dispose_redirects (redirection_undo_list);
693 redirection_undo_list = (REDIRECT *)NULL;
694 }
695 else
696 my_undo_list = (REDIRECT *)NULL;
697
698 if (exec_redirection_undo_list)
699 {
700 exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
701 dispose_redirects (exec_redirection_undo_list);
702 exec_redirection_undo_list = (REDIRECT *)NULL;
703 }
704 else
705 exec_undo_list = (REDIRECT *)NULL;
706
707 if (my_undo_list || exec_undo_list)
708 begin_unwind_frame ("loop_redirections");
709
710 if (my_undo_list)
711 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
712
713 if (exec_undo_list)
714 add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
715
716 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
717
718 QUIT;
719
720 switch (command->type)
721 {
722 case cm_simple:
723 {
724 /* We can't rely on this variable retaining its value across a
725 call to execute_simple_command if a longjmp occurs as the
726 result of a `return' builtin. This is true for sure with gcc. */
727 last_pid = last_made_pid;
728 was_debug_trap = signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0;
729
730 if (ignore_return && command->value.Simple)
731 command->value.Simple->flags |= CMD_IGNORE_RETURN;
732 if (command->flags & CMD_STDIN_REDIR)
733 command->value.Simple->flags |= CMD_STDIN_REDIR;
734 exec_result =
735 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
736 asynchronous, fds_to_close);
737
738 /* The temporary environment should be used for only the simple
739 command immediately following its definition. */
740 dispose_used_env_vars ();
741
742 #if (defined (ultrix) && defined (mips)) || defined (C_ALLOCA)
743 /* Reclaim memory allocated with alloca () on machines which
744 may be using the alloca emulation code. */
745 (void) alloca (0);
746 #endif /* (ultrix && mips) || C_ALLOCA */
747
748 /* If we forked to do the command, then we must wait_for ()
749 the child. */
750
751 /* XXX - this is something to watch out for if there are problems
752 when the shell is compiled without job control. */
753 if (already_making_children && pipe_out == NO_PIPE &&
754 last_pid != last_made_pid)
755 {
756 stop_pipeline (asynchronous, (COMMAND *)NULL);
757
758 if (asynchronous)
759 {
760 DESCRIBE_PID (last_made_pid);
761 }
762 else
763 #if !defined (JOB_CONTROL)
764 /* Do not wait for asynchronous processes started from
765 startup files. */
766 if (last_made_pid != last_asynchronous_pid)
767 #endif
768 /* When executing a shell function that executes other
769 commands, this causes the last simple command in
770 the function to be waited for twice. */
771 exec_result = wait_for (last_made_pid);
772 }
773 }
774
775 if (was_debug_trap)
776 run_debug_trap ();
777
778 if (ignore_return == 0 && invert == 0 &&
779 ((posixly_correct && interactive == 0 && special_builtin_failed) ||
780 (exit_immediately_on_error && (exec_result != EXECUTION_SUCCESS))))
781 {
782 last_command_exit_value = exec_result;
783 run_pending_traps ();
784 jump_to_top_level (EXITPROG);
785 }
786
787 break;
788
789 case cm_for:
790 if (ignore_return)
791 command->value.For->flags |= CMD_IGNORE_RETURN;
792 exec_result = execute_for_command (command->value.For);
793 break;
794
795 #if defined (SELECT_COMMAND)
796 case cm_select:
797 if (ignore_return)
798 command->value.Select->flags |= CMD_IGNORE_RETURN;
799 exec_result = execute_select_command (command->value.Select);
800 break;
801 #endif
802
803 case cm_case:
804 if (ignore_return)
805 command->value.Case->flags |= CMD_IGNORE_RETURN;
806 exec_result = execute_case_command (command->value.Case);
807 break;
808
809 case cm_while:
810 if (ignore_return)
811 command->value.While->flags |= CMD_IGNORE_RETURN;
812 exec_result = execute_while_command (command->value.While);
813 break;
814
815 case cm_until:
816 if (ignore_return)
817 command->value.While->flags |= CMD_IGNORE_RETURN;
818 exec_result = execute_until_command (command->value.While);
819 break;
820
821 case cm_if:
822 if (ignore_return)
823 command->value.If->flags |= CMD_IGNORE_RETURN;
824 exec_result = execute_if_command (command->value.If);
825 break;
826
827 case cm_group:
828
829 /* This code can be executed from either of two paths: an explicit
830 '{}' command, or via a function call. If we are executed via a
831 function call, we have already taken care of the function being
832 executed in the background (down there in execute_simple_command ()),
833 and this command should *not* be marked as asynchronous. If we
834 are executing a regular '{}' group command, and asynchronous == 1,
835 we must want to execute the whole command in the background, so we
836 need a subshell, and we want the stuff executed in that subshell
837 (this group command) to be executed in the foreground of that
838 subshell (i.e. there will not be *another* subshell forked).
839
840 What we do is to force a subshell if asynchronous, and then call
841 execute_command_internal again with asynchronous still set to 1,
842 but with the original group command, so the printed command will
843 look right.
844
845 The code above that handles forking off subshells will note that
846 both subshell and async are on, and turn off async in the child
847 after forking the subshell (but leave async set in the parent, so
848 the normal call to describe_pid is made). This turning off
849 async is *crucial*; if it is not done, this will fall into an
850 infinite loop of executions through this spot in subshell after
851 subshell until the process limit is exhausted. */
852
853 if (asynchronous)
854 {
855 command->flags |= CMD_FORCE_SUBSHELL;
856 exec_result =
857 execute_command_internal (command, 1, pipe_in, pipe_out,
858 fds_to_close);
859 }
860 else
861 {
862 if (ignore_return && command->value.Group->command)
863 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
864 exec_result =
865 execute_command_internal (command->value.Group->command,
866 asynchronous, pipe_in, pipe_out,
867 fds_to_close);
868 }
869 break;
870
871 case cm_connection:
872 exec_result = execute_connection (command, asynchronous,
873 pipe_in, pipe_out, fds_to_close);
874 break;
875
876 case cm_function_def:
877 exec_result = execute_intern_function (command->value.Function_def->name,
878 command->value.Function_def->command);
879 break;
880
881 default:
882 programming_error
883 ("execute_command: bad command type `%d'", command->type);
884 }
885
886 if (my_undo_list)
887 {
888 do_redirections (my_undo_list, 1, 0, 0);
889 dispose_redirects (my_undo_list);
890 }
891
892 if (exec_undo_list)
893 dispose_redirects (exec_undo_list);
894
895 if (my_undo_list || exec_undo_list)
896 discard_unwind_frame ("loop_redirections");
897
898 /* Invert the return value if we have to */
899 if (invert)
900 exec_result = (exec_result == EXECUTION_SUCCESS)
901 ? EXECUTION_FAILURE
902 : EXECUTION_SUCCESS;
903
904 last_command_exit_value = exec_result;
905 run_pending_traps ();
906 if (running_trap == 0)
907 currently_executing_command = (COMMAND *)NULL;
908 return (last_command_exit_value);
909 }
910
911 #if defined (COMMAND_TIMING)
912 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
913 static struct timeval *
914 difftimeval (d, t1, t2)
915 struct timeval *d, *t1, *t2;
916 {
917 d->tv_sec = t2->tv_sec - t1->tv_sec;
918 d->tv_usec = t2->tv_usec - t1->tv_usec;
919 if (d->tv_usec < 0)
920 {
921 d->tv_usec += 1000000;
922 d->tv_sec -= 1;
923 if (d->tv_sec < 0) /* ??? -- BSD/OS does this */
924 d->tv_sec = 0;
925 }
926 return d;
927 }
928
929 static struct timeval *
930 addtimeval (d, t1, t2)
931 struct timeval *d, *t1, *t2;
932 {
933 d->tv_sec = t1->tv_sec + t2->tv_sec;
934 d->tv_usec = t1->tv_usec + t2->tv_usec;
935 if (d->tv_usec > 1000000)
936 {
937 d->tv_usec -= 1000000;
938 d->tv_sec += 1;
939 }
940 return d;
941 }
942
943 /* Do "cpu = ((user + sys) * 10000) / real;" with timevals.
944 Barely-tested code from Deven T. Corzine <deven@ties.org>. */
945 static int
946 timeval_to_cpu (rt, ut, st)
947 struct timeval *rt, *ut, *st; /* real, user, sys */
948 {
949 struct timeval t1, t2;
950 register int i;
951
952 addtimeval (&t1, ut, st);
953 t2.tv_sec = rt->tv_sec;
954 t2.tv_usec = rt->tv_usec;
955
956 for (i = 0; i < 6; i++)
957 {
958 if ((t1.tv_sec > 99999999) || (t2.tv_sec > 99999999))
959 break;
960 t1.tv_sec *= 10;
961 t1.tv_sec += t1.tv_usec / 100000;
962 t1.tv_usec *= 10;
963 t1.tv_usec %= 1000000;
964 t2.tv_sec *= 10;
965 t2.tv_sec += t2.tv_usec / 100000;
966 t2.tv_usec *= 10;
967 t2.tv_usec %= 1000000;
968 }
969 for (i = 0; i < 4; i++)
970 {
971 if (t1.tv_sec < 100000000)
972 t1.tv_sec *= 10;
973 else
974 t2.tv_sec /= 10;
975 }
976
977 return ((t2.tv_sec == 0) ? 0 : t1.tv_sec / t2.tv_sec);
978 }
979 #endif /* HAVE_GETRUSAGE && HAVE_GETTIMEOFDAY */
980
981 #define POSIX_TIMEFORMAT "real %2R\nuser %2U\nsys %2S"
982 #define BASH_TIMEFORMAT "\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS"
983
984 static int precs[] = { 0, 100, 10, 1 };
985
986 /* Expand one `%'-prefixed escape sequence from a time format string. */
987 static int
988 mkfmt (buf, prec, lng, sec, sec_fraction)
989 char *buf;
990 int prec, lng;
991 long sec;
992 int sec_fraction;
993 {
994 long min;
995 char abuf[16];
996 int ind, aind;
997
998 ind = 0;
999 abuf[15] = '\0';
1000
1001 /* If LNG is non-zero, we want to decompose SEC into minutes and seconds. */
1002 if (lng)
1003 {
1004 min = sec / 60;
1005 sec %= 60;
1006 aind = 14;
1007 do
1008 abuf[aind--] = (min % 10) + '0';
1009 while (min /= 10);
1010 aind++;
1011 while (abuf[aind])
1012 buf[ind++] = abuf[aind++];
1013 buf[ind++] = 'm';
1014 }
1015
1016 /* Now add the seconds. */
1017 aind = 14;
1018 do
1019 abuf[aind--] = (sec % 10) + '0';
1020 while (sec /= 10);
1021 aind++;
1022 while (abuf[aind])
1023 buf[ind++] = abuf[aind++];
1024
1025 /* We want to add a decimal point and PREC places after it if PREC is
1026 nonzero. PREC is not greater than 3. SEC_FRACTION is between 0
1027 and 999. */
1028 if (prec != 0)
1029 {
1030 buf[ind++] = '.';
1031 for (aind = 1; aind <= prec; aind++)
1032 {
1033 buf[ind++] = (sec_fraction / precs[aind]) + '0';
1034 sec_fraction %= precs[aind];
1035 }
1036 }
1037
1038 if (lng)
1039 buf[ind++] = 's';
1040 buf[ind] = '\0';
1041
1042 return (ind);
1043 }
1044
1045 /* Interpret the format string FORMAT, interpolating the following escape
1046 sequences:
1047 %[prec][l][RUS]
1048
1049 where the optional `prec' is a precision, meaning the number of
1050 characters after the decimal point, the optional `l' means to format
1051 using minutes and seconds (MMmNN[.FF]s), like the `times' builtin',
1052 and the last character is one of
1053
1054 R number of seconds of `real' time
1055 U number of seconds of `user' time
1056 S number of seconds of `system' time
1057
1058 An occurrence of `%%' in the format string is translated to a `%'. The
1059 result is printed to FP, a pointer to a FILE. The other variables are
1060 the seconds and thousandths of a second of real, user, and system time,
1061 resectively. */
1062 static void
1063 print_formatted_time (fp, format, rs, rsf, us, usf, ss, ssf, cpu)
1064 FILE *fp;
1065 char *format;
1066 long rs, us, ss;
1067 int rsf, usf, ssf, cpu;
1068 {
1069 int prec, lng, len;
1070 char *str, *s, ts[32];
1071 int sum, sum_frac;
1072 int sindex, ssize;
1073
1074 len = strlen (format);
1075 ssize = (len + 64) - (len % 64);
1076 str = xmalloc (ssize);
1077 sindex = 0;
1078
1079 for (s = format; *s; s++)
1080 {
1081 if (*s != '%' || s[1] == '\0')
1082 {
1083 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1084 str[sindex++] = *s;
1085 }
1086 else if (s[1] == '%')
1087 {
1088 s++;
1089 RESIZE_MALLOCED_BUFFER (str, sindex, 1, ssize, 64);
1090 str[sindex++] = *s;
1091 }
1092 else if (s[1] == 'P')
1093 {
1094 s++;
1095 if (cpu > 10000)
1096 cpu = 10000;
1097 sum = cpu / 100;
1098 sum_frac = (cpu % 100) * 10;
1099 len = mkfmt (ts, 2, 0, sum, sum_frac);
1100 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1101 strcpy (str + sindex, ts);
1102 sindex += len;
1103 }
1104 else
1105 {
1106 prec = 3; /* default is three places past the decimal point. */
1107 lng = 0; /* default is to not use minutes or append `s' */
1108 s++;
1109 if (isdigit (*s)) /* `precision' */
1110 {
1111 prec = *s++ - '0';
1112 if (prec > 3) prec = 3;
1113 }
1114 if (*s == 'l') /* `length extender' */
1115 {
1116 lng = 1;
1117 s++;
1118 }
1119 if (*s == 'R' || *s == 'E')
1120 len = mkfmt (ts, prec, lng, rs, rsf);
1121 else if (*s == 'U')
1122 len = mkfmt (ts, prec, lng, us, usf);
1123 else if (*s == 'S')
1124 len = mkfmt (ts, prec, lng, ss, ssf);
1125 else
1126 {
1127 internal_error ("bad format character in time format: %c", *s);
1128 free (str);
1129 return;
1130 }
1131 RESIZE_MALLOCED_BUFFER (str, sindex, len, ssize, 64);
1132 strcpy (str + sindex, ts);
1133 sindex += len;
1134 }
1135 }
1136
1137 str[sindex] = '\0';
1138 fprintf (fp, "%s\n", str);
1139 fflush (fp);
1140
1141 free (str);
1142 }
1143
1144 static int
1145 time_command (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1146 COMMAND *command;
1147 int asynchronous, pipe_in, pipe_out;
1148 struct fd_bitmap *fds_to_close;
1149 {
1150 int rv, posix_time, old_flags;
1151 long rs, us, ss;
1152 int rsf, usf, ssf;
1153 int cpu;
1154 char *time_format;
1155
1156 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1157 struct timeval real, user, sys;
1158 struct timeval before, after;
1159 struct timezone dtz;
1160 struct rusage selfb, selfa, kidsb, kidsa; /* a = after, b = before */
1161 #else
1162 # if defined (HAVE_TIMES)
1163 clock_t tbefore, tafter, real, user, sys;
1164 struct tms before, after;
1165 # endif
1166 #endif
1167
1168 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1169 gettimeofday (&before, &dtz);
1170 getrusage (RUSAGE_SELF, &selfb);
1171 getrusage (RUSAGE_CHILDREN, &kidsb);
1172 #else
1173 # if defined (HAVE_TIMES)
1174 tbefore = times (&before);
1175 # endif
1176 #endif
1177
1178 posix_time = (command->flags & CMD_TIME_POSIX);
1179
1180 old_flags = command->flags;
1181 command->flags &= ~(CMD_TIME_PIPELINE|CMD_TIME_POSIX);
1182 rv = execute_command_internal (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1183 command->flags = old_flags;
1184
1185 #if defined (HAVE_GETRUSAGE) && defined (HAVE_GETTIMEOFDAY)
1186 gettimeofday (&after, &dtz);
1187 getrusage (RUSAGE_SELF, &selfa);
1188 getrusage (RUSAGE_CHILDREN, &kidsa);
1189
1190 difftimeval (&real, &before, &after);
1191 timeval_to_secs (&real, &rs, &rsf);
1192
1193 addtimeval (&user, difftimeval(&after, &selfb.ru_utime, &selfa.ru_utime),
1194 difftimeval(&before, &kidsb.ru_utime, &kidsa.ru_utime));
1195 timeval_to_secs (&user, &us, &usf);
1196
1197 addtimeval (&sys, difftimeval(&after, &selfb.ru_stime, &selfa.ru_stime),
1198 difftimeval(&before, &kidsb.ru_stime, &kidsa.ru_stime));
1199 timeval_to_secs (&sys, &ss, &ssf);
1200
1201 cpu = timeval_to_cpu (&real, &user, &sys);
1202 #else
1203 # if defined (HAVE_TIMES)
1204 tafter = times (&after);
1205
1206 real = tafter - tbefore;
1207 clock_t_to_secs (real, &rs, &rsf);
1208
1209 user = (after.tms_utime - before.tms_utime) + (after.tms_cutime - before.tms_cutime);
1210 clock_t_to_secs (user, &us, &usf);
1211
1212 sys = (after.tms_stime - before.tms_stime) + (after.tms_cstime - before.tms_cstime);
1213 clock_t_to_secs (sys, &ss, &ssf);
1214
1215 cpu = (real == 0) ? 0 : ((user + sys) * 10000) / real;
1216
1217 # else
1218 rs = us = ss = 0L;
1219 rsf = usf = ssf = cpu = 0;
1220 # endif
1221 #endif
1222
1223 if (posix_time)
1224 time_format = POSIX_TIMEFORMAT;
1225 else if ((time_format = get_string_value ("TIMEFORMAT")) == 0)
1226 time_format = BASH_TIMEFORMAT;
1227
1228 if (time_format && *time_format)
1229 print_formatted_time (stderr, time_format, rs, rsf, us, usf, ss, ssf, cpu);
1230
1231 return rv;
1232 }
1233 #endif /* COMMAND_TIMING */
1234
1235 static int
1236 execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1237 COMMAND *command;
1238 int asynchronous, pipe_in, pipe_out;
1239 struct fd_bitmap *fds_to_close;
1240 {
1241 int prev, fildes[2], new_bitmap_size, dummyfd, ignore_return, exec_result;
1242 COMMAND *cmd;
1243 struct fd_bitmap *fd_bitmap;
1244
1245 #if defined (JOB_CONTROL)
1246 sigset_t set, oset;
1247 BLOCK_CHILD (set, oset);
1248 #endif /* JOB_CONTROL */
1249
1250 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1251
1252 prev = pipe_in;
1253 cmd = command;
1254
1255 while (cmd && cmd->type == cm_connection &&
1256 cmd->value.Connection && cmd->value.Connection->connector == '|')
1257 {
1258 /* Make a pipeline between the two commands. */
1259 if (pipe (fildes) < 0)
1260 {
1261 sys_error ("pipe error");
1262 #if defined (JOB_CONTROL)
1263 terminate_current_pipeline ();
1264 kill_current_pipeline ();
1265 #endif /* JOB_CONTROL */
1266 last_command_exit_value = EXECUTION_FAILURE;
1267 /* The unwind-protects installed below will take care
1268 of closing all of the open file descriptors. */
1269 throw_to_top_level ();
1270 return (EXECUTION_FAILURE); /* XXX */
1271 }
1272
1273 /* Here is a problem: with the new file close-on-exec
1274 code, the read end of the pipe (fildes[0]) stays open
1275 in the first process, so that process will never get a
1276 SIGPIPE. There is no way to signal the first process
1277 that it should close fildes[0] after forking, so it
1278 remains open. No SIGPIPE is ever sent because there
1279 is still a file descriptor open for reading connected
1280 to the pipe. We take care of that here. This passes
1281 around a bitmap of file descriptors that must be
1282 closed after making a child process in execute_simple_command. */
1283
1284 /* We need fd_bitmap to be at least as big as fildes[0].
1285 If fildes[0] is less than fds_to_close->size, then
1286 use fds_to_close->size. */
1287 new_bitmap_size = (fildes[0] < fds_to_close->size)
1288 ? fds_to_close->size
1289 : fildes[0] + 8;
1290
1291 fd_bitmap = new_fd_bitmap (new_bitmap_size);
1292
1293 /* Now copy the old information into the new bitmap. */
1294 xbcopy ((char *)fds_to_close->bitmap, (char *)fd_bitmap->bitmap, fds_to_close->size);
1295
1296 /* And mark the pipe file descriptors to be closed. */
1297 fd_bitmap->bitmap[fildes[0]] = 1;
1298
1299 /* In case there are pipe or out-of-processes errors, we
1300 want all these file descriptors to be closed when
1301 unwind-protects are run, and the storage used for the
1302 bitmaps freed up. */
1303 begin_unwind_frame ("pipe-file-descriptors");
1304 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
1305 add_unwind_protect (close_fd_bitmap, fd_bitmap);
1306 if (prev >= 0)
1307 add_unwind_protect (close, prev);
1308 dummyfd = fildes[1];
1309 add_unwind_protect (close, dummyfd);
1310
1311 #if defined (JOB_CONTROL)
1312 add_unwind_protect (restore_signal_mask, oset);
1313 #endif /* JOB_CONTROL */
1314
1315 if (ignore_return && cmd->value.Connection->first)
1316 cmd->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1317 execute_command_internal (cmd->value.Connection->first, asynchronous,
1318 prev, fildes[1], fd_bitmap);
1319
1320 if (prev >= 0)
1321 close (prev);
1322
1323 prev = fildes[0];
1324 close (fildes[1]);
1325
1326 dispose_fd_bitmap (fd_bitmap);
1327 discard_unwind_frame ("pipe-file-descriptors");
1328
1329 cmd = cmd->value.Connection->second;
1330 }
1331
1332 /* Now execute the rightmost command in the pipeline. */
1333 if (ignore_return && cmd)
1334 cmd->flags |= CMD_IGNORE_RETURN;
1335 exec_result = execute_command_internal (cmd, asynchronous, prev, pipe_out, fds_to_close);
1336
1337 if (prev >= 0)
1338 close (prev);
1339
1340 #if defined (JOB_CONTROL)
1341 UNBLOCK_CHILD (oset);
1342 #endif
1343
1344 return (exec_result);
1345 }
1346
1347 static int
1348 execute_connection (command, asynchronous, pipe_in, pipe_out, fds_to_close)
1349 COMMAND *command;
1350 int asynchronous, pipe_in, pipe_out;
1351 struct fd_bitmap *fds_to_close;
1352 {
1353 #if 0
1354 REDIRECT *tr, *tl;
1355 #endif
1356 REDIRECT *rp;
1357 COMMAND *tc, *second;
1358 int ignore_return, exec_result;
1359
1360 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
1361
1362 switch (command->value.Connection->connector)
1363 {
1364 /* Do the first command asynchronously. */
1365 case '&':
1366 tc = command->value.Connection->first;
1367 if (tc == 0)
1368 return (EXECUTION_SUCCESS);
1369
1370 rp = tc->redirects;
1371
1372 if (ignore_return)
1373 tc->flags |= CMD_IGNORE_RETURN;
1374 tc->flags |= CMD_AMPERSAND;
1375
1376 /* If this shell was compiled without job control support, if
1377 the shell is not running interactively, if we are currently
1378 in a subshell via `( xxx )', or if job control is not active
1379 then the standard input for an asynchronous command is
1380 forced to /dev/null. */
1381 #if defined (JOB_CONTROL)
1382 if ((!interactive_shell || subshell_environment || !job_control) && !stdin_redir)
1383 #else
1384 if (!stdin_redir)
1385 #endif /* JOB_CONTROL */
1386 {
1387 #if 0
1388 rd.filename = make_bare_word ("/dev/null");
1389 tr = make_redirection (0, r_inputa_direction, rd);
1390 tr->next = tc->redirects;
1391 tc->redirects = tr;
1392 #endif
1393 tc->flags |= CMD_STDIN_REDIR;
1394 }
1395
1396 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out, fds_to_close);
1397
1398 if (tc->flags & CMD_STDIN_REDIR)
1399 {
1400 #if 0
1401 /* Remove the redirection we added above. It matters,
1402 especially for loops, which call execute_command ()
1403 multiple times with the same command. */
1404 tr = tc->redirects;
1405 do
1406 {
1407 tl = tc->redirects;
1408 tc->redirects = tc->redirects->next;
1409 }
1410 while (tc->redirects && tc->redirects != rp);
1411
1412 tl->next = (REDIRECT *)NULL;
1413 dispose_redirects (tr);
1414 #endif
1415 tc->flags &= ~CMD_STDIN_REDIR;
1416 }
1417
1418 second = command->value.Connection->second;
1419 if (second)
1420 {
1421 if (ignore_return)
1422 second->flags |= CMD_IGNORE_RETURN;
1423
1424 exec_result = execute_command_internal (second, asynchronous, pipe_in, pipe_out, fds_to_close);
1425 }
1426
1427 break;
1428
1429 /* Just call execute command on both sides. */
1430 case ';':
1431 if (ignore_return)
1432 {
1433 if (command->value.Connection->first)
1434 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1435 if (command->value.Connection->second)
1436 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1437 }
1438 QUIT;
1439 execute_command (command->value.Connection->first);
1440 QUIT;
1441 exec_result = execute_command_internal (command->value.Connection->second,
1442 asynchronous, pipe_in, pipe_out,
1443 fds_to_close);
1444 break;
1445
1446 case '|':
1447 exec_result = execute_pipeline (command, asynchronous, pipe_in, pipe_out, fds_to_close);
1448 break;
1449
1450 case AND_AND:
1451 case OR_OR:
1452 if (asynchronous)
1453 {
1454 /* If we have something like `a && b &' or `a || b &', run the
1455 && or || stuff in a subshell. Force a subshell and just call
1456 execute_command_internal again. Leave asynchronous on
1457 so that we get a report from the parent shell about the
1458 background job. */
1459 command->flags |= CMD_FORCE_SUBSHELL;
1460 exec_result = execute_command_internal (command, 1, pipe_in, pipe_out, fds_to_close);
1461 break;
1462 }
1463
1464 /* Execute the first command. If the result of that is successful
1465 and the connector is AND_AND, or the result is not successful
1466 and the connector is OR_OR, then execute the second command,
1467 otherwise return. */
1468
1469 if (command->value.Connection->first)
1470 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
1471
1472 exec_result = execute_command (command->value.Connection->first);
1473 QUIT;
1474 if (((command->value.Connection->connector == AND_AND) &&
1475 (exec_result == EXECUTION_SUCCESS)) ||
1476 ((command->value.Connection->connector == OR_OR) &&
1477 (exec_result != EXECUTION_SUCCESS)))
1478 {
1479 if (ignore_return && command->value.Connection->second)
1480 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
1481
1482 exec_result = execute_command (command->value.Connection->second);
1483 }
1484 break;
1485
1486 default:
1487 programming_error ("execute_connection: bad connector `%d'", command->value.Connection->connector);
1488 jump_to_top_level (DISCARD);
1489 exec_result = EXECUTION_FAILURE;
1490 }
1491
1492 return exec_result;
1493 }
1494
1495 #if defined (JOB_CONTROL)
1496 # define REAP() \
1497 do \
1498 { \
1499 if (!interactive_shell) \
1500 reap_dead_jobs (); \
1501 } \
1502 while (0)
1503 #else /* !JOB_CONTROL */
1504 # define REAP() \
1505 do \
1506 { \
1507 if (!interactive_shell) \
1508 cleanup_dead_jobs (); \
1509 } \
1510 while (0)
1511 #endif /* !JOB_CONTROL */
1512
1513
1514 /* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
1515 DO command; DONE */
1516 static int
1517 execute_for_command (for_command)
1518 FOR_COM *for_command;
1519 {
1520 register WORD_LIST *releaser, *list;
1521 SHELL_VAR *v;
1522 char *identifier;
1523 int retval;
1524 #if 0
1525 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
1526 #endif
1527
1528 if (check_identifier (for_command->name, 1) == 0)
1529 {
1530 if (posixly_correct && interactive_shell == 0)
1531 {
1532 last_command_exit_value = EX_USAGE;
1533 jump_to_top_level (EXITPROG);
1534 }
1535 return (EXECUTION_FAILURE);
1536 }
1537
1538 loop_level++;
1539 identifier = for_command->name->word;
1540
1541 list = releaser = expand_words_no_vars (for_command->map_list);
1542
1543 begin_unwind_frame ("for");
1544 add_unwind_protect (dispose_words, releaser);
1545
1546 #if 0
1547 if (lexical_scoping)
1548 {
1549 old_value = copy_variable (find_variable (identifier));
1550 if (old_value)
1551 add_unwind_protect (dispose_variable, old_value);
1552 }
1553 #endif
1554
1555 if (for_command->flags & CMD_IGNORE_RETURN)
1556 for_command->action->flags |= CMD_IGNORE_RETURN;
1557
1558 for (retval = EXECUTION_SUCCESS; list; list = list->next)
1559 {
1560 QUIT;
1561 this_command_name = (char *)NULL;
1562 v = bind_variable (identifier, list->word->word);
1563 if (readonly_p (v))
1564 {
1565 if (interactive_shell == 0 && posixly_correct)
1566 {
1567 last_command_exit_value = EXECUTION_FAILURE;
1568 jump_to_top_level (FORCE_EOF);
1569 }
1570 else
1571 {
1572 run_unwind_frame ("for");
1573 loop_level--;
1574 return (EXECUTION_FAILURE);
1575 }
1576 }
1577 retval = execute_command (for_command->action);
1578 REAP ();
1579 QUIT;
1580
1581 if (breaking)
1582 {
1583 breaking--;
1584 break;
1585 }
1586
1587 if (continuing)
1588 {
1589 continuing--;
1590 if (continuing)
1591 break;
1592 }
1593 }
1594
1595 loop_level--;
1596
1597 #if 0
1598 if (lexical_scoping)
1599 {
1600 if (!old_value)
1601 makunbound (identifier, shell_variables);
1602 else
1603 {
1604 SHELL_VAR *new_value;
1605
1606 new_value = bind_variable (identifier, value_cell(old_value));
1607 new_value->attributes = old_value->attributes;
1608 dispose_variable (old_value);
1609 }
1610 }
1611 #endif
1612
1613 dispose_words (releaser);
1614 discard_unwind_frame ("for");
1615 return (retval);
1616 }
1617
1618 #if defined (SELECT_COMMAND)
1619 static int LINES, COLS, tabsize;
1620
1621 #define RP_SPACE ") "
1622 #define RP_SPACE_LEN 2
1623
1624 /* XXX - does not handle numbers > 1000000 at all. */
1625 #define NUMBER_LEN(s) \
1626 ((s < 10) ? 1 \
1627 : ((s < 100) ? 2 \
1628 : ((s < 1000) ? 3 \
1629 : ((s < 10000) ? 4 \
1630 : ((s < 100000) ? 5 \
1631 : 6)))))
1632
1633 static int
1634 print_index_and_element (len, ind, list)
1635 int len, ind;
1636 WORD_LIST *list;
1637 {
1638 register WORD_LIST *l;
1639 register int i;
1640
1641 if (list == 0)
1642 return (0);
1643 for (i = ind, l = list; l && --i; l = l->next)
1644 ;
1645 fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
1646 return (STRLEN (l->word->word));
1647 }
1648
1649 static void
1650 indent (from, to)
1651 int from, to;
1652 {
1653 while (from < to)
1654 {
1655 if ((to / tabsize) > (from / tabsize))
1656 {
1657 putc ('\t', stderr);
1658 from += tabsize - from % tabsize;
1659 }
1660 else
1661 {
1662 putc (' ', stderr);
1663 from++;
1664 }
1665 }
1666 }
1667
1668 static void
1669 print_select_list (list, list_len, max_elem_len, indices_len)
1670 WORD_LIST *list;
1671 int list_len, max_elem_len, indices_len;
1672 {
1673 int ind, row, elem_len, pos, cols, rows;
1674 int first_column_indices_len, other_indices_len;
1675
1676 if (list == 0)
1677 {
1678 putc ('\n', stderr);
1679 return;
1680 }
1681
1682 cols = max_elem_len ? COLS / max_elem_len : 1;
1683 if (cols == 0)
1684 cols = 1;
1685 rows = list_len ? list_len / cols + (list_len % cols != 0) : 1;
1686 cols = list_len ? list_len / rows + (list_len % rows != 0) : 1;
1687
1688 if (rows == 1)
1689 {
1690 rows = cols;
1691 cols = 1;
1692 }
1693
1694 first_column_indices_len = NUMBER_LEN (rows);
1695 other_indices_len = indices_len;
1696
1697 for (row = 0; row < rows; row++)
1698 {
1699 ind = row;
1700 pos = 0;
1701 while (1)
1702 {
1703 indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
1704 elem_len = print_index_and_element (indices_len, ind + 1, list);
1705 elem_len += indices_len + RP_SPACE_LEN;
1706 ind += rows;
1707 if (ind >= list_len)
1708 break;
1709 indent (pos + elem_len, pos + max_elem_len);
1710 pos += max_elem_len;
1711 }
1712 putc ('\n', stderr);
1713 }
1714 }
1715
1716 /* Print the elements of LIST, one per line, preceded by an index from 1 to
1717 LIST_LEN. Then display PROMPT and wait for the user to enter a number.
1718 If the number is between 1 and LIST_LEN, return that selection. If EOF
1719 is read, return a null string. If a blank line is entered, the loop is
1720 executed again. */
1721 static char *
1722 select_query (list, list_len, prompt)
1723 WORD_LIST *list;
1724 int list_len;
1725 char *prompt;
1726 {
1727 int max_elem_len, indices_len, len, reply;
1728 WORD_LIST *l;
1729 char *repl_string, *t;
1730
1731 t = get_string_value ("LINES");
1732 LINES = (t && *t) ? atoi (t) : 24;
1733 t = get_string_value ("COLUMNS");
1734 COLS = (t && *t) ? atoi (t) : 80;
1735
1736 #if 0
1737 t = get_string_value ("TABSIZE");
1738 tabsize = (t && *t) ? atoi (t) : 8;
1739 if (tabsize <= 0)
1740 tabsize = 8;
1741 #else
1742 tabsize = 8;
1743 #endif
1744
1745 max_elem_len = 0;
1746 for (l = list; l; l = l->next)
1747 {
1748 len = STRLEN (l->word->word);
1749 if (len > max_elem_len)
1750 max_elem_len = len;
1751 }
1752 indices_len = NUMBER_LEN (list_len);
1753 max_elem_len += indices_len + RP_SPACE_LEN + 2;
1754
1755 while (1)
1756 {
1757 print_select_list (list, list_len, max_elem_len, indices_len);
1758 fprintf (stderr, "%s", prompt);
1759 fflush (stderr);
1760 QUIT;
1761
1762 if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
1763 {
1764 putchar ('\n');
1765 return ((char *)NULL);
1766 }
1767 repl_string = get_string_value ("REPLY");
1768 if (*repl_string == 0)
1769 continue;
1770 reply = atoi (repl_string);
1771 if (reply < 1 || reply > list_len)
1772 return "";
1773
1774 for (l = list; l && --reply; l = l->next)
1775 ;
1776 return (l->word->word);
1777 }
1778 }
1779
1780 /* Execute a SELECT command. The syntax is:
1781 SELECT word IN list DO command_list DONE
1782 Only `break' or `return' in command_list will terminate
1783 the command. */
1784 static int
1785 execute_select_command (select_command)
1786 SELECT_COM *select_command;
1787 {
1788 WORD_LIST *releaser, *list;
1789 SHELL_VAR *v;
1790 char *identifier, *ps3_prompt, *selection;
1791 int retval, list_len, return_val;
1792
1793 if (check_identifier (select_command->name, 1) == 0)
1794 return (EXECUTION_FAILURE);
1795
1796 loop_level++;
1797 identifier = select_command->name->word;
1798
1799 /* command and arithmetic substitution, parameter and variable expansion,
1800 word splitting, pathname expansion, and quote removal. */
1801 list = releaser = expand_words_no_vars (select_command->map_list);
1802 list_len = list_length (list);
1803 if (list == 0 || list_len == 0)
1804 {
1805 if (list)
1806 dispose_words (list);
1807 return (EXECUTION_SUCCESS);
1808 }
1809
1810 begin_unwind_frame ("select");
1811 add_unwind_protect (dispose_words, releaser);
1812
1813 if (select_command->flags & CMD_IGNORE_RETURN)
1814 select_command->action->flags |= CMD_IGNORE_RETURN;
1815
1816 retval = EXECUTION_SUCCESS;
1817
1818 unwind_protect_int (return_catch_flag);
1819 unwind_protect_jmp_buf (return_catch);
1820 return_catch_flag++;
1821
1822 while (1)
1823 {
1824 ps3_prompt = get_string_value ("PS3");
1825 if (ps3_prompt == 0)
1826 ps3_prompt = "#? ";
1827
1828 QUIT;
1829 selection = select_query (list, list_len, ps3_prompt);
1830 QUIT;
1831 if (selection == 0)
1832 break;
1833
1834 v = bind_variable (identifier, selection);
1835 if (readonly_p (v))
1836 {
1837 if (interactive_shell == 0 && posixly_correct)
1838 {
1839 last_command_exit_value = EXECUTION_FAILURE;
1840 jump_to_top_level (FORCE_EOF);
1841 }
1842 else
1843 {
1844 run_unwind_frame ("select");
1845 return (EXECUTION_FAILURE);
1846 }
1847 }
1848
1849 return_val = setjmp (return_catch);
1850
1851 if (return_val)
1852 {
1853 retval = return_catch_value;
1854 break;
1855 }
1856 else
1857 retval = execute_command (select_command->action);
1858
1859 REAP ();
1860 QUIT;
1861
1862 if (breaking)
1863 {
1864 breaking--;
1865 break;
1866 }
1867 }
1868
1869 loop_level--;
1870
1871 run_unwind_frame ("select");
1872 return (retval);
1873 }
1874 #endif /* SELECT_COMMAND */
1875
1876 /* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1877 The pattern_list is a linked list of pattern clauses; each clause contains
1878 some patterns to compare word_desc against, and an associated command to
1879 execute. */
1880 static int
1881 execute_case_command (case_command)
1882 CASE_COM *case_command;
1883 {
1884 register WORD_LIST *list;
1885 WORD_LIST *wlist, *es;
1886 PATTERN_LIST *clauses;
1887 char *word, *pattern;
1888 int retval, match, ignore_return;
1889
1890 /* Posix.2 specifies that the WORD is tilde expanded. */
1891 if (member ('~', case_command->word->word))
1892 {
1893 word = bash_tilde_expand (case_command->word->word);
1894 free (case_command->word->word);
1895 case_command->word->word = word;
1896 }
1897
1898 wlist = expand_word_no_split (case_command->word, 0);
1899 word = wlist ? string_list (wlist) : savestring ("");
1900 dispose_words (wlist);
1901
1902 retval = EXECUTION_SUCCESS;
1903 ignore_return = case_command->flags & CMD_IGNORE_RETURN;
1904
1905 begin_unwind_frame ("case");
1906 add_unwind_protect ((Function *)xfree, word);
1907
1908 #define EXIT_CASE() goto exit_case_command
1909
1910 for (clauses = case_command->clauses; clauses; clauses = clauses->next)
1911 {
1912 QUIT;
1913 for (list = clauses->patterns; list; list = list->next)
1914 {
1915 /* Posix.2 specifies to tilde expand each member of the pattern
1916 list. */
1917 if (member ('~', list->word->word))
1918 {
1919 pattern = bash_tilde_expand (list->word->word);
1920 free (list->word->word);
1921 list->word->word = pattern;
1922 }
1923
1924 es = expand_word_leave_quoted (list->word, 0);
1925
1926 if (es && es->word && es->word->word && *(es->word->word))
1927 pattern = quote_string_for_globbing (es->word->word, 1);
1928 else
1929 {
1930 pattern = xmalloc (1);
1931 pattern[0] = '\0';
1932 }
1933
1934 /* Since the pattern does not undergo quote removal (as per
1935 Posix.2, section 3.9.4.3), the fnmatch () call must be able
1936 to recognize backslashes as escape characters. */
1937 match = fnmatch (pattern, word, 0) != FNM_NOMATCH;
1938 free (pattern);
1939
1940 dispose_words (es);
1941
1942 if (match)
1943 {
1944 if (clauses->action && ignore_return)
1945 clauses->action->flags |= CMD_IGNORE_RETURN;
1946 retval = execute_command (clauses->action);
1947 EXIT_CASE ();
1948 }
1949
1950 QUIT;
1951 }
1952 }
1953
1954 exit_case_command:
1955 free (word);
1956 discard_unwind_frame ("case");
1957 return (retval);
1958 }
1959
1960 #define CMD_WHILE 0
1961 #define CMD_UNTIL 1
1962
1963 /* The WHILE command. Syntax: WHILE test DO action; DONE.
1964 Repeatedly execute action while executing test produces
1965 EXECUTION_SUCCESS. */
1966 static int
1967 execute_while_command (while_command)
1968 WHILE_COM *while_command;
1969 {
1970 return (execute_while_or_until (while_command, CMD_WHILE));
1971 }
1972
1973 /* UNTIL is just like WHILE except that the test result is negated. */
1974 static int
1975 execute_until_command (while_command)
1976 WHILE_COM *while_command;
1977 {
1978 return (execute_while_or_until (while_command, CMD_UNTIL));
1979 }
1980
1981 /* The body for both while and until. The only difference between the
1982 two is that the test value is treated differently. TYPE is
1983 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1984 be EXECUTION_SUCCESS if no commands in the body are executed, and
1985 the status of the last command executed in the body otherwise. */
1986 static int
1987 execute_while_or_until (while_command, type)
1988 WHILE_COM *while_command;
1989 int type;
1990 {
1991 int return_value, body_status;
1992
1993 body_status = EXECUTION_SUCCESS;
1994 loop_level++;
1995
1996 while_command->test->flags |= CMD_IGNORE_RETURN;
1997 if (while_command->flags & CMD_IGNORE_RETURN)
1998 while_command->action->flags |= CMD_IGNORE_RETURN;
1999
2000 while (1)
2001 {
2002 return_value = execute_command (while_command->test);
2003 REAP ();
2004
2005 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
2006 break;
2007 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
2008 break;
2009
2010 QUIT;
2011 body_status = execute_command (while_command->action);
2012 QUIT;
2013
2014 if (breaking)
2015 {
2016 breaking--;
2017 break;
2018 }
2019
2020 if (continuing)
2021 {
2022 continuing--;
2023 if (continuing)
2024 break;
2025 }
2026 }
2027 loop_level--;
2028
2029 return (body_status);
2030 }
2031
2032 /* IF test THEN command [ELSE command].
2033 IF also allows ELIF in the place of ELSE IF, but
2034 the parser makes *that* stupidity transparent. */
2035 static int
2036 execute_if_command (if_command)
2037 IF_COM *if_command;
2038 {
2039 int return_value;
2040
2041 if_command->test->flags |= CMD_IGNORE_RETURN;
2042 return_value = execute_command (if_command->test);
2043
2044 if (return_value == EXECUTION_SUCCESS)
2045 {
2046 QUIT;
2047
2048 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
2049 if_command->true_case->flags |= CMD_IGNORE_RETURN;
2050
2051 return (execute_command (if_command->true_case));
2052 }
2053 else
2054 {
2055 QUIT;
2056
2057 if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
2058 if_command->false_case->flags |= CMD_IGNORE_RETURN;
2059
2060 return (execute_command (if_command->false_case));
2061 }
2062 }
2063
2064 static void
2065 bind_lastarg (arg)
2066 char *arg;
2067 {
2068 SHELL_VAR *var;
2069
2070 if (arg == 0)
2071 arg = "";
2072 var = bind_variable ("_", arg);
2073 var->attributes &= ~att_exported;
2074 }
2075
2076 /* Execute a null command. Fork a subshell if the command uses pipes or is
2077 to be run asynchronously. This handles all the side effects that are
2078 supposed to take place. */
2079 static int
2080 execute_null_command (redirects, pipe_in, pipe_out, async, old_last_command_subst_pid)
2081 REDIRECT *redirects;
2082 int pipe_in, pipe_out, async, old_last_command_subst_pid;
2083 {
2084 if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
2085 {
2086 /* We have a null command, but we really want a subshell to take
2087 care of it. Just fork, do piping and redirections, and exit. */
2088 if (make_child ((char *)NULL, async) == 0)
2089 {
2090 /* Cancel traps, in trap.c. */
2091 restore_original_signals (); /* XXX */
2092
2093 do_piping (pipe_in, pipe_out);
2094
2095 subshell_environment = SUBSHELL_ASYNC;
2096
2097 if (do_redirections (redirects, 1, 0, 0) == 0)
2098 exit (EXECUTION_SUCCESS);
2099 else
2100 exit (EXECUTION_FAILURE);
2101 }
2102 else
2103 {
2104 close_pipes (pipe_in, pipe_out);
2105 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2106 unlink_fifo_list ();
2107 #endif
2108 return (EXECUTION_SUCCESS);
2109 }
2110 }
2111 else
2112 {
2113 /* Even if there aren't any command names, pretend to do the
2114 redirections that are specified. The user expects the side
2115 effects to take place. If the redirections fail, then return
2116 failure. Otherwise, if a command substitution took place while
2117 expanding the command or a redirection, return the value of that
2118 substitution. Otherwise, return EXECUTION_SUCCESS. */
2119
2120 if (do_redirections (redirects, 0, 0, 0) != 0)
2121 return (EXECUTION_FAILURE);
2122 else if (old_last_command_subst_pid != last_command_subst_pid)
2123 return (last_command_exit_value);
2124 else
2125 return (EXECUTION_SUCCESS);
2126 }
2127 }
2128
2129 /* This is a hack to suppress word splitting for assignment statements
2130 given as arguments to builtins with the ASSIGNMENT_BUILTIN flag set. */
2131 static void
2132 fix_assignment_words (words)
2133 WORD_LIST *words;
2134 {
2135 WORD_LIST *w;
2136 struct builtin *b;
2137
2138 if (words == 0)
2139 return;
2140
2141 b = builtin_address_internal (words->word->word);
2142 if (b == 0 || (b->flags & ASSIGNMENT_BUILTIN) == 0)
2143 return;
2144
2145 for (w = words; w; w = w->next)
2146 if (w->word->flags & W_ASSIGNMENT)
2147 w->word->flags |= W_NOSPLIT;
2148 }
2149
2150 /* The meaty part of all the executions. We have to start hacking the
2151 real execution of commands here. Fork a process, set things up,
2152 execute the command. */
2153 static int
2154 execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
2155 SIMPLE_COM *simple_command;
2156 int pipe_in, pipe_out, async;
2157 struct fd_bitmap *fds_to_close;
2158 {
2159 WORD_LIST *words, *lastword;
2160 char *command_line, *lastarg, *temp;
2161 int first_word_quoted, result, builtin_is_special;
2162 pid_t old_last_command_subst_pid;
2163 Function *builtin;
2164 SHELL_VAR *func;
2165
2166 result = EXECUTION_SUCCESS;
2167 special_builtin_failed = builtin_is_special = 0;
2168
2169 /* If we're in a function, update the line number information. */
2170 if (variable_context)
2171 line_number = simple_command->line - function_line_number;
2172
2173 /* Remember what this command line looks like at invocation. */
2174 command_string_index = 0;
2175 print_simple_command (simple_command);
2176 command_line = xmalloc (1 + strlen (the_printed_command));
2177 strcpy (command_line, the_printed_command); /* XXX memory leak on errors */
2178
2179 first_word_quoted =
2180 simple_command->words ? (simple_command->words->word->flags & W_QUOTED): 0;
2181
2182 old_last_command_subst_pid = last_command_subst_pid;
2183
2184 /* If we are re-running this as the result of executing the `command'
2185 builtin, do not expand the command words a second time. */
2186 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
2187 {
2188 current_fds_to_close = fds_to_close;
2189 fix_assignment_words (simple_command->words);
2190 words = expand_words (simple_command->words);
2191 current_fds_to_close = (struct fd_bitmap *)NULL;
2192 }
2193 else
2194 words = copy_word_list (simple_command->words);
2195
2196 /* It is possible for WORDS not to have anything left in it.
2197 Perhaps all the words consisted of `$foo', and there was
2198 no variable `$foo'. */
2199 if (words == 0)
2200 {
2201 result = execute_null_command (simple_command->redirects,
2202 pipe_in, pipe_out, async,
2203 old_last_command_subst_pid);
2204 FREE (command_line);
2205 bind_lastarg ((char *)NULL);
2206 return (result);
2207 }
2208
2209 lastarg = (char *)NULL;
2210
2211 begin_unwind_frame ("simple-command");
2212
2213 if (echo_command_at_execute)
2214 xtrace_print_word_list (words);
2215
2216 builtin = (Function *)NULL;
2217 func = (SHELL_VAR *)NULL;
2218 if ((simple_command->flags & CMD_NO_FUNCTIONS) == 0)
2219 {
2220 /* Posix.2 says special builtins are found before functions. We
2221 don't set builtin_is_special anywhere other than here, because
2222 this path is followed only when the `command' builtin is *not*
2223 being used, and we don't want to exit the shell if a special
2224 builtin executed with `command builtin' fails. `command' is not
2225 a special builtin. */
2226 if (posixly_correct)
2227 {
2228 builtin = find_special_builtin (words->word->word);
2229 if (builtin)
2230 builtin_is_special = 1;
2231 }
2232 if (builtin == 0)
2233 func = find_function (words->word->word);
2234 }
2235
2236 add_unwind_protect (dispose_words, words);
2237 QUIT;
2238
2239 /* Bind the last word in this command to "$_" after execution. */
2240 for (lastword = words; lastword->next; lastword = lastword->next)
2241 ;
2242 lastarg = lastword->word->word;
2243
2244 #if defined (JOB_CONTROL)
2245 /* Is this command a job control related thing? */
2246 if (words->word->word[0] == '%')
2247 {
2248 this_command_name = async ? "bg" : "fg";
2249 last_shell_builtin = this_shell_builtin;
2250 this_shell_builtin = builtin_address (this_command_name);
2251 result = (*this_shell_builtin) (words);
2252 goto return_result;
2253 }
2254
2255 /* One other possiblilty. The user may want to resume an existing job.
2256 If they do, find out whether this word is a candidate for a running
2257 job. */
2258 if (job_control && async == 0 &&
2259 !first_word_quoted &&
2260 !words->next &&
2261 words->word->word[0] &&
2262 !simple_command->redirects &&
2263 pipe_in == NO_PIPE &&
2264 pipe_out == NO_PIPE &&
2265 (temp = get_string_value ("auto_resume")))
2266 {
2267 char *word;
2268 register int i;
2269 int wl, cl, exact, substring, match, started_status;
2270 register PROCESS *p;
2271
2272 word = words->word->word;
2273 exact = STREQ (temp, "exact");
2274 substring = STREQ (temp, "substring");
2275 wl = strlen (word);
2276 for (i = job_slots - 1; i > -1; i--)
2277 {
2278 if (jobs[i] == 0 || (JOBSTATE (i) != JSTOPPED))
2279 continue;
2280
2281 p = jobs[i]->pipe;
2282 do
2283 {
2284 if (exact)
2285 {
2286 cl = strlen (p->command);
2287 match = STREQN (p->command, word, cl);
2288 }
2289 else if (substring)
2290 match = strindex (p->command, word) != (char *)0;
2291 else
2292 match = STREQN (p->command, word, wl);
2293
2294 if (match == 0)
2295 {
2296 p = p->next;
2297 continue;
2298 }
2299
2300 run_unwind_frame ("simple-command");
2301 this_command_name = "fg";
2302 last_shell_builtin = this_shell_builtin;
2303 this_shell_builtin = builtin_address ("fg");
2304
2305 started_status = start_job (i, 1);
2306 return ((started_status < 0) ? EXECUTION_FAILURE : started_status);
2307 }
2308 while (p != jobs[i]->pipe);
2309 }
2310 }
2311 #endif /* JOB_CONTROL */
2312
2313 /* Remember the name of this command globally. */
2314 this_command_name = words->word->word;
2315
2316 QUIT;
2317
2318 /* This command could be a shell builtin or a user-defined function.
2319 We have already found special builtins by this time, so we do not
2320 set builtin_is_special. If this is a function or builtin, and we
2321 have pipes, then fork a subshell in here. Otherwise, just execute
2322 the command directly. */
2323 if (func == 0 && builtin == 0)
2324 builtin = find_shell_builtin (this_command_name);
2325
2326 last_shell_builtin = this_shell_builtin;
2327 this_shell_builtin = builtin;
2328
2329 if (builtin || func)
2330 {
2331 if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
2332 {
2333 if (make_child (command_line, async) == 0)
2334 {
2335 /* reset_terminating_signals (); */ /* XXX */
2336 /* Cancel traps, in trap.c. */
2337 restore_original_signals ();
2338
2339 if (async)
2340 {
2341 if ((simple_command->flags & CMD_STDIN_REDIR) &&
2342 pipe_in == NO_PIPE &&
2343 (stdin_redirects (simple_command->redirects) == 0))
2344 async_redirect_stdin ();
2345 setup_async_signals ();
2346 }
2347
2348 execute_subshell_builtin_or_function
2349 (words, simple_command->redirects, builtin, func,
2350 pipe_in, pipe_out, async, fds_to_close,
2351 simple_command->flags);
2352 }
2353 else
2354 {
2355 close_pipes (pipe_in, pipe_out);
2356 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2357 unlink_fifo_list ();
2358 #endif
2359 command_line = (char *)NULL; /* don't free this. */
2360 goto return_result;
2361 }
2362 }
2363 else
2364 {
2365 result = execute_builtin_or_function
2366 (words, builtin, func, simple_command->redirects, fds_to_close,
2367 simple_command->flags);
2368 if (builtin)
2369 {
2370 if (result > EX_SHERRBASE)
2371 {
2372 result = builtin_status (result);
2373 if (builtin_is_special)
2374 special_builtin_failed = 1;
2375 }
2376 /* In POSIX mode, if there are assignment statements preceding
2377 a special builtin, they persist after the builtin
2378 completes. */
2379 if (posixly_correct && builtin_is_special && temporary_env)
2380 merge_temporary_env ();
2381 }
2382 else /* function */
2383 {
2384 if (result == EX_USAGE)
2385 result = EX_BADUSAGE;
2386 else if (result > EX_SHERRBASE)
2387 result = EXECUTION_FAILURE;
2388 }
2389
2390 goto return_result;
2391 }
2392 }
2393
2394 execute_disk_command (words, simple_command->redirects, command_line,
2395 pipe_in, pipe_out, async, fds_to_close,
2396 simple_command->flags);
2397
2398 return_result:
2399 bind_lastarg (lastarg);
2400 FREE (command_line);
2401 run_unwind_frame ("simple-command");
2402 return (result);
2403 }
2404
2405 /* Translate the special builtin exit statuses. We don't really need a
2406 function for this; it's a placeholder for future work. */
2407 static int
2408 builtin_status (result)
2409 int result;
2410 {
2411 int r;
2412
2413 switch (result)
2414 {
2415 case EX_USAGE:
2416 r = EX_BADUSAGE;
2417 break;
2418 case EX_REDIRFAIL:
2419 case EX_BADSYNTAX:
2420 case EX_BADASSIGN:
2421 case EX_EXPFAIL:
2422 r = EXECUTION_FAILURE;
2423 break;
2424 default:
2425 r = EXECUTION_SUCCESS;
2426 break;
2427 }
2428 return (r);
2429 }
2430
2431 static int
2432 execute_builtin (builtin, words, flags, subshell)
2433 Function *builtin;
2434 WORD_LIST *words;
2435 int flags, subshell;
2436 {
2437 int old_e_flag, result, eval_unwind;
2438
2439 old_e_flag = exit_immediately_on_error;
2440 /* The eval builtin calls parse_and_execute, which does not know about
2441 the setting of flags, and always calls the execution functions with
2442 flags that will exit the shell on an error if -e is set. If the
2443 eval builtin is being called, and we're supposed to ignore the exit
2444 value of the command, we turn the -e flag off ourselves, then
2445 restore it when the command completes. */
2446 if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
2447 {
2448 begin_unwind_frame ("eval_builtin");
2449 unwind_protect_int (exit_immediately_on_error);
2450 exit_immediately_on_error = 0;
2451 eval_unwind = 1;
2452 }
2453 else
2454 eval_unwind = 0;
2455
2456 /* The temporary environment for a builtin is supposed to apply to
2457 all commands executed by that builtin. Currently, this is a
2458 problem only with the `source' and `eval' builtins. */
2459 if (builtin == source_builtin || builtin == eval_builtin)
2460 {
2461 if (subshell == 0)
2462 begin_unwind_frame ("builtin_env");
2463
2464 if (temporary_env)
2465 {
2466 builtin_env = copy_array (temporary_env);
2467 if (subshell == 0)
2468 add_unwind_protect (dispose_builtin_env, (char *)NULL);
2469 dispose_used_env_vars ();
2470 }
2471 #if 0
2472 else
2473 builtin_env = (char **)NULL;
2474 #endif
2475 }
2476
2477 result = ((*builtin) (words->next));
2478
2479 if (subshell == 0 && (builtin == source_builtin || builtin == eval_builtin))
2480 {
2481 /* In POSIX mode, if any variable assignments precede the `.' or
2482 `eval' builtin, they persist after the builtin completes, since `.'
2483 and `eval' are special builtins. */
2484 if (posixly_correct && builtin_env)
2485 merge_builtin_env ();
2486 dispose_builtin_env ();
2487 discard_unwind_frame ("builtin_env");
2488 }
2489
2490 if (eval_unwind)
2491 {
2492 exit_immediately_on_error += old_e_flag;
2493 discard_unwind_frame ("eval_builtin");
2494 }
2495
2496 return (result);
2497 }
2498
2499 static int
2500 execute_function (var, words, flags, fds_to_close, async, subshell)
2501 SHELL_VAR *var;
2502 WORD_LIST *words;
2503 int flags, subshell, async;
2504 struct fd_bitmap *fds_to_close;
2505 {
2506 int return_val, result;
2507 COMMAND *tc, *fc;
2508 char *debug_trap;
2509
2510 tc = (COMMAND *)copy_command (function_cell (var));
2511 if (tc && (flags & CMD_IGNORE_RETURN))
2512 tc->flags |= CMD_IGNORE_RETURN;
2513
2514 if (subshell == 0)
2515 {
2516 begin_unwind_frame ("function_calling");
2517 push_context ();
2518 add_unwind_protect (pop_context, (char *)NULL);
2519 unwind_protect_int (line_number);
2520 unwind_protect_int (return_catch_flag);
2521 unwind_protect_jmp_buf (return_catch);
2522 add_unwind_protect (dispose_command, (char *)tc);
2523 unwind_protect_int (loop_level);
2524 }
2525
2526 debug_trap = (signal_is_trapped (DEBUG_TRAP) && signal_is_ignored (DEBUG_TRAP) == 0)
2527 ? trap_list[DEBUG_TRAP]
2528 : (char *)NULL;
2529 if (debug_trap)
2530 {
2531 if (subshell == 0)
2532 {
2533 debug_trap = savestring (debug_trap);
2534 add_unwind_protect (set_debug_trap, debug_trap);
2535 /* XXX - small memory leak here -- hard to fix */
2536 }
2537 restore_default_signal (DEBUG_TRAP);
2538 }
2539
2540 /* The temporary environment for a function is supposed to apply to
2541 all commands executed within the function body. */
2542 if (temporary_env)
2543 {
2544 function_env = copy_array (temporary_env);
2545 if (subshell == 0)
2546 add_unwind_protect (dispose_function_env, (char *)NULL);
2547 dispose_used_env_vars ();
2548 }
2549 #if 0
2550 else
2551 function_env = (char **)NULL;
2552 #endif
2553
2554 remember_args (words->next, 1);
2555
2556 /* Number of the line on which the function body starts. */
2557 line_number = function_line_number = tc->line;
2558
2559 if (subshell)
2560 {
2561 #if defined (JOB_CONTROL)
2562 stop_pipeline (async, (COMMAND *)NULL);
2563 #endif
2564 fc = (tc->type == cm_group) ? tc->value.Group->command : tc;
2565
2566 if (fc && (flags & CMD_IGNORE_RETURN))
2567 fc->flags |= CMD_IGNORE_RETURN;
2568
2569 variable_context++;
2570 }
2571 else
2572 fc = tc;
2573
2574 return_catch_flag++;
2575 return_val = setjmp (return_catch);
2576
2577 if (return_val)
2578 result = return_catch_value;
2579 else
2580 result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
2581
2582 if (subshell == 0)
2583 run_unwind_frame ("function_calling");
2584
2585 return (result);
2586 }
2587
2588 /* Execute a shell builtin or function in a subshell environment. This
2589 routine does not return; it only calls exit(). If BUILTIN is non-null,
2590 it points to a function to call to execute a shell builtin; otherwise
2591 VAR points at the body of a function to execute. WORDS is the arguments
2592 to the command, REDIRECTS specifies redirections to perform before the
2593 command is executed. */
2594 static void
2595 execute_subshell_builtin_or_function (words, redirects, builtin, var,
2596 pipe_in, pipe_out, async, fds_to_close,
2597 flags)
2598 WORD_LIST *words;
2599 REDIRECT *redirects;
2600 Function *builtin;
2601 SHELL_VAR *var;
2602 int pipe_in, pipe_out, async;
2603 struct fd_bitmap *fds_to_close;
2604 int flags;
2605 {
2606 int result, r;
2607
2608 /* A subshell is neither a login shell nor interactive. */
2609 login_shell = interactive = 0;
2610
2611 subshell_environment = SUBSHELL_ASYNC;
2612
2613 maybe_make_export_env (); /* XXX - is this needed? */
2614
2615 #if defined (JOB_CONTROL)
2616 /* Eradicate all traces of job control after we fork the subshell, so
2617 all jobs begun by this subshell are in the same process group as
2618 the shell itself. */
2619
2620 /* Allow the output of `jobs' to be piped. */
2621 if (builtin == jobs_builtin && !async &&
2622 (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
2623 kill_current_pipeline ();
2624 else
2625 without_job_control ();
2626
2627 set_sigchld_handler ();
2628 #endif /* JOB_CONTROL */
2629
2630 set_sigint_handler ();
2631
2632 do_piping (pipe_in, pipe_out);
2633
2634 if (fds_to_close)
2635 close_fd_bitmap (fds_to_close);
2636
2637 if (do_redirections (redirects, 1, 0, 0) != 0)
2638 exit (EXECUTION_FAILURE);
2639
2640 if (builtin)
2641 {
2642 /* Give builtins a place to jump back to on failure,
2643 so we don't go back up to main(). */
2644 result = setjmp (top_level);
2645
2646 if (result == EXITPROG)
2647 exit (last_command_exit_value);
2648 else if (result)
2649 exit (EXECUTION_FAILURE);
2650 else
2651 {
2652 r = execute_builtin (builtin, words, flags, 1);
2653 if (r == EX_USAGE)
2654 r = EX_BADUSAGE;
2655 exit (r);
2656 }
2657 }
2658 else
2659 exit (execute_function (var, words, flags, fds_to_close, async, 1));
2660 }
2661
2662 /* Execute a builtin or function in the current shell context. If BUILTIN
2663 is non-null, it is the builtin command to execute, otherwise VAR points
2664 to the body of a function. WORDS are the command's arguments, REDIRECTS
2665 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
2666 file descriptors to close.
2667
2668 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
2669 not undone before this function returns. */
2670 static int
2671 execute_builtin_or_function (words, builtin, var, redirects,
2672 fds_to_close, flags)
2673 WORD_LIST *words;
2674 Function *builtin;
2675 SHELL_VAR *var;
2676 REDIRECT *redirects;
2677 struct fd_bitmap *fds_to_close;
2678 int flags;
2679 {
2680 int result;
2681 REDIRECT *saved_undo_list;
2682
2683 if (do_redirections (redirects, 1, 1, 0) != 0)
2684 {
2685 cleanup_redirects (redirection_undo_list);
2686 redirection_undo_list = (REDIRECT *)NULL;
2687 dispose_exec_redirects ();
2688 return (EX_REDIRFAIL); /* was EXECUTION_FAILURE */
2689 }
2690
2691 saved_undo_list = redirection_undo_list;
2692
2693 /* Calling the "exec" builtin changes redirections forever. */
2694 if (builtin == exec_builtin)
2695 {
2696 dispose_redirects (saved_undo_list);
2697 saved_undo_list = exec_redirection_undo_list;
2698 exec_redirection_undo_list = (REDIRECT *)NULL;
2699 }
2700 else
2701 dispose_exec_redirects ();
2702
2703 if (saved_undo_list)
2704 {
2705 begin_unwind_frame ("saved redirects");
2706 add_unwind_protect (cleanup_redirects, (char *)saved_undo_list);
2707 }
2708
2709 redirection_undo_list = (REDIRECT *)NULL;
2710
2711 if (builtin)
2712 result = execute_builtin (builtin, words, flags, 0);
2713 else
2714 result = execute_function (var, words, flags, fds_to_close, 0, 0);
2715
2716 if (saved_undo_list)
2717 {
2718 redirection_undo_list = saved_undo_list;
2719 discard_unwind_frame ("saved redirects");
2720 }
2721
2722 if (redirection_undo_list)
2723 {
2724 cleanup_redirects (redirection_undo_list);
2725 redirection_undo_list = (REDIRECT *)NULL;
2726 }
2727
2728 return (result);
2729 }
2730
2731 void
2732 setup_async_signals ()
2733 {
2734 #if defined (JOB_CONTROL)
2735 if (job_control == 0)
2736 #endif
2737 {
2738 set_signal_handler (SIGINT, SIG_IGN);
2739 set_signal_ignored (SIGINT);
2740 set_signal_handler (SIGQUIT, SIG_IGN);
2741 set_signal_ignored (SIGQUIT);
2742 }
2743 }
2744
2745 /* Execute a simple command that is hopefully defined in a disk file
2746 somewhere.
2747
2748 1) fork ()
2749 2) connect pipes
2750 3) look up the command
2751 4) do redirections
2752 5) execve ()
2753 6) If the execve failed, see if the file has executable mode set.
2754 If so, and it isn't a directory, then execute its contents as
2755 a shell script.
2756
2757 Note that the filename hashing stuff has to take place up here,
2758 in the parent. This is probably why the Bourne style shells
2759 don't handle it, since that would require them to go through
2760 this gnarly hair, for no good reason. */
2761 static void
2762 execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
2763 async, fds_to_close, cmdflags)
2764 WORD_LIST *words;
2765 REDIRECT *redirects;
2766 char *command_line;
2767 int pipe_in, pipe_out, async;
2768 struct fd_bitmap *fds_to_close;
2769 int cmdflags;
2770 {
2771 char *pathname, *command, **args;
2772 int nofork;
2773 int pid;
2774
2775 nofork = (cmdflags & CMD_NO_FORK); /* Don't fork, just exec, if no pipes */
2776 pathname = words->word->word;
2777
2778 #if defined (RESTRICTED_SHELL)
2779 if (restricted && strchr (pathname, '/'))
2780 {
2781 internal_error ("%s: restricted: cannot specify `/' in command names",
2782 pathname);
2783 last_command_exit_value = EXECUTION_FAILURE;
2784 return;
2785 }
2786 #endif /* RESTRICTED_SHELL */
2787
2788 command = search_for_command (pathname);
2789
2790 if (command)
2791 {
2792 maybe_make_export_env ();
2793 put_command_name_into_env (command);
2794 }
2795
2796 /* We have to make the child before we check for the non-existance
2797 of COMMAND, since we want the error messages to be redirected. */
2798 /* If we can get away without forking and there are no pipes to deal with,
2799 don't bother to fork, just directly exec the command. */
2800 if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
2801 pid = 0;
2802 else
2803 pid = make_child (savestring (command_line), async);
2804
2805 if (pid == 0)
2806 {
2807 int old_interactive;
2808
2809 #if 0
2810 /* This has been disabled for the time being. */
2811 #if !defined (ARG_MAX) || ARG_MAX >= 10240
2812 if (posixly_correct == 0)
2813 put_gnu_argv_flags_into_env ((int)getpid (), glob_argv_flags);
2814 #endif
2815 #endif
2816
2817 /* Cancel traps, in trap.c. */
2818 restore_original_signals ();
2819
2820 /* restore_original_signals may have undone the work done
2821 by make_child to ensure that SIGINT and SIGQUIT are ignored
2822 in asynchronous children. */
2823 if (async)
2824 {
2825 if ((cmdflags & CMD_STDIN_REDIR) &&
2826 pipe_in == NO_PIPE &&
2827 (stdin_redirects (redirects) == 0))
2828 async_redirect_stdin ();
2829 setup_async_signals ();
2830 }
2831
2832 do_piping (pipe_in, pipe_out);
2833
2834 if (async)
2835 {
2836 old_interactive = interactive;
2837 interactive = 0;
2838 }
2839
2840 subshell_environment = SUBSHELL_FORK;
2841
2842 /* This functionality is now provided by close-on-exec of the
2843 file descriptors manipulated by redirection and piping.
2844 Some file descriptors still need to be closed in all children
2845 because of the way bash does pipes; fds_to_close is a
2846 bitmap of all such file descriptors. */
2847 if (fds_to_close)
2848 close_fd_bitmap (fds_to_close);
2849
2850 if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
2851 {
2852 #if defined (PROCESS_SUBSTITUTION)
2853 /* Try to remove named pipes that may have been created as the
2854 result of redirections. */
2855 unlink_fifo_list ();
2856 #endif /* PROCESS_SUBSTITUTION */
2857 exit (EXECUTION_FAILURE);
2858 }
2859
2860 if (async)
2861 interactive = old_interactive;
2862
2863 if (command == 0)
2864 {
2865 internal_error ("%s: command not found", pathname);
2866 exit (EX_NOTFOUND); /* Posix.2 says the exit status is 127 */
2867 }
2868
2869 /* Execve expects the command name to be in args[0]. So we
2870 leave it there, in the same format that the user used to
2871 type it in. */
2872 args = word_list_to_argv (words, 0, 0, (int *)NULL);
2873 exit (shell_execve (command, args, export_env));
2874 }
2875 else
2876 {
2877 /* Make sure that the pipes are closed in the parent. */
2878 close_pipes (pipe_in, pipe_out);
2879 #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
2880 unlink_fifo_list ();
2881 #endif
2882 FREE (command);
2883 }
2884 }
2885
2886 #if !defined (HAVE_HASH_BANG_EXEC)
2887 /* If the operating system on which we're running does not handle
2888 the #! executable format, then help out. SAMPLE is the text read
2889 from the file, SAMPLE_LEN characters. COMMAND is the name of
2890 the script; it and ARGS, the arguments given by the user, will
2891 become arguments to the specified interpreter. ENV is the environment
2892 to pass to the interpreter.
2893
2894 The word immediately following the #! is the interpreter to execute.
2895 A single argument to the interpreter is allowed. */
2896 static int
2897 execute_shell_script (sample, sample_len, command, args, env)
2898 unsigned char *sample;
2899 int sample_len;
2900 char *command;
2901 char **args, **env;
2902 {
2903 register int i;
2904 char *execname, *firstarg;
2905 int start, size_increment, larry;
2906
2907 /* Find the name of the interpreter to exec. */
2908 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
2909 ;
2910
2911 for (start = i;
2912 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2913 i++)
2914 ;
2915
2916 larry = i - start;
2917 execname = xmalloc (1 + larry);
2918 strncpy (execname, (char *)(sample + start), larry);
2919 execname[larry] = '\0';
2920 size_increment = 1;
2921
2922 /* Now the argument, if any. */
2923 firstarg = (char *)NULL;
2924 for (start = i;
2925 whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2926 i++)
2927 ;
2928
2929 /* If there is more text on the line, then it is an argument for the
2930 interpreter. */
2931 if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
2932 {
2933 for (start = i;
2934 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
2935 i++)
2936 ;
2937 larry = i - start;
2938 firstarg = xmalloc (1 + larry);
2939 strncpy (firstarg, (char *)(sample + start), larry);
2940 firstarg[larry] = '\0';
2941
2942 size_increment = 2;
2943 }
2944
2945 larry = array_len (args) + size_increment;
2946
2947 args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
2948
2949 for (i = larry - 1; i; i--)
2950 args[i] = args[i - size_increment];
2951
2952 args[0] = execname;
2953 if (firstarg)
2954 {
2955 args[1] = firstarg;
2956 args[2] = command;
2957 }
2958 else
2959 args[1] = command;
2960
2961 args[larry] = (char *)NULL;
2962
2963 return (shell_execve (execname, args, env));
2964 }
2965 #endif /* !HAVE_HASH_BANG_EXEC */
2966
2967 static void
2968 initialize_subshell ()
2969 {
2970 #if defined (ALIAS)
2971 /* Forget about any aliases that we knew of. We are in a subshell. */
2972 delete_all_aliases ();
2973 #endif /* ALIAS */
2974
2975 #if defined (HISTORY)
2976 /* Forget about the history lines we have read. This is a non-interactive
2977 subshell. */
2978 history_lines_this_session = 0;
2979 #endif
2980
2981 #if defined (JOB_CONTROL)
2982 /* Forget about the way job control was working. We are in a subshell. */
2983 without_job_control ();
2984 set_sigchld_handler ();
2985 #endif /* JOB_CONTROL */
2986
2987 /* Reset the values of the shell flags and options. */
2988 reset_shell_flags ();
2989 reset_shell_options ();
2990 reset_shopt_options ();
2991
2992 /* If we're not interactive, close the file descriptor from which we're
2993 reading the current shell script. */
2994 #if defined (BUFFERED_INPUT)
2995 if (interactive_shell == 0 && default_buffered_input >= 0)
2996 {
2997 close_buffered_fd (default_buffered_input);
2998 default_buffered_input = bash_input.location.buffered_fd = -1;
2999 }
3000 #else
3001 if (interactive_shell == 0 && default_input)
3002 {
3003 fclose (default_input);
3004 default_input = (FILE *)NULL;
3005 }
3006 #endif
3007 }
3008
3009 #if defined (HAVE_SETOSTYPE) && defined (_POSIX_SOURCE)
3010 # define SETOSTYPE(x) __setostype(x)
3011 #else
3012 # define SETOSTYPE(x)
3013 #endif
3014
3015 /* Call execve (), handling interpreting shell scripts, and handling
3016 exec failures. */
3017 int
3018 shell_execve (command, args, env)
3019 char *command;
3020 char **args, **env;
3021 {
3022 struct stat finfo;
3023 int larray, i, fd;
3024
3025 SETOSTYPE (0); /* Some systems use for USG/POSIX semantics */
3026 execve (command, args, env);
3027 SETOSTYPE (1);
3028
3029 /* If we get to this point, then start checking out the file.
3030 Maybe it is something we can hack ourselves. */
3031 if (errno != ENOEXEC)
3032 {
3033 i = errno;
3034 if ((stat (command, &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
3035 internal_error ("%s: is a directory", command);
3036 else
3037 {
3038 errno = i;
3039 file_error (command);
3040 }
3041 return ((i == ENOENT) ? EX_NOTFOUND : EX_NOEXEC); /* XXX Posix.2 says that exit status is 126 */
3042 }
3043
3044 /* This file is executable.
3045 If it begins with #!, then help out people with losing operating
3046 systems. Otherwise, check to see if it is a binary file by seeing
3047 if the first line (or up to 80 characters) are in the ASCII set.
3048 Execute the contents as shell commands. */
3049 fd = open (command, O_RDONLY);
3050 if (fd >= 0)
3051 {
3052 unsigned char sample[80];
3053 int sample_len;
3054
3055 sample_len = read (fd, (char *)sample, 80);
3056 close (fd);
3057
3058 if (sample_len == 0)
3059 return (EXECUTION_SUCCESS);
3060
3061 /* Is this supposed to be an executable script?
3062 If so, the format of the line is "#! interpreter [argument]".
3063 A single argument is allowed. The BSD kernel restricts
3064 the length of the entire line to 32 characters (32 bytes
3065 being the size of the BSD exec header), but we allow 80
3066 characters. */
3067 if (sample_len > 0)
3068 {
3069 #if !defined (HAVE_HASH_BANG_EXEC)
3070 if (sample[0] == '#' && sample[1] == '!')
3071 return (execute_shell_script (sample, sample_len, command, args, env));
3072 else
3073 #endif
3074 if (check_binary_file (sample, sample_len))
3075 {
3076 internal_error ("%s: cannot execute binary file", command);
3077 return (EX_BINARY_FILE);
3078 }
3079 }
3080 }
3081
3082 initialize_subshell ();
3083
3084 set_sigint_handler ();
3085
3086 /* Insert the name of this shell into the argument list. */
3087 larray = array_len (args) + 1;
3088 args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
3089
3090 for (i = larray - 1; i; i--)
3091 args[i] = args[i - 1];
3092
3093 args[0] = shell_name;
3094 args[1] = command;
3095 args[larray] = (char *)NULL;
3096
3097 if (args[0][0] == '-')
3098 args[0]++;
3099
3100 #if defined (RESTRICTED_SHELL)
3101 if (restricted)
3102 change_flag ('r', FLAG_OFF);
3103 #endif
3104
3105 if (subshell_argv)
3106 {
3107 /* Can't free subshell_argv[0]; that is shell_name. */
3108 for (i = 1; i < subshell_argc; i++)
3109 free (subshell_argv[i]);
3110 free (subshell_argv);
3111 }
3112
3113 dispose_command (currently_executing_command); /* XXX */
3114 currently_executing_command = (COMMAND *)NULL;
3115
3116 subshell_argc = larray;
3117 subshell_argv = args;
3118 subshell_envp = env;
3119
3120 unbind_args (); /* remove the positional parameters */
3121
3122 longjmp (subshell_top_level, 1);
3123 }
3124
3125 static int
3126 execute_intern_function (name, function)
3127 WORD_DESC *name;
3128 COMMAND *function;
3129 {
3130 SHELL_VAR *var;
3131
3132 if (check_identifier (name, posixly_correct) == 0)
3133 {
3134 if (posixly_correct && interactive_shell == 0)
3135 {
3136 last_command_exit_value = EX_USAGE;
3137 jump_to_top_level (EXITPROG);
3138 }
3139 return (EXECUTION_FAILURE);
3140 }
3141
3142 var = find_function (name->word);
3143 if (var && readonly_p (var))
3144 {
3145 internal_error ("%s: readonly function", var->name);
3146 return (EXECUTION_FAILURE);
3147 }
3148
3149 bind_function (name->word, function);
3150 return (EXECUTION_SUCCESS);
3151 }
3152
3153 #if defined (INCLUDE_UNUSED)
3154 #if defined (PROCESS_SUBSTITUTION)
3155 void
3156 close_all_files ()
3157 {
3158 register int i, fd_table_size;
3159
3160 fd_table_size = getdtablesize ();
3161 if (fd_table_size > 256) /* clamp to a reasonable value */
3162 fd_table_size = 256;
3163
3164 for (i = 3; i < fd_table_size; i++)
3165 close (i);
3166 }
3167 #endif /* PROCESS_SUBSTITUTION */
3168 #endif
3169
3170 static void
3171 close_pipes (in, out)
3172 int in, out;
3173 {
3174 if (in >= 0)
3175 close (in);
3176 if (out >= 0)
3177 close (out);
3178 }
3179
3180 /* Redirect input and output to be from and to the specified pipes.
3181 NO_PIPE and REDIRECT_BOTH are handled correctly. */
3182 static void
3183 do_piping (pipe_in, pipe_out)
3184 int pipe_in, pipe_out;
3185 {
3186 if (pipe_in != NO_PIPE)
3187 {
3188 if (dup2 (pipe_in, 0) < 0)
3189 sys_error ("cannot duplicate fd %d to fd 0", pipe_in);
3190 if (pipe_in > 0)
3191 close (pipe_in);
3192 }
3193 if (pipe_out != NO_PIPE)
3194 {
3195 if (pipe_out != REDIRECT_BOTH)
3196 {
3197 if (dup2 (pipe_out, 1) < 0)
3198 sys_error ("cannot duplicate fd %d to fd 1", pipe_out);
3199 if (pipe_out == 0 || pipe_out > 1)
3200 close (pipe_out);
3201 }
3202 else
3203 if (dup2 (1, 2) < 0)
3204 sys_error ("cannot duplicate fd 1 to fd 2");
3205 }
3206 }
3207
3208 static void
3209 redirection_error (temp, error)
3210 REDIRECT *temp;
3211 int error;
3212 {
3213 char *filename;
3214
3215 if (expandable_redirection_filename (temp))
3216 {
3217 if (posixly_correct && !interactive_shell)
3218 disallow_filename_globbing++;
3219 filename = redirection_expand (temp->redirectee.filename);
3220 if (posixly_correct && !interactive_shell)
3221 disallow_filename_globbing--;
3222 if (filename == 0)
3223 filename = savestring (temp->redirectee.filename->word);
3224 if (filename == 0)
3225 {
3226 filename = xmalloc (1);
3227 filename[0] = '\0';
3228 }
3229 }
3230 else
3231 filename = itos (temp->redirectee.dest);
3232
3233 switch (error)
3234 {
3235 case AMBIGUOUS_REDIRECT:
3236 internal_error ("%s: ambiguous redirect", filename);
3237 break;
3238
3239 case NOCLOBBER_REDIRECT:
3240 internal_error ("%s: cannot overwrite existing file", filename);
3241 break;
3242
3243 #if defined (RESTRICTED_SHELL)
3244 case RESTRICTED_REDIRECT:
3245 internal_error ("%s: restricted: cannot redirect output", filename);
3246 break;
3247 #endif /* RESTRICTED_SHELL */
3248
3249 case HEREDOC_REDIRECT:
3250 internal_error ("cannot create temp file for here document: %s", strerror (heredoc_errno));
3251 break;
3252
3253 default:
3254 internal_error ("%s: %s", filename, strerror (error));
3255 break;
3256 }
3257
3258 FREE (filename);
3259 }
3260
3261 /* Perform the redirections on LIST. If FOR_REAL, then actually make
3262 input and output file descriptors, otherwise just do whatever is
3263 neccessary for side effecting. INTERNAL says to remember how to
3264 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
3265 file descriptors opened in do_redirection () have their close-on-exec
3266 flag set. */
3267 static int
3268 do_redirections (list, for_real, internal, set_clexec)
3269 REDIRECT *list;
3270 int for_real, internal, set_clexec;
3271 {
3272 int error;
3273 REDIRECT *temp;
3274
3275 if (internal)
3276 {
3277 if (redirection_undo_list)
3278 {
3279 dispose_redirects (redirection_undo_list);
3280 redirection_undo_list = (REDIRECT *)NULL;
3281 }
3282 if (exec_redirection_undo_list)
3283 dispose_exec_redirects ();
3284 }
3285
3286 for (temp = list; temp; temp = temp->next)
3287 {
3288 error = do_redirection_internal (temp, for_real, internal, set_clexec);
3289 if (error)
3290 {
3291 redirection_error (temp, error);
3292 return (error);
3293 }
3294 }
3295 return (0);
3296 }
3297
3298 /* Return non-zero if the redirection pointed to by REDIRECT has a
3299 redirectee.filename that can be expanded. */
3300 static int
3301 expandable_redirection_filename (redirect)
3302 REDIRECT *redirect;
3303 {
3304 switch (redirect->instruction)
3305 {
3306 case r_output_direction:
3307 case r_appending_to:
3308 case r_input_direction:
3309 case r_inputa_direction:
3310 case r_err_and_out:
3311 case r_input_output:
3312 case r_output_force:
3313 case r_duplicating_input_word:
3314 case r_duplicating_output_word:
3315 return 1;
3316
3317 default:
3318 return 0;
3319 }
3320 }
3321
3322 /* Expand the word in WORD returning a string. If WORD expands to
3323 multiple words (or no words), then return NULL. */
3324 char *
3325 redirection_expand (word)
3326 WORD_DESC *word;
3327 {
3328 char *result;
3329 WORD_LIST *tlist1, *tlist2;
3330
3331 tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
3332 tlist2 = expand_words_no_vars (tlist1);
3333 dispose_words (tlist1);
3334
3335 if (!tlist2 || tlist2->next)
3336 {
3337 /* We expanded to no words, or to more than a single word.
3338 Dispose of the word list and return NULL. */
3339 if (tlist2)
3340 dispose_words (tlist2);
3341 return ((char *)NULL);
3342 }
3343 result = string_list (tlist2); /* XXX savestring (tlist2->word->word)? */
3344 dispose_words (tlist2);
3345 return (result);
3346 }
3347
3348 /* Write the text of the here document pointed to by REDIRECTEE to the file
3349 descriptor FD, which is already open to a temp file. Return 0 if the
3350 write is successful, otherwise return errno. */
3351 static int
3352 write_here_document (fd, redirectee)
3353 int fd;
3354 WORD_DESC *redirectee;
3355 {
3356 char *document;
3357 int document_len, fd2;
3358 FILE *fp;
3359 register WORD_LIST *t, *tlist;
3360
3361 /* Expand the text if the word that was specified had
3362 no quoting. The text that we expand is treated
3363 exactly as if it were surrounded by double quotes. */
3364
3365 if (redirectee->flags & W_QUOTED)
3366 {
3367 document = redirectee->word;
3368 document_len = strlen (document);
3369 /* Set errno to something reasonable if the write fails. */
3370 if (write (fd, document, document_len) < document_len)
3371 {
3372 if (errno == 0)
3373 errno = ENOSPC;
3374 return (errno);
3375 }
3376 else
3377 return 0;
3378 }
3379
3380 tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
3381 if (tlist)
3382 {
3383 /* Try using buffered I/O (stdio) and writing a word
3384 at a time, letting stdio do the work of buffering
3385 for us rather than managing our own strings. Most
3386 stdios are not particularly fast, however -- this
3387 may need to be reconsidered later. */
3388 if ((fd2 = dup (fd)) < 0 || (fp = fdopen (fd2, "w")) == NULL)
3389 {
3390 if (fd2 >= 0)
3391 close (fd2);
3392 return (errno);
3393 }
3394 errno = 0;
3395 for (t = tlist; t; t = t->next)
3396 {
3397 /* This is essentially the body of
3398 string_list_internal expanded inline. */
3399 document = t->word->word;
3400 document_len = strlen (document);
3401 if (t != tlist)
3402 putc (' ', fp); /* separator */
3403 fwrite (document, document_len, 1, fp);
3404 if (ferror (fp))
3405 {
3406 if (errno == 0)
3407 errno = ENOSPC;
3408 fd2 = errno;
3409 fclose(fp);
3410 dispose_words (tlist);
3411 return (fd2);
3412 }
3413 }
3414 fclose (fp);
3415 dispose_words (tlist);
3416 }
3417 return 0;
3418 }
3419
3420 /* Create a temporary file holding the text of the here document pointed to
3421 by REDIRECTEE, and return a file descriptor open for reading to the temp
3422 file. Return -1 on any error, and make sure errno is set appropriately. */
3423 static int
3424 here_document_to_fd (redirectee)
3425 WORD_DESC *redirectee;
3426 {
3427 char filename[24];
3428 int r, fd;
3429
3430 /* Make the filename for the temp file. */
3431 sprintf (filename, "/tmp/t%d-sh", (int)time ((time_t *) 0) + (int)getpid ());
3432
3433 /* Make sure we open it exclusively. */
3434 fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT | O_EXCL, 0600);
3435 if (fd < 0)
3436 return (fd);
3437
3438 errno = r = 0; /* XXX */
3439 /* write_here_document returns 0 on success, errno on failure. */
3440 if (redirectee->word)
3441 r = write_here_document (fd, redirectee);
3442
3443 close (fd);
3444 if (r)
3445 {
3446 unlink (filename);
3447 errno = r;
3448 return (-1);
3449 }
3450
3451 /* XXX - this is raceable */
3452 /* Make the document really temporary. Also make it the input. */
3453 fd = open (filename, O_RDONLY, 0600);
3454
3455 if (fd < 0)
3456 {
3457 r = errno;
3458 unlink (filename);
3459 errno = r;
3460 return -1;
3461 }
3462
3463 if (unlink (filename) < 0)
3464 {
3465 r = errno;
3466 close (fd);
3467 errno = r;
3468 return (-1);
3469 }
3470
3471 return (fd);
3472 }
3473
3474 /* Open FILENAME with FLAGS in noclobber mode, hopefully avoiding most
3475 race conditions and avoiding the problem where the file is replaced
3476 between the stat(2) and open(2). */
3477 static int
3478 noclobber_open (filename, flags, ri)
3479 char *filename;
3480 int flags;
3481 enum r_instruction ri;
3482 {
3483 int r, fd;
3484 struct stat finfo, finfo2;
3485
3486 /* If the file exists and is a regular file, return an error
3487 immediately. */
3488 r = stat (filename, &finfo);
3489 if (r == 0 && (S_ISREG (finfo.st_mode)))
3490 return (NOCLOBBER_REDIRECT);
3491
3492 /* If the file was not present (r != 0), make sure we open it
3493 exclusively so that if it is created before we open it, our open
3494 will fail. Make sure that we do not truncate an existing file.
3495 Note that we don't turn on O_EXCL unless the stat failed -- if
3496 the file was not a regular file, we leave O_EXCL off. */
3497 flags &= ~O_TRUNC;
3498 if (r != 0)
3499 {
3500 fd = open (filename, flags|O_EXCL, 0666);
3501 return ((fd < 0 && errno == EEXIST) ? NOCLOBBER_REDIRECT : fd);
3502 }
3503 fd = open (filename, flags, 0666);
3504
3505 /* If the open failed, return the file descriptor right away. */
3506 if (fd < 0)
3507 return (errno == EEXIST ? NOCLOBBER_REDIRECT : fd);
3508
3509 /* OK, the open succeeded, but the file may have been changed from a
3510 non-regular file to a regular file between the stat and the open.
3511 We are assuming that the O_EXCL open handles the case where FILENAME
3512 did not exist and is symlinked to an existing file between the stat
3513 and open. */
3514
3515 /* If we can open it and fstat the file descriptor, and neither check
3516 revealed that it was a regular file, and the file has not been replaced,
3517 return the file descriptor. */
3518 if ((fstat (fd, &finfo2) == 0) && (S_ISREG (finfo2.st_mode) == 0) &&
3519 r == 0 && (S_ISREG (finfo.st_mode) == 0) &&
3520 same_file (filename, filename, &finfo, &finfo2))
3521 return fd;
3522
3523 /* The file has been replaced. badness. */
3524 close (fd);
3525 errno = EEXIST;
3526 return (NOCLOBBER_REDIRECT);
3527 }
3528
3529 /* Do the specific redirection requested. Returns errno or one of the
3530 special redirection errors (*_REDIRECT) in case of error, 0 on success.
3531 If FOR_REAL is zero, then just do whatever is neccessary to produce the
3532 appropriate side effects. REMEMBERING, if non-zero, says to remember
3533 how to undo each redirection. If SET_CLEXEC is non-zero, then
3534 we set all file descriptors > 2 that we open to be close-on-exec. */
3535 static int
3536 do_redirection_internal (redirect, for_real, remembering, set_clexec)
3537 REDIRECT *redirect;
3538 int for_real, remembering, set_clexec;
3539 {
3540 WORD_DESC *redirectee;
3541 int redir_fd, fd, redirector, r;
3542 char *redirectee_word;
3543 enum r_instruction ri;
3544 REDIRECT *new_redirect;
3545
3546 redirectee = redirect->redirectee.filename;
3547 redir_fd = redirect->redirectee.dest;
3548 redirector = redirect->redirector;
3549 ri = redirect->instruction;
3550
3551 if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
3552 {
3553 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
3554 the redirection into a new one and continue. */
3555 redirectee_word = redirection_expand (redirectee);
3556
3557 if (redirectee_word == 0)
3558 return (AMBIGUOUS_REDIRECT);
3559 else if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
3560 {
3561 rd.dest = 0L;
3562 new_redirect = make_redirection (redirector, r_close_this, rd);
3563 }
3564 else if (all_digits (redirectee_word))
3565 {
3566 if (ri == r_duplicating_input_word)
3567 {
3568 rd.dest = atol (redirectee_word);
3569 new_redirect = make_redirection (redirector, r_duplicating_input, rd);
3570 }
3571 else
3572 {
3573 rd.dest = atol (redirectee_word);
3574 new_redirect = make_redirection (redirector, r_duplicating_output, rd);
3575 }
3576 }
3577 else if (ri == r_duplicating_output_word && redirector == 1)
3578 {
3579 if (posixly_correct == 0)
3580 {
3581 rd.filename = make_bare_word (redirectee_word);
3582 new_redirect = make_redirection (1, r_err_and_out, rd);
3583 }
3584 else
3585 new_redirect = copy_redirect (redirect);
3586 }
3587 else
3588 {
3589 free (redirectee_word);
3590 return (AMBIGUOUS_REDIRECT);
3591 }
3592
3593 free (redirectee_word);
3594
3595 /* Set up the variables needed by the rest of the function from the
3596 new redirection. */
3597 if (new_redirect->instruction == r_err_and_out)
3598 {
3599 char *alloca_hack;
3600
3601 /* Copy the word without allocating any memory that must be
3602 explicitly freed. */
3603 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
3604 xbcopy ((char *)new_redirect->redirectee.filename,
3605 (char *)redirectee, sizeof (WORD_DESC));
3606
3607 alloca_hack = (char *)
3608 alloca (1 + strlen (new_redirect->redirectee.filename->word));
3609 redirectee->word = alloca_hack;
3610 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
3611 }
3612 else
3613 /* It's guaranteed to be an integer, and shouldn't be freed. */
3614 redirectee = new_redirect->redirectee.filename;
3615
3616 redir_fd = new_redirect->redirectee.dest;
3617 redirector = new_redirect->redirector;
3618 ri = new_redirect->instruction;
3619
3620 /* Overwrite the flags element of the old redirect with the new value. */
3621 redirect->flags = new_redirect->flags;
3622 dispose_redirects (new_redirect);
3623 }
3624
3625 switch (ri)
3626 {
3627 case r_output_direction:
3628 case r_appending_to:
3629 case r_input_direction:
3630 case r_inputa_direction:
3631 case r_err_and_out: /* command &>filename */
3632 case r_input_output:
3633 case r_output_force:
3634 if (posixly_correct && !interactive_shell)
3635 disallow_filename_globbing++;
3636 redirectee_word = redirection_expand (redirectee);
3637 if (posixly_correct && !interactive_shell)
3638 disallow_filename_globbing--;
3639
3640 if (redirectee_word == 0)
3641 return (AMBIGUOUS_REDIRECT);
3642
3643 #if defined (RESTRICTED_SHELL)
3644 if (restricted && (WRITE_REDIRECT (ri)))
3645 {
3646 free (redirectee_word);
3647 return (RESTRICTED_REDIRECT);
3648 }
3649 #endif /* RESTRICTED_SHELL */
3650
3651 /* If we are in noclobber mode, you are not allowed to overwrite
3652 existing files. Check before opening. */
3653 if (noclobber && OUTPUT_REDIRECT (ri))
3654 {
3655 fd = noclobber_open (redirectee_word, redirect->flags, ri);
3656 if (fd == NOCLOBBER_REDIRECT)
3657 {
3658 free (redirectee_word);
3659 return (NOCLOBBER_REDIRECT);
3660 }
3661 }
3662 else
3663 {
3664 fd = open (redirectee_word, redirect->flags, 0666);
3665 #if defined (AFS)
3666 if ((fd < 0) && (errno == EACCES))
3667 fd = open (redirectee_word, redirect->flags & ~O_CREAT, 0666);
3668 #endif /* AFS */
3669 }
3670 free (redirectee_word);
3671
3672 if (fd < 0)
3673 return (errno);
3674
3675 if (for_real)
3676 {
3677 if (remembering)
3678 /* Only setup to undo it if the thing to undo is active. */
3679 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3680 add_undo_redirect (redirector);
3681 else
3682 add_undo_close_redirect (redirector);
3683
3684 #if defined (BUFFERED_INPUT)
3685 check_bash_input (redirector);
3686 #endif
3687
3688 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
3689 return (errno);
3690
3691 #if defined (BUFFERED_INPUT)
3692 /* Do not change the buffered stream for an implicit redirection
3693 of /dev/null to fd 0 for asynchronous commands without job
3694 control (r_inputa_direction). */
3695 if (ri == r_input_direction || ri == r_input_output)
3696 duplicate_buffered_stream (fd, redirector);
3697 #endif /* BUFFERED_INPUT */
3698
3699 /*
3700 * If we're remembering, then this is the result of a while, for
3701 * or until loop with a loop redirection, or a function/builtin
3702 * executing in the parent shell with a redirection. In the
3703 * function/builtin case, we want to set all file descriptors > 2
3704 * to be close-on-exec to duplicate the effect of the old
3705 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
3706 * both sh and ksh leave the file descriptors open across execs.
3707 * The Posix standard mentions only the exec builtin.
3708 */
3709 if (set_clexec && (redirector > 2))
3710 SET_CLOSE_ON_EXEC (redirector);
3711 }
3712
3713 if (fd != redirector)
3714 {
3715 #if defined (BUFFERED_INPUT)
3716 if (INPUT_REDIRECT (ri))
3717 close_buffered_fd (fd);
3718 else
3719 #endif /* !BUFFERED_INPUT */
3720 close (fd); /* Don't close what we just opened! */
3721 }
3722
3723 /* If we are hacking both stdout and stderr, do the stderr
3724 redirection here. */
3725 if (ri == r_err_and_out)
3726 {
3727 if (for_real)
3728 {
3729 if (remembering)
3730 add_undo_redirect (2);
3731 if (dup2 (1, 2) < 0)
3732 return (errno);
3733 }
3734 }
3735 break;
3736
3737 case r_reading_until:
3738 case r_deblank_reading_until:
3739 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
3740 the new input. Place it in a temporary file. */
3741 if (redirectee)
3742 {
3743 fd = here_document_to_fd (redirectee);
3744
3745 if (fd < 0)
3746 {
3747 heredoc_errno = errno;
3748 return (HEREDOC_REDIRECT);
3749 }
3750
3751 if (for_real)
3752 {
3753 if (remembering)
3754 /* Only setup to undo it if the thing to undo is active. */
3755 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
3756 add_undo_redirect (redirector);
3757 else
3758 add_undo_close_redirect (redirector);
3759
3760 #if defined (BUFFERED_INPUT)
3761 check_bash_input (redirector);
3762 #endif
3763 if (fd != redirector && dup2 (fd, redirector) < 0)
3764 {
3765 r = errno;
3766 close (fd);
3767 return (r);
3768 }
3769
3770 #if defined (BUFFERED_INPUT)
3771 duplicate_buffered_stream (fd, redirector);
3772 #endif
3773
3774 if (set_clexec && (redirector > 2))
3775 SET_CLOSE_ON_EXEC (redirector);
3776 }
3777
3778 #if defined (BUFFERED_INPUT)
3779 close_buffered_fd (fd);
3780 #else
3781 close (fd);
3782 #endif
3783 }
3784 break;
3785
3786 case r_duplicating_input:
3787 case r_duplicating_output:
3788 if (for_real && (redir_fd != redirector))
3789 {
3790 if (remembering)
3791 /* Only setup to undo it if the thing to undo is active. */
3792 if (fcntl (redirector, F_GETFD, 0) != -1)
3793 add_undo_redirect (redirector);
3794 else
3795 add_undo_close_redirect (redirector);
3796
3797 #if defined (BUFFERED_INPUT)
3798 check_bash_input (redirector);
3799 #endif
3800 /* This is correct. 2>&1 means dup2 (1, 2); */
3801 if (dup2 (redir_fd, redirector) < 0)
3802 return (errno);
3803
3804 #if defined (BUFFERED_INPUT)
3805 if (ri == r_duplicating_input)
3806 duplicate_buffered_stream (redir_fd, redirector);
3807 #endif /* BUFFERED_INPUT */
3808
3809 /* First duplicate the close-on-exec state of redirectee. dup2
3810 leaves the flag unset on the new descriptor, which means it
3811 stays open. Only set the close-on-exec bit for file descriptors
3812 greater than 2 in any case, since 0-2 should always be open
3813 unless closed by something like `exec 2<&-'. */
3814 /* if ((already_set || set_unconditionally) && (ok_to_set))
3815 set_it () */
3816 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
3817 (redirector > 2))
3818 SET_CLOSE_ON_EXEC (redirector);
3819 }
3820 break;
3821
3822 case r_close_this:
3823 if (for_real)
3824 {
3825 if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
3826 add_undo_redirect (redirector);
3827
3828 #if defined (BUFFERED_INPUT)
3829 check_bash_input (redirector);
3830 close_buffered_fd (redirector);
3831 #else /* !BUFFERED_INPUT */
3832 close (redirector);
3833 #endif /* !BUFFERED_INPUT */
3834 }
3835 break;
3836
3837 case r_duplicating_input_word:
3838 case r_duplicating_output_word:
3839 break;
3840 }
3841 return (0);
3842 }
3843
3844 #define SHELL_FD_BASE 10
3845
3846 /* Remember the file descriptor associated with the slot FD,
3847 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
3848 before it is executed. Any redirections that need to be undone
3849 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
3850 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
3851 static int
3852 add_undo_redirect (fd)
3853 int fd;
3854 {
3855 int new_fd, clexec_flag;
3856 REDIRECT *new_redirect, *closer, *dummy_redirect;
3857
3858 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
3859
3860 if (new_fd < 0)
3861 {
3862 sys_error ("redirection error");
3863 return (-1);
3864 }
3865
3866 clexec_flag = fcntl (fd, F_GETFD, 0);
3867
3868 rd.dest = 0L;
3869 closer = make_redirection (new_fd, r_close_this, rd);
3870 dummy_redirect = copy_redirects (closer);
3871
3872 rd.dest = (long)new_fd;
3873 new_redirect = make_redirection (fd, r_duplicating_output, rd);
3874 new_redirect->next = closer;
3875
3876 closer->next = redirection_undo_list;
3877 redirection_undo_list = new_redirect;
3878
3879 /* Save redirections that need to be undone even if the undo list
3880 is thrown away by the `exec' builtin. */
3881 add_exec_redirect (dummy_redirect);
3882
3883 /* File descriptors used only for saving others should always be
3884 marked close-on-exec. Unfortunately, we have to preserve the
3885 close-on-exec state of the file descriptor we are saving, since
3886 fcntl (F_DUPFD) sets the new file descriptor to remain open
3887 across execs. If, however, the file descriptor whose state we
3888 are saving is <= 2, we can just set the close-on-exec flag,
3889 because file descriptors 0-2 should always be open-on-exec,
3890 and the restore above in do_redirection() will take care of it. */
3891 if (clexec_flag || fd < 3)
3892 SET_CLOSE_ON_EXEC (new_fd);
3893
3894 return (0);
3895 }
3896
3897 /* Set up to close FD when we are finished with the current command
3898 and its redirections. */
3899 static void
3900 add_undo_close_redirect (fd)
3901 int fd;
3902 {
3903 REDIRECT *closer;
3904
3905 rd.dest = 0L;
3906 closer = make_redirection (fd, r_close_this, rd);
3907 closer->next = redirection_undo_list;
3908 redirection_undo_list = closer;
3909 }
3910
3911 static void
3912 add_exec_redirect (dummy_redirect)
3913 REDIRECT *dummy_redirect;
3914 {
3915 dummy_redirect->next = exec_redirection_undo_list;
3916 exec_redirection_undo_list = dummy_redirect;
3917 }
3918
3919 #define u_mode_bits(x) (((x) & 0000700) >> 6)
3920 #define g_mode_bits(x) (((x) & 0000070) >> 3)
3921 #define o_mode_bits(x) (((x) & 0000007) >> 0)
3922 #define X_BIT(x) ((x) & 1)
3923
3924 /* Return some flags based on information about this file.
3925 The EXISTS bit is non-zero if the file is found.
3926 The EXECABLE bit is non-zero the file is executble.
3927 Zero is returned if the file is not found. */
3928 int
3929 file_status (name)
3930 char *name;
3931 {
3932 struct stat finfo;
3933
3934 /* Determine whether this file exists or not. */
3935 if (stat (name, &finfo) < 0)
3936 return (0);
3937
3938 /* If the file is a directory, then it is not "executable" in the
3939 sense of the shell. */
3940 if (S_ISDIR (finfo.st_mode))
3941 return (FS_EXISTS|FS_DIRECTORY);
3942
3943 #if defined (AFS)
3944 /* We have to use access(2) to determine access because AFS does not
3945 support Unix file system semantics. This may produce wrong
3946 answers for non-AFS files when ruid != euid. I hate AFS. */
3947 if (access (name, X_OK) == 0)
3948 return (FS_EXISTS | FS_EXECABLE);
3949 else
3950 return (FS_EXISTS);
3951 #else /* !AFS */
3952
3953 /* Find out if the file is actually executable. By definition, the
3954 only other criteria is that the file has an execute bit set that
3955 we can use. */
3956
3957 /* Root only requires execute permission for any of owner, group or
3958 others to be able to exec a file. */
3959 if (current_user.euid == (uid_t)0)
3960 {
3961 int bits;
3962
3963 bits = (u_mode_bits (finfo.st_mode) |
3964 g_mode_bits (finfo.st_mode) |
3965 o_mode_bits (finfo.st_mode));
3966
3967 if (X_BIT (bits))
3968 return (FS_EXISTS | FS_EXECABLE);
3969 }
3970
3971 /* If we are the owner of the file, the owner execute bit applies. */
3972 if (current_user.euid == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
3973 return (FS_EXISTS | FS_EXECABLE);
3974
3975 /* If we are in the owning group, the group permissions apply. */
3976 if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
3977 return (FS_EXISTS | FS_EXECABLE);
3978
3979 /* If `others' have execute permission to the file, then so do we,
3980 since we are also `others'. */
3981 if (X_BIT (o_mode_bits (finfo.st_mode)))
3982 return (FS_EXISTS | FS_EXECABLE);
3983
3984 return (FS_EXISTS);
3985 #endif /* !AFS */
3986 }
3987
3988 /* Return non-zero if FILE exists and is executable.
3989 Note that this function is the definition of what an
3990 executable file is; do not change this unless YOU know
3991 what an executable file is. */
3992 int
3993 executable_file (file)
3994 char *file;
3995 {
3996 int s;
3997
3998 s = file_status (file);
3999 return ((s & FS_EXECABLE) && ((s & FS_DIRECTORY) == 0));
4000 }
4001
4002 int
4003 is_directory (file)
4004 char *file;
4005 {
4006 return (file_status (file) & FS_DIRECTORY);
4007 }
4008
4009 /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
4010 encounters a `.' as the directory pathname while scanning the
4011 list of possible pathnames; i.e., if `.' comes before the directory
4012 containing the file of interest. */
4013 int dot_found_in_search = 0;
4014
4015 /* Locate the executable file referenced by NAME, searching along
4016 the contents of the shell PATH variable. Return a new string
4017 which is the full pathname to the file, or NULL if the file
4018 couldn't be found. If a file is found that isn't executable,
4019 and that is the only match, then return that. */
4020 char *
4021 find_user_command (name)
4022 char *name;
4023 {
4024 return (find_user_command_internal (name, FS_EXEC_PREFERRED|FS_NODIRS));
4025 }
4026
4027 /* Locate the file referenced by NAME, searching along the contents
4028 of the shell PATH variable. Return a new string which is the full
4029 pathname to the file, or NULL if the file couldn't be found. This
4030 returns the first file found. */
4031 char *
4032 find_path_file (name)
4033 char *name;
4034 {
4035 return (find_user_command_internal (name, FS_EXISTS));
4036 }
4037
4038 static char *
4039 _find_user_command_internal (name, flags)
4040 char *name;
4041 int flags;
4042 {
4043 char *path_list;
4044 SHELL_VAR *var;
4045
4046 /* Search for the value of PATH in both the temporary environment, and
4047 in the regular list of variables. */
4048 if (var = find_variable_internal ("PATH", 1)) /* XXX could be array? */
4049 path_list = value_cell (var);
4050 else
4051 path_list = (char *)NULL;
4052
4053 if (path_list == 0 || *path_list == '\0')
4054 return (savestring (name));
4055
4056 return (find_user_command_in_path (name, path_list, flags));
4057 }
4058
4059 static char *
4060 find_user_command_internal (name, flags)
4061 char *name;
4062 int flags;
4063 {
4064 #ifdef __WIN32__
4065 char *res, *dotexe;
4066
4067 dotexe = xmalloc (strlen (name) + 5);
4068 strcpy (dotexe, name);
4069 strcat (dotexe, ".exe");
4070 res = _find_user_command_internal (dotexe, flags);
4071 free (dotexe);
4072 if (res == 0)
4073 res = _find_user_command_internal (name, flags);
4074 return res;
4075 #else
4076 return (_find_user_command_internal (name, flags));
4077 #endif
4078 }
4079
4080 /* Return the next element from PATH_LIST, a colon separated list of
4081 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
4082 the index is modified by this function.
4083 Return the next element of PATH_LIST or NULL if there are no more. */
4084 static char *
4085 get_next_path_element (path_list, path_index_pointer)
4086 char *path_list;
4087 int *path_index_pointer;
4088 {
4089 char *path;
4090
4091 path = extract_colon_unit (path_list, path_index_pointer);
4092
4093 if (!path)
4094 return (path);
4095
4096 if (!*path)
4097 {
4098 free (path);
4099 path = savestring (".");
4100 }
4101
4102 return (path);
4103 }
4104
4105 /* Look for PATHNAME in $PATH. Returns either the hashed command
4106 corresponding to PATHNAME or the first instance of PATHNAME found
4107 in $PATH. Returns a newly-allocated string. */
4108 char *
4109 search_for_command (pathname)
4110 char *pathname;
4111 {
4112 char *hashed_file, *command;
4113 int temp_path, st;
4114 SHELL_VAR *path;
4115
4116 hashed_file = command = (char *)NULL;
4117
4118 /* If PATH is in the temporary environment for this command, don't use the
4119 hash table to search for the full pathname. */
4120 path = find_tempenv_variable ("PATH");
4121 temp_path = path != 0;
4122
4123 /* Don't waste time trying to find hashed data for a pathname
4124 that is already completely specified or if we're using a command-
4125 specific value for PATH. */
4126 if (path == 0 && absolute_program (pathname) == 0)
4127 hashed_file = find_hashed_filename (pathname);
4128
4129 /* If a command found in the hash table no longer exists, we need to
4130 look for it in $PATH. Thank you Posix.2. This forces us to stat
4131 every command found in the hash table. */
4132
4133 if (hashed_file && (posixly_correct || check_hashed_filenames))
4134 {
4135 st = file_status (hashed_file);
4136 if ((st ^ (FS_EXISTS | FS_EXECABLE)) != 0)
4137 {
4138 remove_hashed_filename (pathname);
4139 free (hashed_file);
4140 hashed_file = (char *)NULL;
4141 }
4142 }
4143
4144 if (hashed_file)
4145 command = hashed_file;
4146 else if (absolute_program (pathname))
4147 /* A command containing a slash is not looked up in PATH or saved in
4148 the hash table. */
4149 command = savestring (pathname);
4150 else
4151 {
4152 /* If $PATH is in the temporary environment, we've already retrieved
4153 it, so don't bother trying again. */
4154 if (temp_path)
4155 command = find_user_command_in_path (pathname, value_cell (path),
4156 FS_EXEC_PREFERRED|FS_NODIRS);
4157 else
4158 command = find_user_command (pathname);
4159 if (command && hashing_enabled && temp_path == 0)
4160 remember_filename (pathname, command, dot_found_in_search, 1);
4161 }
4162 return (command);
4163 }
4164
4165 char *
4166 user_command_matches (name, flags, state)
4167 char *name;
4168 int flags, state;
4169 {
4170 register int i;
4171 int path_index, name_len;
4172 char *path_list, *path_element, *match;
4173 struct stat dotinfo;
4174 static char **match_list = NULL;
4175 static int match_list_size = 0;
4176 static int match_index = 0;
4177
4178 if (state == 0)
4179 {
4180 /* Create the list of matches. */
4181 if (match_list == 0)
4182 {
4183 match_list_size = 5;
4184 match_list = (char **)xmalloc (match_list_size * sizeof(char *));
4185 }
4186
4187 /* Clear out the old match list. */
4188 for (i = 0; i < match_list_size; i++)
4189 match_list[i] = 0;
4190
4191 /* We haven't found any files yet. */
4192 match_index = 0;
4193
4194 if (absolute_program (name))
4195 {
4196 match_list[0] = find_absolute_program (name, flags);
4197 match_list[1] = (char *)NULL;
4198 path_list = (char *)NULL;
4199 }
4200 else
4201 {
4202 name_len = strlen (name);
4203 file_to_lose_on = (char *)NULL;
4204 dot_found_in_search = 0;
4205 stat (".", &dotinfo);
4206 path_list = get_string_value ("PATH");
4207 path_index = 0;
4208 }
4209
4210 while (path_list && path_list[path_index])
4211 {
4212 path_element = get_next_path_element (path_list, &path_index);
4213
4214 if (path_element == 0)
4215 break;
4216
4217 match = find_in_path_element (name, path_element, flags, name_len, &dotinfo);
4218
4219 free (path_element);
4220
4221 if (match == 0)
4222 continue;
4223
4224 if (match_index + 1 == match_list_size)
4225 {
4226 match_list_size += 10;
4227 match_list = (char **)xrealloc (match_list, (match_list_size + 1) * sizeof (char *));
4228 }
4229
4230 match_list[match_index++] = match;
4231 match_list[match_index] = (char *)NULL;
4232 FREE (file_to_lose_on);
4233 file_to_lose_on = (char *)NULL;
4234 }
4235
4236 /* We haven't returned any strings yet. */
4237 match_index = 0;
4238 }
4239
4240 match = match_list[match_index];
4241
4242 if (match)
4243 match_index++;
4244
4245 return (match);
4246 }
4247
4248 /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
4249 This allocates new memory and returns it. */
4250 static char *
4251 make_full_pathname (path, name, name_len)
4252 char *path, *name;
4253 int name_len;
4254 {
4255 char *full_path;
4256 int path_len;
4257
4258 path_len = strlen (path);
4259 full_path = xmalloc (2 + path_len + name_len);
4260 strcpy (full_path, path);
4261 full_path[path_len] = '/';
4262 strcpy (full_path + path_len + 1, name);
4263 return (full_path);
4264 }
4265
4266 static char *
4267 find_absolute_program (name, flags)
4268 char *name;
4269 int flags;
4270 {
4271 int st;
4272
4273 st = file_status (name);
4274
4275 /* If the file doesn't exist, quit now. */
4276 if ((st & FS_EXISTS) == 0)
4277 return ((char *)NULL);
4278
4279 /* If we only care about whether the file exists or not, return
4280 this filename. Otherwise, maybe we care about whether this
4281 file is executable. If it is, and that is what we want, return it. */
4282 if ((flags & FS_EXISTS) || ((flags & FS_EXEC_ONLY) && (st & FS_EXECABLE)))
4283 return (savestring (name));
4284
4285 return ((char *)NULL);
4286 }
4287
4288 static char *
4289 find_in_path_element (name, path, flags, name_len, dotinfop)
4290 char *name, *path;
4291 int flags, name_len;
4292 struct stat *dotinfop;
4293 {
4294 int status;
4295 char *full_path, *xpath;
4296
4297 xpath = (*path == '~') ? bash_tilde_expand (path) : path;
4298
4299 /* Remember the location of "." in the path, in all its forms
4300 (as long as they begin with a `.', e.g. `./.') */
4301 if (dot_found_in_search == 0 && *xpath == '.')
4302 dot_found_in_search = same_file (".", xpath, dotinfop, (struct stat *)NULL);
4303
4304 full_path = make_full_pathname (xpath, name, name_len);
4305
4306 status = file_status (full_path);
4307
4308 if (xpath != path)
4309 free (xpath);
4310
4311 if ((status & FS_EXISTS) == 0)
4312 {
4313 free (full_path);
4314 return ((char *)NULL);
4315 }
4316
4317 /* The file exists. If the caller simply wants the first file, here it is. */
4318 if (flags & FS_EXISTS)
4319 return (full_path);
4320
4321 /* If the file is executable, then it satisfies the cases of
4322 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
4323 if ((status & FS_EXECABLE) &&
4324 (((flags & FS_NODIRS) == 0) || ((status & FS_DIRECTORY) == 0)))
4325 {
4326 FREE (file_to_lose_on);
4327 file_to_lose_on = (char *)NULL;
4328 return (full_path);
4329 }
4330
4331 /* The file is not executable, but it does exist. If we prefer
4332 an executable, then remember this one if it is the first one
4333 we have found. */
4334 if ((flags & FS_EXEC_PREFERRED) && file_to_lose_on == 0)
4335 file_to_lose_on = savestring (full_path);
4336
4337 /* If we want only executable files, or we don't want directories and
4338 this file is a directory, fail. */
4339 if ((flags & FS_EXEC_ONLY) || (flags & FS_EXEC_PREFERRED) ||
4340 ((flags & FS_NODIRS) && (status & FS_DIRECTORY)))
4341 {
4342 free (full_path);
4343 return ((char *)NULL);
4344 }
4345 else
4346 return (full_path);
4347 }
4348
4349 /* This does the dirty work for find_user_command_internal () and
4350 user_command_matches ().
4351 NAME is the name of the file to search for.
4352 PATH_LIST is a colon separated list of directories to search.
4353 FLAGS contains bit fields which control the files which are eligible.
4354 Some values are:
4355 FS_EXEC_ONLY: The file must be an executable to be found.
4356 FS_EXEC_PREFERRED: If we can't find an executable, then the
4357 the first file matching NAME will do.
4358 FS_EXISTS: The first file found will do.
4359 FS_NODIRS: Don't find any directories.
4360 */
4361 static char *
4362 find_user_command_in_path (name, path_list, flags)
4363 char *name;
4364 char *path_list;
4365 int flags;
4366 {
4367 char *full_path, *path;
4368 int path_index, name_len;
4369 struct stat dotinfo;
4370
4371 /* We haven't started looking, so we certainly haven't seen
4372 a `.' as the directory path yet. */
4373 dot_found_in_search = 0;
4374
4375 if (absolute_program (name))
4376 {
4377 full_path = find_absolute_program (name, flags);
4378 return (full_path);
4379 }
4380
4381 if (path_list == 0 || *path_list == '\0')
4382 return (savestring (name)); /* XXX */
4383
4384 file_to_lose_on = (char *)NULL;
4385 name_len = strlen (name);
4386 stat (".", &dotinfo);
4387 path_index = 0;
4388
4389 while (path_list[path_index])
4390 {
4391 /* Allow the user to interrupt out of a lengthy path search. */
4392 QUIT;
4393
4394 path = get_next_path_element (path_list, &path_index);
4395 if (path == 0)
4396 break;
4397
4398 /* Side effects: sets dot_found_in_search, possibly sets
4399 file_to_lose_on. */
4400 full_path = find_in_path_element (name, path, flags, name_len, &dotinfo);
4401 free (path);
4402
4403 /* This should really be in find_in_path_element, but there isn't the
4404 right combination of flags. */
4405 if (full_path && is_directory (full_path))
4406 {
4407 free (full_path);
4408 continue;
4409 }
4410
4411 if (full_path)
4412 {
4413 FREE (file_to_lose_on);
4414 return (full_path);
4415 }
4416 }
4417
4418 /* We didn't find exactly what the user was looking for. Return
4419 the contents of FILE_TO_LOSE_ON which is NULL when the search
4420 required an executable, or non-NULL if a file was found and the
4421 search would accept a non-executable as a last resort. */
4422 return (file_to_lose_on);
4423 }