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