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