]> git.ipfire.org Git - thirdparty/bash.git/blame - CWRU/new/execute_cmd.c.lastpipe-first
small asan fixes; size_t and other ANSI C changes; restore readline variables in...
[thirdparty/bash.git] / CWRU / new / execute_cmd.c.lastpipe-first
CommitLineData
5e13499c
CR
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
21#include <stdio.h>
22#include <ctype.h>
23#include <sys/types.h>
24#include <sys/file.h>
25#include "posixstat.h"
26#include "filecntl.h"
27#include <signal.h>
28
29#if !defined (SIGABRT)
30#define SIGABRT SIGIOT
31#endif
32
33#include <sys/param.h>
34#include <errno.h>
35
36#include "shell.h"
37#include "y.tab.h"
38#include "flags.h"
39#include "hash.h"
40#include "jobs.h"
41
42#include "sysdefs.h"
43#include <glob/fnmatch.h>
44
45#if defined (BUFFERED_INPUT)
46# include "input.h"
47#endif
48
49#define CMD_NO_WAIT 0x40 /* XXX move to command.h */
50#define CMD_LAST_PIPE 0x80 /* XXX ditto */
51
52#if !defined (errno)
53extern int errno;
54#endif
55
56extern int breaking, continuing, loop_level;
57extern int interactive, login_shell;
58
59#if defined (JOB_CONTROL)
60extern int job_control;
61extern int set_job_control ();
62#endif /* JOB_CONTROL */
63
64extern int getdtablesize ();
65extern int close ();
66extern char *strerror ();
67extern char *string_list ();
68
69#if defined (USG)
70extern pid_t last_made_pid;
71#endif
72
73struct stat SB;
74
75extern WORD_LIST *expand_words (), *expand_word ();
76extern WORD_LIST *expand_word_leave_quoted ();
77extern char *make_command_string ();
78
79extern Function *find_shell_builtin (), *builtin_address ();
80extern SigHandler *set_sigint_handler ();
81
82#if defined (PROCESS_SUBSTITUTION)
83void close_all_files ();
84#endif /* PROCESS_SUBSTITUTION */
85
86/* Static functions defined and used in this file. */
87static void close_pipes (), do_piping (), execute_disk_command ();
88static void execute_subshell_builtin_or_function ();
89static void cleanup_redirects (), cleanup_func_redirects (), bind_lastarg ();
90static void add_undo_close_redirect ();
91static int do_redirection_internal (), do_redirections ();
92static int expandable_redirection_filename (), execute_shell_script ();
93static int execute_builtin_or_function (), add_undo_redirect ();
94static char *find_user_command_internal (), *find_user_command_in_path ();
95
96/* The value returned by the last synchronous command. */
97int last_command_exit_value = 0;
98
99/* The list of redirections to preform which will undo the redirections
100 that I made in the shell. */
101REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
102
103/* Have we just forked, and are we now running in a subshell environment? */
104int subshell_environment = 0;
105
106/* Use this as the function to call when adding unwind protects so we
107 don't need to know what free() returns. */
108void
109vfree (string)
110 char *string;
111{
112 free (string);
113}
114
115#define FD_BITMAP_DEFAULT_SIZE 32
116/* Functions to allocate and deallocate the structures used to pass
117 information from the shell to its children about file descriptors
118 to close. */
119struct fd_bitmap *
120new_fd_bitmap (size)
121 long size;
122{
123 struct fd_bitmap *ret;
124
125 ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
126
127 ret->size = size;
128
129 if (size)
130 {
131 ret->bitmap = (char *)xmalloc (size);
132 bzero (ret->bitmap, size);
133 }
134 else
135 ret->bitmap = (char *)NULL;
136 return (ret);
137}
138
139void
140dispose_fd_bitmap (fdbp)
141 struct fd_bitmap *fdbp;
142{
143 if (fdbp->bitmap)
144 free (fdbp->bitmap);
145
146 free (fdbp);
147}
148
149void
150close_fd_bitmap (fdbp)
151 struct fd_bitmap *fdbp;
152{
153 register int i;
154
155 if (fdbp)
156 {
157 for (i = 0; i < fdbp->size; i++)
158 if (fdbp->bitmap[i])
159 {
160 close (i);
161 fdbp->bitmap[i] = 0;
162 }
163 }
164}
165
166/* Execute the command passed in COMMAND. COMMAND is exactly what
167 read_command () places into GLOBAL_COMMAND. See "command.h" for the
168 details of the command structure.
169
170 EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
171 return values. Executing a command with nothing in it returns
172 EXECUTION_SUCCESS. */
173execute_command (command)
174 COMMAND *command;
175{
176 struct fd_bitmap *bitmap;
177 int result;
178
179 bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
180
181 /* Just do the command, but not asynchronously. */
182 result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
183
184 dispose_fd_bitmap (bitmap);
185
186#if defined (PROCESS_SUBSTITUTION)
187 unlink_fifo_list ();
188#endif /* PROCESS_SUBSTITUTION */
189
190 return (result);
191}
192
193/* Return 1 if TYPE is a shell control structure type. */
194int
195shell_control_structure (type)
196 enum command_type type;
197{
198 switch (type)
199 {
200 case cm_for:
201 case cm_case:
202 case cm_while:
203 case cm_until:
204 case cm_if:
205 case cm_group:
206 return (1);
207
208 default:
209 return (0);
210 }
211}
212
213/* A function to use to unwind_protect the redirection undo list
214 for loops. */
215static void
216cleanup_redirects (list)
217 REDIRECT *list;
218{
219 do_redirections (list, 1, 0, 0);
220 dispose_redirects (list);
221}
222
223/* Function to unwind_protect the redirections for functions and builtins. */
224static void
225cleanup_func_redirects (list)
226 REDIRECT *list;
227{
228 do_redirections (list, 1, 0, 0);
229}
230
231#if defined (JOB_CONTROL)
232/* A function to restore the signal mask to its proper value when the shell
233 is interrupted or errors occur while creating a pipeline. */
234static int
235restore_signal_mask (set)
236 sigset_t set;
237{
238 return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
239}
240#endif /* JOB_CONTROL */
241
242/* A debugging function that can be called from gdb, for instance. */
243open_files ()
244{
245 register int i;
246 int f, fd_table_size;
247
248 fd_table_size = getdtablesize ();
249
250 fprintf (stderr, "pid %d open files:", getpid ());
251 for (i = 3; i < fd_table_size; i++)
252 {
253 if ((f = fcntl (i, F_GETFD, 0)) != -1)
254 fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
255 }
256 fprintf (stderr, "\n");
257}
258
259execute_command_internal (command, asynchronous, pipe_in, pipe_out,
260 fds_to_close)
261 COMMAND *command;
262 int asynchronous;
263 int pipe_in, pipe_out;
264 struct fd_bitmap *fds_to_close;
265{
266 int exec_result = EXECUTION_SUCCESS;
267 int invert, ignore_return;
268 REDIRECT *my_undo_list;
269
270 if (!command || breaking || continuing)
271 return (EXECUTION_SUCCESS);
272
273 run_pending_traps ();
274
275 invert = (command->flags & CMD_INVERT_RETURN) != 0;
276
277 /* If a command was being explicitly run in a subshell, or if it is
278 a shell control-structure, and it has a pipe, then we do the command
279 in a subshell. */
280
281 if ((command->flags & CMD_WANT_SUBSHELL) ||
282 (command->flags & CMD_FORCE_SUBSHELL) ||
283 (shell_control_structure (command->type) &&
284 (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
285 {
286 pid_t paren_pid;
287
288 /* Fork a subshell, turn off the subshell bit, turn off job
289 control and call execute_command () on the command again. */
290 paren_pid = make_child (savestring (make_command_string (command)),
291 asynchronous);
292 if (paren_pid == 0)
293 {
294 int user_subshell, return_code;
295
296#if defined (JOB_CONTROL)
297 set_sigchld_handler ();
298#endif /* JOB_CONTROL */
299
300 set_sigint_handler ();
301
302 user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
303 command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL);
304
305 /* If a command is asynchronous in a subshell (like ( foo ) & or
306 the special case of an asynchronous GROUP command where the
307 the subshell bit is turned on down in case cm_group: below),
308 turn off `asynchronous', so that two subshells aren't spawned.
309
310 This seems semantically correct to me. For example,
311 ( foo ) & seems to say ``do the command `foo' in a subshell
312 environment, but don't wait for that subshell to finish'',
313 and "{ foo ; bar } &" seems to me to be like functions or
314 builtins in the background, which executed in a subshell
315 environment. I just don't see the need to fork two subshells. */
316
317 /* Don't fork again, we are already in a subshell. */
318 asynchronous = 0;
319
320 /* Subshells are neither login nor interactive. */
321 login_shell = interactive = 0;
322
323 subshell_environment = 1;
324
325#if defined (JOB_CONTROL)
326 /* Delete all traces that there were any jobs running. This is
327 only for subshells. */
328 without_job_control ();
329#endif /* JOB_CONTROL */
330 do_piping (pipe_in, pipe_out);
331
332 if (fds_to_close)
333 close_fd_bitmap (fds_to_close);
334
335 /* Do redirections, then dispose of them before recursive call. */
336 if (command->redirects)
337 {
338 if (do_redirections (command->redirects, 1, 0, 0) != 0)
339 exit (EXECUTION_FAILURE);
340
341 dispose_redirects (command->redirects);
342 command->redirects = (REDIRECT *)NULL;
343 }
344
345 return_code = execute_command_internal
346 (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
347
348 /* If we were explicitly placed in a subshell with (), we need
349 to do the `shell cleanup' things, such as running traps[0]. */
350 if (user_subshell)
351 run_exit_trap ();
352
353 exit (return_code);
354 }
355 else
356 {
357 close_pipes (pipe_in, pipe_out);
358
359 /* If we are part of a pipeline, and not the end of the pipeline,
360 then we should simply return and let the last command in the
361 pipe be waited for. If we are not in a pipeline, or are the
362 last command in the pipeline, then we wait for the subshell
363 and return its exit status as usual. */
364 if (pipe_out != NO_PIPE)
365 return (EXECUTION_SUCCESS);
366
367 if (command->flags & CMD_NO_WAIT)
368 return (EXECUTION_SUCCESS);
369
370 stop_pipeline (asynchronous, (COMMAND *)NULL);
371
372 if (!asynchronous)
373 {
374 last_command_exit_value = wait_for (paren_pid);
375
376 /* If we have to, invert the return value. */
377 if (invert)
378 {
379 if (last_command_exit_value == EXECUTION_SUCCESS)
380 return (EXECUTION_FAILURE);
381 else
382 return (EXECUTION_SUCCESS);
383 }
384 else
385 return (last_command_exit_value);
386 }
387 else
388 {
389 if (interactive)
390 describe_pid (paren_pid);
391
392 run_pending_traps ();
393
394 return (EXECUTION_SUCCESS);
395 }
396 }
397 }
398
399 /* Handle WHILE FOR CASE etc. with redirections. (Also '&' input
400 redirection.) */
401 if (do_redirections (command->redirects, 1, 1, 0) != 0)
402 return (EXECUTION_FAILURE);
403
404 my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
405
406 begin_unwind_frame ("loop_redirections");
407
408 if (my_undo_list)
409 add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
410
411 ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
412
413 switch (command->type)
414 {
415 case cm_for:
416 if (ignore_return)
417 command->value.For->flags |= CMD_IGNORE_RETURN;
418 exec_result = execute_for_command (command->value.For);
419 break;
420
421 case cm_case:
422 if (ignore_return)
423 command->value.Case->flags |= CMD_IGNORE_RETURN;
424 exec_result = execute_case_command (command->value.Case);
425 break;
426
427 case cm_while:
428 if (ignore_return)
429 command->value.While->flags |= CMD_IGNORE_RETURN;
430 exec_result = execute_while_command (command->value.While);
431 break;
432
433 case cm_until:
434 if (ignore_return)
435 command->value.While->flags |= CMD_IGNORE_RETURN;
436 exec_result = execute_until_command (command->value.While);
437 break;
438
439 case cm_if:
440 if (ignore_return)
441 command->value.If->flags |= CMD_IGNORE_RETURN;
442 exec_result = execute_if_command (command->value.If);
443 break;
444
445 case cm_group:
446
447 /* This code can be executed from either of two paths: an explicit
448 '{}' command, or via a function call. If we are executed via a
449 function call, we have already taken care of the function being
450 executed in the background (down there in execute_simple_command ()),
451 and this command should *not* be marked as asynchronous. If we
452 are executing a regular '{}' group command, and asynchronous == 1,
453 we must want to execute the whole command in the background, so we
454 need a subshell, and we want the stuff executed in that subshell
455 (this group command) to be executed in the foreground of that
456 subshell (i.e. there will not be *another* subshell forked).
457
458 What we do is to force a subshell if asynchronous, and then call
459 execute_command_internal again with asynchronous still set to 1,
460 but with the original group command, so the printed command will
461 look right.
462
463 The code above that handles forking off subshells will note that
464 both subshell and async are on, and turn off async in the child
465 after forking the subshell (but leave async set in the parent, so
466 the normal call to describe_pid is made). This turning off
467 async is *crucial*; if it is not done, this will fall into an
468 infinite loop of executions through this spot in subshell after
469 subshell until the process limit is exhausted. */
470
471 if (asynchronous)
472 {
473 command->flags |= CMD_FORCE_SUBSHELL;
474 exec_result =
475 execute_command_internal (command, 1, pipe_in, pipe_out,
476 fds_to_close);
477 }
478 else
479 {
480 if (ignore_return && command->value.Group->command)
481 command->value.Group->command->flags |= CMD_IGNORE_RETURN;
482 exec_result =
483 execute_command_internal (command->value.Group->command,
484 asynchronous, pipe_in, pipe_out,
485 fds_to_close);
486 }
487 break;
488
489 case cm_simple:
490 {
491 pid_t last_pid = last_made_pid;
492
493#if defined (JOB_CONTROL)
494 extern int already_making_children;
495#endif /* JOB_CONTROL */
496 if (ignore_return && command->value.Simple)
497 command->value.Simple->flags |= CMD_IGNORE_RETURN;
498 exec_result =
499 execute_simple_command (command->value.Simple, pipe_in, pipe_out,
500 asynchronous, fds_to_close);
501
502 /* The temporary environment should be used for only the simple
503 command immediately following its definition. */
504 dispose_used_env_vars ();
505
506#if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
507 /* Reclaim memory allocated with alloca () on machines which
508 may be using the alloca emulation code. */
509 (void) alloca (0);
510#endif /* (Ultrix && mips) || !HAVE_ALLOCA */
511
512 if (command->flags & CMD_NO_WAIT)
513 break;
514
515 /* If we forked to do the command, then we must wait_for ()
516 the child. */
517#if defined (JOB_CONTROL)
518 if (already_making_children && pipe_out == NO_PIPE)
519#else
520 if (pipe_out == NO_PIPE)
521#endif /* JOB_CONTROL */
522 {
523 if (last_pid != last_made_pid)
524 {
525 stop_pipeline (asynchronous, (COMMAND *)NULL);
526
527 if (asynchronous)
528 {
529 if (interactive)
530 describe_pid (last_made_pid);
531 }
532 else
533#if !defined (JOB_CONTROL)
534 /* Do not wait for asynchronous processes started from
535 startup files. */
536 if (last_made_pid != last_asynchronous_pid)
537#endif
538 /* When executing a shell function that executes other
539 commands, this causes the last simple command in
540 the function to be waited for twice. */
541 exec_result = wait_for (last_made_pid);
542 }
543 }
544 }
545 if (!ignore_return && exit_immediately_on_error && !invert &&
546 (exec_result != EXECUTION_SUCCESS))
547 {
548 last_command_exit_value = exec_result;
549 run_pending_traps ();
550 longjmp (top_level, EXITPROG);
551 }
552
553 break;
554
555 case cm_connection:
556 switch (command->value.Connection->connector)
557 {
558 /* Do the first command asynchronously. */
559 case '&':
560 {
561 COMMAND *tc = command->value.Connection->first;
562 REDIRECT *rp = tc->redirects;
563
564 if (ignore_return && tc)
565 tc->flags |= CMD_IGNORE_RETURN;
566
567 /* If this shell was compiled without job control, or if job
568 control is not active (e.g., if the shell is not interactive),
569 the standard input for an asynchronous command is /dev/null. */
570#if defined (JOB_CONTROL)
571 if (!interactive || !job_control)
572#endif /* JOB_CONTROL */
573 {
574 REDIRECT *tr =
575 make_redirection (0, r_inputa_direction,
576 make_word ("/dev/null"));
577 tr->next = tc->redirects;
578 tc->redirects = tr;
579 }
580
581 exec_result = execute_command_internal (tc, 1, pipe_in, pipe_out,
582 fds_to_close);
583
584#if defined (JOB_CONTROL)
585 if (!interactive || !job_control)
586#endif /* JOB_CONTROL */
587 {
588 /* Remove the redirection we added above. It matters,
589 especially for loops, which call execute_command ()
590 multiple times with the same command. */
591 REDIRECT *tr, *tl;
592
593 tr = tc->redirects;
594 do
595 {
596 tl = tc->redirects;
597 tc->redirects = tc->redirects->next;
598 }
599 while (tc->redirects && tc->redirects != rp);
600
601 tl->next = (REDIRECT *)NULL;
602 dispose_redirects (tr);
603 }
604
605 {
606 register COMMAND *second;
607
608 second = command->value.Connection->second;
609
610 if (second)
611 {
612 if (ignore_return)
613 second->flags |= CMD_IGNORE_RETURN;
614
615 exec_result = execute_command_internal
616 (second, asynchronous, pipe_in, pipe_out, fds_to_close);
617 }
618 }
619 }
620 break;
621
622 case ';':
623 /* Just call execute command on both of them. */
624 if (ignore_return)
625 {
626 if (command->value.Connection->first)
627 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
628 QUIT;
629 if (command->value.Connection->second)
630 command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
631 }
632 execute_command (command->value.Connection->first);
633 QUIT;
634 exec_result =
635 execute_command_internal (command->value.Connection->second,
636 asynchronous, pipe_in, pipe_out,
637 fds_to_close);
638 break;
639
640 case '|':
641 {
642 int prev, fildes[2], new_bitmap_size, dummyfd;
643 COMMAND *cmd;
644 int outpipe;
645 struct fd_bitmap *fd_bitmap;
646
647#if defined (JOB_CONTROL)
648 COMMAND *lastcmd;
649 int lastpipe[2];
650 pid_t lastpipe_pid;
651
652 sigset_t set, oset;
653 BLOCK_CHILD (set, oset);
654#endif /* JOB_CONTROL */
655
656#if defined (JOB_CONTROL)
657 /* Fork the last command in the pipeline first, then the rest of
658 the commands, to avoid synchronization problems. */
659 /* Find the last pipeline element */
660 lastcmd = command;
661 while (lastcmd && lastcmd->type == cm_connection &&
662 lastcmd->value.Connection &&
663 lastcmd->value.Connection->connector == '|')
664 lastcmd = lastcmd->value.Connection->second;
665
666 if (pipe (lastpipe) < 0)
667 {
668 report_error ("pipe error: %s", strerror (errno));
669 terminate_current_pipeline ();
670 kill_current_pipeline ();
671 last_command_exit_value = EXECUTION_FAILURE;
672 throw_to_top_level ();
673 }
674
675 /* Now execute the rightmost command in the pipeline, but do
676 not wait for it. */
677 if (ignore_return && lastcmd)
678 lastcmd->flags |= CMD_IGNORE_RETURN;
679 lastcmd->flags |= (CMD_NO_WAIT | CMD_LAST_PIPE);
680 fds_to_close->bitmap[lastpipe[1]] = 1;
681 (void) execute_command_internal
682 (lastcmd, asynchronous, lastpipe[0], pipe_out, fds_to_close);
683 lastpipe_pid = last_made_pid;
684#endif /* JOB_CONTROL */
685
686 prev = pipe_in;
687 cmd = command;
688
689 while (cmd &&
690 cmd->type == cm_connection &&
691 cmd->value.Connection &&
692 cmd->value.Connection->connector == '|')
693 {
694 /* Make a pipeline between the two commands. */
695 if (pipe (fildes) < 0)
696 {
697 report_error ("pipe error: %s", strerror (errno));
698#if defined (JOB_CONTROL)
699 terminate_current_pipeline ();
700 kill_current_pipeline ();
701#endif /* JOB_CONTROL */
702 last_command_exit_value = EXECUTION_FAILURE;
703 /* The unwind-protects installed below will take care
704 of closing all of the open file descriptors. */
705 throw_to_top_level ();
706 }
707 else
708 {
709 /* Here is a problem: with the new file close-on-exec
710 code, the read end of the pipe (fildes[0]) stays open
711 in the first process, so that process will never get a
712 SIGPIPE. There is no way to signal the first process
713 that it should close fildes[0] after forking, so it
714 remains open. No SIGPIPE is ever sent because there
715 is still a file descriptor open for reading connected
716 to the pipe. We take care of that here. This passes
717 around a bitmap of file descriptors that must be
718 closed after making a child process in
719 execute_simple_command. */
720
721 /* We need fd_bitmap to be at least as big as fildes[0].
722 If fildes[0] is less than fds_to_close->size, then
723 use fds_to_close->size. */
724
725 if (fildes[0] < fds_to_close->size)
726 new_bitmap_size = fds_to_close->size;
727 else
728 new_bitmap_size = fildes[0] + 8;
729
730 fd_bitmap = new_fd_bitmap (new_bitmap_size);
731
732 /* Now copy the old information into the new bitmap. */
733 bcopy (fds_to_close->bitmap, fd_bitmap->bitmap,
734 fds_to_close->size);
735
736 /* And mark the pipe file descriptors to be closed. */
737 fd_bitmap->bitmap[fildes[0]] = 1;
738
739 /* In case there are pipe or out-of-processes errors, we
740 want all these file descriptors to be closed when
741 unwind-protects are run, and the storage used for the
742 bitmaps freed up. */
743 begin_unwind_frame ("pipe-file-descriptors");
744 add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
745 add_unwind_protect (close_fd_bitmap, fd_bitmap);
746 if (prev >= 0)
747 add_unwind_protect (close, prev);
748 dummyfd = fildes[1];
749 add_unwind_protect (close, dummyfd);
750
751#if defined (JOB_CONTROL)
752 add_unwind_protect (restore_signal_mask, oset);
753#endif /* JOB_CONTROL */
754
755 if (ignore_return && cmd->value.Connection->first)
756 cmd->value.Connection->first->flags |=
757 CMD_IGNORE_RETURN;
758
759#if defined (JOB_CONTROL)
760 if (cmd->value.Connection->second == lastcmd)
761 {
762 outpipe = lastpipe[1];
763 close (fildes[1]);
764 }
765 else
766#endif /* JOB_CONTROL */
767 outpipe = fildes[1];
768
769 execute_command_internal
770 (cmd->value.Connection->first, asynchronous, prev,
771 outpipe, fd_bitmap);
772
773 if (prev >= 0)
774 close (prev);
775
776 prev = fildes[0];
777 close (outpipe);
778
779 dispose_fd_bitmap (fd_bitmap);
780 discard_unwind_frame ("pipe-file-descriptors");
781 }
782 cmd = cmd->value.Connection->second;
783#if defined (JOB_CONTROL)
784 if (cmd == lastcmd)
785 break;
786#endif
787 }
788
789#if !defined (JOB_CONTROL)
790 /* Now execute the rightmost command in the pipeline. */
791 if (ignore_return && cmd)
792 cmd->flags |= CMD_IGNORE_RETURN;
793 exec_result =
794 execute_command_internal
795 (cmd, asynchronous, prev, pipe_out, fds_to_close);
796#endif /* !JOB_CONTROL */
797
798 if (prev >= 0)
799 close (prev);
800
801#if defined (JOB_CONTROL)
802 UNBLOCK_CHILD (oset);
803#endif
804
805#if defined (JOB_CONTROL)
806 /* Because we created the processes out of order, we have to
807 reorder the pipeline slightly. */
808 rotate_the_pipeline ();
809 stop_pipeline (asynchronous, (COMMAND *)NULL);
810 if (asynchronous && interactive)
811 describe_pid (lastpipe_pid);
812 exec_result = wait_for (lastpipe_pid);
813 if (!ignore_return && exit_immediately_on_error && !invert &&
814 (exec_result != EXECUTION_SUCCESS))
815 {
816 last_command_exit_value = exec_result;
817 run_pending_traps ();
818 longjmp (top_level, EXITPROG);
819 }
820#endif /* JOB_CONTROL */
821 }
822 break;
823
824 case AND_AND:
825 if (asynchronous)
826 {
827 /* If we have something like `a && b &', run the && stuff in a
828 subshell. Force a subshell and just call
829 execute_command_internal again. Leave asynchronous on
830 so that we get a report from the parent shell about the
831 background job. */
832 command->flags |= CMD_FORCE_SUBSHELL;
833 exec_result = execute_command_internal (command, 1, pipe_in,
834 pipe_out, fds_to_close);
835 break;
836 }
837
838 /* Execute the first command. If the result of that is successful,
839 then execute the second command, otherwise return. */
840
841 if (command->value.Connection->first)
842 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
843
844 exec_result = execute_command (command->value.Connection->first);
845 QUIT;
846 if (exec_result == EXECUTION_SUCCESS)
847 {
848 if (ignore_return && command->value.Connection->second)
849 command->value.Connection->second->flags |=
850 CMD_IGNORE_RETURN;
851
852 exec_result =
853 execute_command (command->value.Connection->second);
854 }
855 break;
856
857 case OR_OR:
858 if (asynchronous)
859 {
860 /* If we have something like `a || b &', run the || stuff in a
861 subshell. Force a subshell and just call
862 execute_command_internal again. Leave asynchronous on
863 so that we get a report from the parent shell about the
864 background job. */
865 command->flags |= CMD_FORCE_SUBSHELL;
866 exec_result = execute_command_internal (command, 1, pipe_in,
867 pipe_out, fds_to_close);
868 break;
869 }
870
871 /* Execute the first command. If the result of that is successful,
872 then return, otherwise execute the second command. */
873
874 if (command->value.Connection->first)
875 command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
876
877 exec_result = execute_command (command->value.Connection->first);
878 QUIT;
879 if (exec_result != EXECUTION_SUCCESS)
880 {
881 if (ignore_return && command->value.Connection->second)
882 command->value.Connection->second->flags |=
883 CMD_IGNORE_RETURN;
884
885 exec_result =
886 execute_command (command->value.Connection->second);
887 }
888
889 break;
890
891 default:
892 programming_error ("Bad connector `%d'!",
893 command->value.Connection->connector);
894 longjmp (top_level, DISCARD);
895 break;
896 }
897 break;
898
899 case cm_function_def:
900 exec_result = intern_function (command->value.Function_def->name,
901 command->value.Function_def->command);
902 break;
903
904 default:
905 programming_error
906 ("execute_command: Bad command type `%d'!", command->type);
907 }
908
909 if (my_undo_list)
910 {
911 do_redirections (my_undo_list, 1, 0, 0);
912 dispose_redirects (my_undo_list);
913 }
914
915 discard_unwind_frame ("loop_redirections");
916
917 /* Invert the return value if we have to */
918 if (invert)
919 {
920 if (exec_result == EXECUTION_SUCCESS)
921 exec_result = EXECUTION_FAILURE;
922 else
923 exec_result = EXECUTION_SUCCESS;
924 }
925
926 last_command_exit_value = exec_result;
927 run_pending_traps ();
928 return (last_command_exit_value);
929}
930
931/* Execute a FOR command. The syntax is: FOR word_desc IN word_list;
932 DO command; DONE */
933execute_for_command (for_command)
934 FOR_COM *for_command;
935{
936 /* I just noticed that the Bourne shell leaves word_desc bound to the
937 last name in word_list after the FOR statement is done. This seems
938 wrong to me; I thought that the variable binding should be lexically
939 scoped, i.e., only would last the duration of the FOR command. This
940 behaviour can be gotten by turning on the lexical_scoping switch. */
941
942 register WORD_LIST *releaser, *list;
943 WORD_DESC *temp = for_command->name;
944 char *identifier;
945 SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
946 int retval = EXECUTION_SUCCESS;
947 extern int dispose_words ();
948 extern int dispose_variable ();
949
950 if (!check_identifier (temp))
951 return (EXECUTION_FAILURE);
952
953 loop_level++;
954 identifier = temp->word;
955
956 list = releaser = expand_words (for_command->map_list, 0);
957
958 begin_unwind_frame ("for");
959 add_unwind_protect (dispose_words, releaser);
960
961 if (lexical_scoping)
962 {
963 old_value = copy_variable (find_variable (identifier));
964 if (old_value)
965 add_unwind_protect (dispose_variable, old_value);
966 }
967
968 while (list)
969 {
970 QUIT;
971 bind_variable (identifier, list->word->word);
972 if (for_command->flags & CMD_IGNORE_RETURN)
973 for_command->action->flags |= CMD_IGNORE_RETURN;
974 execute_command (for_command->action);
975 retval = last_command_exit_value;
976 QUIT;
977
978 if (breaking)
979 {
980 breaking--;
981 break;
982 }
983
984 if (continuing)
985 {
986 continuing--;
987 if (continuing)
988 break;
989 }
990
991 list = list->next;
992 }
993
994 loop_level--;
995
996 if (lexical_scoping)
997 {
998 if (!old_value)
999 makunbound (identifier, shell_variables);
1000 else
1001 {
1002 SHELL_VAR *new_value;
1003
1004 new_value = bind_variable (identifier, value_cell(old_value));
1005 new_value->attributes = old_value->attributes;
1006 }
1007 }
1008
1009 run_unwind_frame ("for");
1010 return (retval);
1011}
1012
1013/* Execute a CASE command. The syntax is: CASE word_desc IN pattern_list ESAC.
1014 The pattern_list is a linked list of pattern clauses; each clause contains
1015 some patterns to compare word_desc against, and an associated command to
1016 execute. */
1017execute_case_command (case_command)
1018 CASE_COM *case_command;
1019{
1020 extern int dispose_words ();
1021 extern char *tilde_expand ();
1022 register WORD_LIST *list;
1023 WORD_LIST *wlist;
1024 PATTERN_LIST *clauses;
1025 char *word;
1026 int retval;
1027
1028 /* Posix.2 Draft 11.2 says that the word is tilde expanded. */
1029 if (member ('~', case_command->word->word))
1030 {
1031 word = tilde_expand (case_command->word->word);
1032 free (case_command->word->word);
1033 case_command->word->word = word;
1034 }
1035 wlist = expand_word (case_command->word, 0);
1036 clauses = case_command->clauses;
1037 word = (wlist) ? string_list (wlist) : savestring ("");
1038 retval = EXECUTION_SUCCESS;
1039
1040 begin_unwind_frame ("case");
1041 add_unwind_protect (dispose_words, wlist);
1042 add_unwind_protect ((Function *)vfree, word);
1043
1044 while (clauses)
1045 {
1046 QUIT;
1047 list = clauses->patterns;
1048 while (list)
1049 {
1050 extern char *quote_string_for_globbing ();
1051 char *t, *pattern;
1052 WORD_LIST *es;
1053 int match, freepat;
1054
1055 /* Posix.2 draft 11.3 says to do tilde expansion on each member
1056 of the pattern list. */
1057 if (member ('~', list->word->word))
1058 {
1059 t = tilde_expand (list->word->word);
1060 free (list->word->word);
1061 list->word->word = t;
1062 }
1063
1064 es = expand_word_leave_quoted (list->word, 0);
1065 if (es && es->word && es->word->word && *(es->word->word))
1066 {
1067 pattern = quote_string_for_globbing (es->word->word, 1);
1068 freepat = 1;
1069 }
1070 else
1071 {
1072 pattern = "";
1073 freepat = 0;
1074 }
1075
1076 /* Since the pattern does not undergo quote removal according to
1077 Posix.2 section 3.9.4.3, the fnmatch() call must be able to
1078 recognize backslashes as escape characters. */
1079 match = fnmatch (pattern, word, 0) != FNM_NOMATCH;
1080 if (freepat)
1081 free (pattern);
1082 dispose_words (es);
1083
1084 if (match)
1085 {
1086 if (clauses->action &&
1087 (case_command->flags & CMD_IGNORE_RETURN))
1088 clauses->action->flags |= CMD_IGNORE_RETURN;
1089 execute_command (clauses->action);
1090 retval = last_command_exit_value;
1091 goto exit_command;
1092 }
1093
1094 list = list->next;
1095 QUIT;
1096 }
1097 clauses = clauses->next;
1098 }
1099 exit_command:
1100 run_unwind_frame ("case");
1101 return (retval);
1102}
1103
1104#define CMD_WHILE 0
1105#define CMD_UNTIL 1
1106
1107/* The WHILE command. Syntax: WHILE test DO action; DONE.
1108 Repeatedly execute action while executing test produces
1109 EXECUTION_SUCCESS. */
1110execute_while_command (while_command)
1111 WHILE_COM *while_command;
1112{
1113 return (execute_while_or_until (while_command, CMD_WHILE));
1114}
1115
1116/* UNTIL is just like WHILE except that the test result is negated. */
1117execute_until_command (while_command)
1118 WHILE_COM *while_command;
1119{
1120 return (execute_while_or_until (while_command, CMD_UNTIL));
1121}
1122
1123/* The body for both while and until. The only difference between the
1124 two is that the test value is treated differently. TYPE is
1125 CMD_WHILE or CMD_UNTIL. The return value for both commands should
1126 be EXECUTION_SUCCESS if no commands in the body are executed, and
1127 the status of the last command executed in the body otherwise. */
1128execute_while_or_until (while_command, type)
1129 WHILE_COM *while_command;
1130 int type;
1131{
1132 extern int breaking;
1133 extern int continuing;
1134 int commands_executed = 0;
1135 int return_value, body_status = EXECUTION_SUCCESS;
1136
1137 loop_level++;
1138 while_command->test->flags |= CMD_IGNORE_RETURN;
1139
1140 while (1)
1141 {
1142 return_value = execute_command (while_command->test);
1143
1144 if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
1145 break;
1146 if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
1147 break;
1148
1149 QUIT;
1150 commands_executed = 1;
1151
1152 if (while_command->flags & CMD_IGNORE_RETURN)
1153 while_command->action->flags |= CMD_IGNORE_RETURN;
1154 body_status = execute_command (while_command->action);
1155
1156 QUIT;
1157
1158 if (breaking)
1159 {
1160 breaking--;
1161 break;
1162 }
1163
1164 if (continuing)
1165 {
1166 continuing--;
1167 if (continuing)
1168 break;
1169 }
1170 }
1171 loop_level--;
1172
1173 return (body_status);
1174}
1175
1176/* IF test THEN command [ELSE command].
1177 IF also allows ELIF in the place of ELSE IF, but
1178 the parser makes *that* stupidity transparent. */
1179execute_if_command (if_command)
1180 IF_COM *if_command;
1181{
1182 int return_value;
1183
1184 if_command->test->flags |= CMD_IGNORE_RETURN;
1185 return_value = execute_command (if_command->test);
1186
1187 if (return_value == EXECUTION_SUCCESS)
1188 {
1189 QUIT;
1190 if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
1191 if_command->true_case->flags |= CMD_IGNORE_RETURN;
1192 return (execute_command (if_command->true_case));
1193 }
1194 else
1195 {
1196 QUIT;
1197
1198 if (if_command->false_case &&
1199 (if_command->flags & CMD_IGNORE_RETURN))
1200 {
1201 if_command->false_case->flags |= CMD_IGNORE_RETURN;
1202 }
1203
1204 return (execute_command (if_command->false_case));
1205 }
1206}
1207
1208/* The name of the command that is currently being executed.
1209 `test' needs this, for example. */
1210char *this_command_name;
1211
1212static void
1213bind_lastarg (arg)
1214 char *arg;
1215{
1216 SHELL_VAR *var;
1217
1218 if (!arg)
1219 arg = "";
1220 var = bind_variable ("_", arg);
1221 var->attributes &= ~att_exported;
1222}
1223
1224/* For catching RETURN in a function. */
1225int return_catch_flag = 0;
1226int return_catch_value;
1227jmp_buf return_catch;
1228
1229/* The meaty part of all the executions. We have to start hacking the
1230 real execution of commands here. Fork a process, set things up,
1231 execute the command. */
1232execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
1233 SIMPLE_COM *simple_command;
1234 int pipe_in, pipe_out;
1235 struct fd_bitmap *fds_to_close;
1236{
1237 extern int command_string_index, variable_context, line_number;
1238 extern char *the_printed_command;
1239 extern pid_t last_command_subst_pid;
1240 WORD_LIST *expand_words (), *copy_word_list ();
1241 WORD_LIST *words, *lastword;
1242 char *command_line, *lastarg;
1243 int first_word_quoted, result;
1244 pid_t old_last_command_subst_pid;
1245
1246 result = EXECUTION_SUCCESS;
1247
1248 /* If we're in a function, update the pseudo-line-number information. */
1249 if (variable_context)
1250 line_number++;
1251
1252 /* Remember what this command line looks like at invocation. */
1253 command_string_index = 0;
1254 print_simple_command (simple_command);
1255 command_line = (char *)alloca (1 + strlen (the_printed_command));
1256 strcpy (command_line, the_printed_command);
1257
1258 first_word_quoted =
1259 simple_command->words ? simple_command->words->word->quoted : 0;
1260
1261 old_last_command_subst_pid = last_command_subst_pid;
1262
1263 /* If we are re-running this as the result of executing the `command'
1264 builtin, do not expand the command words a second time. */
1265 if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
1266 words = expand_words (simple_command->words);
1267 else
1268 words = copy_word_list (simple_command->words);
1269
1270 lastarg = (char *)NULL;
1271 begin_unwind_frame ("simple-command");
1272
1273 /* It is possible for WORDS not to have anything left in it.
1274 Perhaps all the words consisted of `$foo', and there was
1275 no variable `$foo'. */
1276 if (words)
1277 {
1278 extern int dispose_words ();
1279 extern Function *last_shell_builtin, *this_shell_builtin;
1280 Function *builtin;
1281 SHELL_VAR *func;
1282
1283 if (echo_command_at_execute)
1284 {
1285 extern char *indirection_level_string ();
1286 char *line = string_list (words);
1287
1288 if (line && *line)
1289 fprintf (stderr, "%s%s\n", indirection_level_string (), line);
1290
1291 if (line)
1292 free (line);
1293 }
1294
1295 if (simple_command->flags & CMD_NO_FUNCTIONS)
1296 func = (SHELL_VAR *)NULL;
1297 else
1298 func = find_function (words->word->word);
1299
1300 add_unwind_protect (dispose_words, words);
1301
1302 QUIT;
1303
1304 /* Bind the last word in this command to "$_" after execution. */
1305 for (lastword = words; lastword->next; lastword = lastword->next);
1306 lastarg = lastword->word->word;
1307
1308#if defined (JOB_CONTROL)
1309 /* Is this command a job control related thing? */
1310 if (words->word->word[0] == '%')
1311 {
1312 int result;
1313
1314 if (async)
1315 this_command_name = "bg";
1316 else
1317 this_command_name = "fg";
1318
1319 last_shell_builtin = this_shell_builtin;
1320 this_shell_builtin = builtin_address (this_command_name);
1321 result = (*this_shell_builtin) (words);
1322 goto return_result;
1323 }
1324
1325 /* One other possiblilty. The user may want to resume an existing job.
1326 If they do, find out whether this word is a candidate for a running
1327 job. */
1328 {
1329 char *auto_resume_value;
1330
1331 if ((auto_resume_value = get_string_value ("auto_resume")) &&
1332 !first_word_quoted &&
1333 !words->next &&
1334 words->word->word[0] &&
1335 !simple_command->redirects &&
1336 pipe_in == NO_PIPE &&
1337 pipe_out == NO_PIPE &&
1338 !async)
1339 {
1340 char *word = words->word->word;
1341 register int i, wl = strlen (word), exact;
1342
1343 exact = strcmp (auto_resume_value, "exact") == 0;
1344 for (i = job_slots - 1; i > -1; i--)
1345 {
1346 if (jobs[i])
1347 {
1348 register PROCESS *p = jobs[i]->pipe;
1349 do
1350 {
1351 if ((JOBSTATE (i) == JSTOPPED) &&
1352 (strncmp (p->command, word,
1353 exact ? strlen (p->command) : wl) == 0))
1354 {
1355 int started_status;
1356
1357 run_unwind_frame ("simple-command");
1358 last_shell_builtin = this_shell_builtin;
1359 this_shell_builtin = builtin_address ("fg");
1360
1361 started_status = start_job (i, 1);
1362
1363 if (started_status < 0)
1364 return (EXECUTION_FAILURE);
1365 else
1366 return (started_status);
1367 }
1368 p = p->next;
1369 }
1370 while (p != jobs[i]->pipe);
1371 }
1372 }
1373 }
1374 }
1375#endif /* JOB_CONTROL */
1376
1377 /* Remember the name of this command globally. */
1378 this_command_name = words->word->word;
1379
1380 QUIT;
1381
1382 /* Not a running job. Do normal command processing. */
1383 maybe_make_export_env ();
1384
1385 /* This command could be a shell builtin or a user-defined function.
1386 If so, and we have pipes, then fork a subshell in here. Else, just
1387 do the command. */
1388
1389 if (func)
1390 builtin = (Function *)NULL;
1391 else
1392 builtin = find_shell_builtin (this_command_name);
1393
1394 last_shell_builtin = this_shell_builtin;
1395 this_shell_builtin = builtin;
1396
1397 if (builtin || func)
1398 {
1399 put_command_name_into_env (this_command_name);
1400 if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
1401 {
1402 if (make_child (savestring (command_line), async) == 0)
1403 {
1404 execute_subshell_builtin_or_function
1405 (words, simple_command->redirects, builtin, func,
1406 pipe_in, pipe_out, async, fds_to_close,
1407 simple_command->flags);
1408 }
1409 else
1410 {
1411 close_pipes (pipe_in, pipe_out);
1412 goto return_result;
1413 }
1414 }
1415 else
1416 {
1417 result = execute_builtin_or_function
1418 (words, builtin, func, simple_command->redirects, fds_to_close,
1419 simple_command->flags);
1420
1421 goto return_result;
1422 }
1423 }
1424
1425 execute_disk_command (words, simple_command->redirects, command_line,
1426 pipe_in, pipe_out, async, fds_to_close);
1427
1428 goto return_result;
1429 }
1430 else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
1431 {
1432 /* We have a null command, but we really want a subshell to take
1433 care of it. Just fork, do piping and redirections, and exit. */
1434 if (make_child (savestring (""), async) == 0)
1435 {
1436 do_piping (pipe_in, pipe_out);
1437
1438 subshell_environment = 1;
1439
1440 if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
1441 exit (EXECUTION_SUCCESS);
1442 else
1443 exit (EXECUTION_FAILURE);
1444 }
1445 else
1446 {
1447 close_pipes (pipe_in, pipe_out);
1448 result = EXECUTION_SUCCESS;
1449 goto return_result;
1450 }
1451 }
1452 else
1453 {
1454 /* Even if there aren't any command names, pretend to do the
1455 redirections that are specified. The user expects the side
1456 effects to take place. If the redirections fail, then return
1457 failure. Otherwise, if a command substitution took place while
1458 expanding the command or a redirection, return the value of that
1459 substitution. Otherwise, return EXECUTION_SUCCESS. */
1460
1461 if (do_redirections (simple_command->redirects, 0, 0, 0) != 0)
1462 result = EXECUTION_FAILURE;
1463 else if (old_last_command_subst_pid != last_command_subst_pid)
1464 result = last_command_exit_value;
1465 else
1466 result = EXECUTION_SUCCESS;
1467 }
1468
1469 return_result:
1470 bind_lastarg (lastarg);
1471 run_unwind_frame ("simple-command");
1472 return (result);
1473}
1474
1475/* Execute a shell builtin or function in a subshell environment. This
1476 routine does not return; it only calls exit(). If BUILTIN is non-null,
1477 it points to a function to call to execute a shell builtin; otherwise
1478 VAR points at the body of a function to execute. WORDS is the arguments
1479 to the command, REDIRECTS specifies redirections to perform before the
1480 command is executed. */
1481static void
1482execute_subshell_builtin_or_function (words, redirects, builtin, var,
1483 pipe_in, pipe_out, async, fds_to_close,
1484 flags)
1485 WORD_LIST *words;
1486 REDIRECT *redirects;
1487 Function *builtin;
1488 SHELL_VAR *var;
1489 int pipe_in, pipe_out, async;
1490 struct fd_bitmap *fds_to_close;
1491 int flags;
1492{
1493 extern char **temporary_env, **function_env, **copy_array ();
1494 extern int login_shell, interactive;
1495#if defined (JOB_CONTROL)
1496 extern int jobs_builtin ();
1497#endif /* JOB_CONTROL */
1498
1499 /* A subshell is neither a login shell nor interactive. */
1500 login_shell = interactive = 0;
1501
1502 subshell_environment = 1;
1503
1504#if defined (JOB_CONTROL)
1505 /* Eradicate all traces of job control after we fork the subshell, so
1506 all jobs begun by this subshell are in the same process group as
1507 the shell itself. */
1508
1509 /* Allow the output of `jobs' to be piped. */
1510 if (builtin == jobs_builtin && !async &&
1511 (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
1512 kill_current_pipeline ();
1513 else
1514 without_job_control ();
1515
1516 set_sigchld_handler ();
1517#endif /* JOB_CONTROL */
1518
1519 set_sigint_handler ();
1520
1521 do_piping (pipe_in, pipe_out);
1522
1523 if (fds_to_close)
1524 close_fd_bitmap (fds_to_close);
1525
1526 if (do_redirections (redirects, 1, 0, 0) != 0)
1527 exit (EXECUTION_FAILURE);
1528
1529 if (builtin)
1530 {
1531 extern jmp_buf top_level;
1532 int result;
1533
1534 /* Give builtins a place to jump back to on failure,
1535 so we don't go back up to main(). */
1536 result = setjmp (top_level);
1537
1538 if (result == EXITPROG)
1539 exit (last_command_exit_value);
1540 else if (result)
1541 exit (EXECUTION_FAILURE);
1542 else
1543 exit ((*builtin) (words->next));
1544 }
1545 else
1546 {
1547 extern int variable_context, line_number;
1548 extern void dispose_command (), dispose_function_env ();
1549 COMMAND *fc, *tc;
1550 int result, return_val;
1551
1552 tc = (COMMAND *)function_cell (var);
1553 fc = (COMMAND *)NULL;
1554
1555 remember_args (words->next, 1);
1556 line_number = 0;
1557#if defined (JOB_CONTROL)
1558 stop_pipeline (async, (COMMAND *)NULL);
1559#endif
1560
1561 begin_unwind_frame ("subshell_function_calling");
1562 unwind_protect_int (variable_context);
1563 unwind_protect_int (return_catch_flag);
1564 unwind_protect_jmp_buf (return_catch);
1565 add_unwind_protect (dispose_command, fc);
1566
1567 /* The temporary environment for a function is supposed to apply to
1568 all commands executed in the function. If we have a temporary
1569 environment, copy it to the special `function environment' and
1570 get rid of the temporary environment. */
1571 if (temporary_env)
1572 {
1573 function_env = copy_array (temporary_env);
1574 add_unwind_protect (dispose_function_env, (char *)NULL);
1575 dispose_used_env_vars ();
1576 }
1577 else
1578 function_env = (char **)NULL;
1579
1580 /* We can do this because function bodies are always guaranteed to
1581 be group commands, according to the grammar in parse.y. If we
1582 don't do this now, execute_command_internal will graciously fork
1583 another subshell for us, and we'll lose contact with the rest of
1584 the pipeline and fail to get any SIGPIPE that might be sent. */
1585
1586 if (tc->type == cm_group)
1587 fc = (COMMAND *)copy_command (tc->value.Group->command);
1588 else
1589 fc = (COMMAND *)copy_command (tc);
1590
1591 if (fc && (flags & CMD_IGNORE_RETURN))
1592 fc->flags |= CMD_IGNORE_RETURN;
1593
1594 /* result = execute_command (fc); doesn't work.
1595 We need to explicitly specify the pipes in and out so that they
1596 are closed in all the processes that rely on their being closed.
1597 If they are not, it is possible to not get the SIGPIPE that we
1598 need to kill all the processes sharing the pipe. */
1599
1600 variable_context++;
1601 return_catch_flag++;
1602 return_val = setjmp (return_catch);
1603
1604 if (return_val)
1605 result = return_catch_value;
1606 else
1607 result =
1608 execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
1609
1610 run_unwind_frame ("subshell_function_calling");
1611
1612 exit (result);
1613 }
1614}
1615
1616/* Execute a builtin or function in the current shell context. If BUILTIN
1617 is non-null, it is the builtin command to execute, otherwise VAR points
1618 to the body of a function. WORDS are the command's arguments, REDIRECTS
1619 are the redirections to perform. FDS_TO_CLOSE is the usual bitmap of
1620 file descriptors to close.
1621
1622 If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
1623 not undone before this function returns. */
1624static int
1625execute_builtin_or_function (words, builtin, var, redirects,
1626 fds_to_close, flags)
1627 WORD_LIST *words;
1628 Function *builtin;
1629 SHELL_VAR *var;
1630 REDIRECT *redirects;
1631 struct fd_bitmap *fds_to_close;
1632 int flags;
1633{
1634 extern int exec_builtin (), eval_builtin ();
1635 extern char **temporary_env, **function_env, **copy_array ();
1636 int result = EXECUTION_FAILURE;
1637 REDIRECT *saved_undo_list;
1638
1639 if (do_redirections (redirects, 1, 1, 0) != 0)
1640 return (EXECUTION_FAILURE);
1641
1642 saved_undo_list = redirection_undo_list;
1643
1644 /* Calling the "exec" builtin changes redirections forever. */
1645 if (builtin == exec_builtin)
1646 {
1647 dispose_redirects (saved_undo_list);
1648 saved_undo_list = (REDIRECT *)NULL;
1649 }
1650 else
1651 {
1652 begin_unwind_frame ("saved redirects");
1653 add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
1654 }
1655
1656 redirection_undo_list = (REDIRECT *)NULL;
1657
1658 if (builtin)
1659 {
1660 int old_e_flag = exit_immediately_on_error;
1661
1662 /* The eval builtin calls parse_and_execute, which does not know about
1663 the setting of flags, and always calls the execution functions with
1664 flags that will exit the shell on an error if -e is set. If the
1665 eval builtin is being called, and we're supposed to ignore the exit
1666 value of the command, we turn the -e flag off ourselves, then
1667 restore it when the command completes. */
1668 if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
1669 {
1670 begin_unwind_frame ("eval_builtin");
1671 unwind_protect_int (exit_immediately_on_error);
1672 exit_immediately_on_error = 0;
1673 }
1674
1675 result = ((*builtin) (words->next));
1676
1677 if ((builtin == eval_builtin) && (flags & CMD_IGNORE_RETURN))
1678 {
1679 exit_immediately_on_error += old_e_flag;
1680 discard_unwind_frame ("eval_builtin");
1681 }
1682 }
1683 else
1684 {
1685 extern void dispose_command (), dispose_function_env ();
1686 extern int pop_context ();
1687 extern int line_number;
1688 int return_val;
1689 COMMAND *tc;
1690
1691 tc = (COMMAND *)copy_command (function_cell (var));
1692 if (tc && (flags & CMD_IGNORE_RETURN))
1693 tc->flags |= CMD_IGNORE_RETURN;
1694
1695 begin_unwind_frame ("function_calling");
1696 push_context ();
1697 add_unwind_protect (pop_context, (char *)NULL);
1698 add_unwind_protect (dispose_command, (char *)tc);
1699 unwind_protect_int (return_catch_flag);
1700 unwind_protect_int (line_number);
1701 unwind_protect_jmp_buf (return_catch);
1702
1703 /* The temporary environment for a function is supposed to apply to
1704 all commands executed in the function. If we have a temporary
1705 environment, copy it to the special `function environment' and
1706 get rid of the temporary environment. */
1707 if (temporary_env)
1708 {
1709 function_env = copy_array (temporary_env);
1710 add_unwind_protect (dispose_function_env, (char *)NULL);
1711 dispose_used_env_vars ();
1712 }
1713 else
1714 function_env = (char **)NULL;
1715
1716 /* Note the second argument of "1", meaning that we discard
1717 the current value of "$*"! This is apparently the right thing. */
1718 remember_args (words->next, 1);
1719
1720 line_number = 0;
1721 return_catch_flag++;
1722 return_val = setjmp (return_catch);
1723
1724 if (return_val)
1725 result = return_catch_value;
1726 else
1727 result =
1728 execute_command_internal (tc, 0, NO_PIPE, NO_PIPE, fds_to_close);
1729
1730 run_unwind_frame ("function_calling");
1731 }
1732
1733 redirection_undo_list = saved_undo_list;
1734 if (builtin != exec_builtin)
1735 discard_unwind_frame ("saved redirects");
1736 do_redirections (redirection_undo_list, 1, 0, 0);
1737
1738 return (result);
1739}
1740
1741/* Execute a simple command that is hopefully defined in a disk file
1742 somewhere.
1743
1744 1) fork ()
1745 2) connect pipes
1746 3) look up the command
1747 4) do redirections
1748 5) execve ()
1749 6) If the execve failed, see if the file has executable mode set.
1750 If so, and it isn't a directory, then execute its contents as
1751 a shell script.
1752
1753 Note that the filename hashing stuff has to take place up here,
1754 in the parent. This is probably why the Bourne style shells
1755 don't handle it, since that would require them to go through
1756 this gnarly hair, for no good reason. */
1757static void
1758execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
1759 async, fds_to_close)
1760 WORD_LIST *words;
1761 REDIRECT *redirects;
1762 char *command_line;
1763 int pipe_in, pipe_out, async;
1764 struct fd_bitmap *fds_to_close;
1765{
1766 char **make_word_array (), *find_user_command (), *find_hashed_filename ();
1767 char *hashed_file, *command, **args;
1768
1769#if defined (RESTRICTED_SHELL)
1770 extern int restricted;
1771
1772 if (restricted && strchr (words->word->word, '/'))
1773 {
1774 report_error ("%s: restricted: cannot specify `/' in command names",
1775 words->word->word);
1776 last_command_exit_value = EXECUTION_FAILURE;
1777 return;
1778 }
1779#endif /* RESTRICTED_SHELL */
1780
1781 hashed_file = command = (char *)NULL;
1782
1783 /* Don't waste time trying to find hashed data for a pathname
1784 that is already completely specified. */
1785
1786 if (!absolute_program (words->word->word))
1787 hashed_file = find_hashed_filename (words->word->word);
1788
1789 /* XXX - this could be a big performance hit... */
1790 /* If a command found in the hash table no longer exists, we need to
1791 look for it in $PATH. */
1792 if (hashed_file)
1793 {
1794 int st;
1795
1796 st = file_status (hashed_file);
1797 if ((st & (FS_EXISTS | FS_EXECABLE)) != (FS_EXISTS | FS_EXECABLE))
1798 {
1799 remove_hashed_filename (words->word->word);
1800 hashed_file = (char *) NULL;
1801 }
1802 }
1803
1804 if (hashed_file)
1805 command = savestring (hashed_file);
1806 else
1807 {
1808 /* A command containing a slash is not looked up in PATH. */
1809 if (absolute_program (words->word->word))
1810 command = savestring (words->word->word);
1811 else
1812 {
1813 command = find_user_command (words->word->word);
1814
1815 /* A command name containing a slash is not saved in the
1816 hash table. */
1817 if (command && !hashing_disabled)
1818 {
1819 extern int dot_found_in_search;
1820
1821 remember_filename
1822 (words->word->word, command, dot_found_in_search);
1823
1824 /* Increase the number of hits to 1. */
1825 find_hashed_filename (words->word->word);
1826 }
1827 }
1828 }
1829
1830 if (command)
1831 put_command_name_into_env (command);
1832
1833 /* We have to make the child before we check for the non-existance
1834 of COMMAND, since we want the error messages to be redirected. */
1835 if (make_child (savestring (command_line), async) == 0)
1836 {
1837 do_piping (pipe_in, pipe_out);
1838
1839 /* Execve expects the command name to be in args[0]. So we
1840 leave it there, in the same format that the user used to
1841 type it in. */
1842 args = make_word_array (words);
1843
1844 if (async)
1845 {
1846 begin_unwind_frame ("async_redirections");
1847 unwind_protect_int (interactive);
1848 interactive = 0;
1849 }
1850
1851 subshell_environment = 1;
1852
1853 if (do_redirections (redirects, 1, 0, 0) != 0)
1854 {
1855#if defined (PROCESS_SUBSTITUTION)
1856 /* Try to remove named pipes that may have been created as the
1857 result of redirections. */
1858 unlink_fifo_list ();
1859#endif /* PROCESS_SUBSTITUTION */
1860 exit (EXECUTION_FAILURE);
1861 }
1862
1863 if (async)
1864 run_unwind_frame ("async_redirections");
1865
1866 if (!command)
1867 {
1868 report_error ("%s: command not found", args[0]);
1869 exit (EXECUTION_FAILURE);
1870 }
1871
1872 /* This functionality is now provided by close-on-exec of the
1873 file descriptors manipulated by redirection and piping.
1874 Some file descriptors still need to be closed in all children
1875 because of the way bash does pipes; fds_to_close is a
1876 bitmap of all such file descriptors. */
1877 if (fds_to_close)
1878 close_fd_bitmap (fds_to_close);
1879
1880 exit (shell_execve (command, args, export_env));
1881 }
1882 else
1883 {
1884 /* Make sure that the pipes are closed in the parent. */
1885 close_pipes (pipe_in, pipe_out);
1886 if (command)
1887 free (command);
1888 }
1889}
1890
1891/* If the operating system on which we're running does not handle
1892 the #! executable format, then help out. SAMPLE is the text read
1893 from the file, SAMPLE_LEN characters. COMMAND is the name of
1894 the script; it and ARGS, the arguments given by the user, will
1895 become arguments to the specified interpreter. ENV is the environment
1896 to pass to the interpreter.
1897
1898 The word immediately following the #! is the interpreter to execute.
1899 A single argument to the interpreter is allowed. */
1900static int
1901execute_shell_script (sample, sample_len, command, args, env)
1902 unsigned char *sample;
1903 int sample_len;
1904 char *command;
1905 char **args, **env;
1906{
1907 extern char *shell_name;
1908 register int i;
1909 char *execname, *firstarg;
1910 int start, size_increment, larry;
1911
1912 /* Find the name of the interpreter to exec. */
1913 for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
1914 ;
1915
1916 for (start = i;
1917 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
1918 i++)
1919 ;
1920
1921 execname = (char *)xmalloc (1 + (i - start));
1922 strncpy (execname, sample + start, i - start);
1923 execname[i - start] = '\0';
1924 size_increment = 1;
1925
1926 /* Now the argument, if any. */
1927 firstarg = (char *)NULL;
1928 for (start = i;
1929 whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
1930 i++)
1931 ;
1932
1933 /* If there is more text on the line, then it is an argument for the
1934 interpreter. */
1935 if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
1936 {
1937 for (start = i;
1938 !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
1939 i++)
1940 ;
1941 firstarg = (char *)xmalloc (1 + (i - start));
1942 strncpy (firstarg, sample + start, i - start);
1943 firstarg[i - start] = '\0';
1944
1945 size_increment = 2;
1946 }
1947
1948 larry = array_len (args) + size_increment;
1949
1950 args = (char **)xrealloc (args, (1 + larry) * sizeof (char *));
1951
1952 for (i = larry - 1; i; i--)
1953 args[i] = args[i - size_increment];
1954
1955 args[0] = execname;
1956 if (firstarg)
1957 {
1958 args[1] = firstarg;
1959 args[2] = command;
1960 }
1961 else
1962 args[1] = command;
1963
1964 args[larry] = (char *)NULL;
1965
1966 return (shell_execve (execname, args, env));
1967}
1968
1969/* Call execve (), handling interpreting shell scripts, and handling
1970 exec failures. */
1971int
1972shell_execve (command, args, env)
1973 char *command;
1974 char **args, **env;
1975{
1976#if defined (isc386) && defined (_POSIX_SOURCE)
1977 __setostype (0); /* Turn on USGr3 semantics. */
1978 execve (command, args, env);
1979 __setostype (1); /* Turn the POSIX semantics back on. */
1980#else
1981 execve (command, args, env);
1982#endif /* !(isc386 && _POSIX_SOURCE) */
1983
1984 /* If we get to this point, then start checking out the file.
1985 Maybe it is something we can hack ourselves. */
1986 {
1987 struct stat finfo;
1988
1989 if (errno != ENOEXEC)
1990 {
1991 if ((stat (command, &finfo) == 0) &&
1992 (S_ISDIR (finfo.st_mode)))
1993 report_error ("%s: is a directory", args[0]);
1994 else
1995 file_error (command);
1996
1997 return (EXECUTION_FAILURE);
1998 }
1999 else
2000 {
2001 /* This file is executable.
2002 If it begins with #!, then help out people with losing operating
2003 systems. Otherwise, check to see if it is a binary file by seeing
2004 if the first line (or up to 30 characters) are in the ASCII set.
2005 Execute the contents as shell commands. */
2006 extern char *shell_name;
2007 int larray = array_len (args) + 1;
2008 int i, should_exec = 0;
2009
2010 {
2011 int fd = open (command, O_RDONLY);
2012 if (fd != -1)
2013 {
2014 unsigned char sample[80];
2015 int sample_len = read (fd, &sample[0], 80);
2016
2017 close (fd);
2018
2019 if (sample_len == 0)
2020 return (EXECUTION_SUCCESS);
2021
2022 /* Is this supposed to be an executable script? */
2023 /* If so, the format of the line is "#! interpreter [argument]".
2024 A single argument is allowed. The BSD kernel restricts
2025 the length of the entire line to 32 characters (32 bytes
2026 being the size of the BSD exec header), but we allow 80
2027 characters. */
2028
2029 if (sample_len > 0 && sample[0] == '#' && sample[1] == '!')
2030 return (execute_shell_script (sample, sample_len, command,
2031 args, env));
2032#if defined (NOTDEF)
2033#if defined (HAVE_CSH) && ( defined (Bsd) || defined (Ultrix) )
2034 /* If this system has Csh, then keep the old
2035 BSD semantics. */
2036 else if (sample_len > 0 && sample[0] == '#')
2037 {
2038 /* Scripts starting with a # are for Csh. */
2039 shell_name = savestring ("/bin/csh");
2040 should_exec = 1;
2041 }
2042#endif /* HAVE_CSH */
2043#endif /* NOTDEF */
2044 else if ((sample_len != -1) &&
2045 check_binary_file (sample, sample_len))
2046 {
2047 report_error ("%s: cannot execute binary file", command);
2048 return (EX_BINARY_FILE);
2049 }
2050 }
2051 }
2052#if defined (JOB_CONTROL)
2053 /* Forget about the way that job control was working. We are
2054 in a subshell. */
2055 without_job_control ();
2056#endif /* JOB_CONTROL */
2057#if defined (ALIAS)
2058 /* Forget about any aliases that we knew of. We are in a subshell. */
2059 delete_all_aliases ();
2060#endif /* ALIAS */
2061
2062#if defined (JOB_CONTROL)
2063 set_sigchld_handler ();
2064#endif /* JOB_CONTROL */
2065 set_sigint_handler ();
2066
2067 /* Insert the name of this shell into the argument list. */
2068 args = (char **)xrealloc (args, (1 + larray) * sizeof (char *));
2069
2070 for (i = larray - 1; i; i--)
2071 args[i] = args[i - 1];
2072
2073 args[0] = shell_name;
2074 args[1] = command;
2075 args[larray] = (char *)NULL;
2076
2077 if (args[0][0] == '-')
2078 args[0]++;
2079
2080 if (should_exec)
2081 {
2082 struct stat finfo;
2083
2084#if defined (isc386) && defined (_POSIX_SOURCE)
2085 __setostype (0); /* Turn on USGr3 semantics. */
2086 execve (shell_name, args, env);
2087 __setostype (1); /* Turn the POSIX semantics back on. */
2088#else
2089 execve (shell_name, args, env);
2090#endif /* isc386 && _POSIX_SOURCE */
2091
2092 /* Oh, no! We couldn't even exec this! */
2093 if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
2094 report_error ("%s: is a directory", args[0]);
2095 else
2096 file_error (args[0]);
2097
2098 return (EXECUTION_FAILURE);
2099 }
2100 else
2101 {
2102 extern jmp_buf subshell_top_level;
2103 extern int subshell_argc;
2104 extern char **subshell_argv;
2105 extern char **subshell_envp;
2106
2107 subshell_argc = larray;
2108 subshell_argv = args;
2109 subshell_envp = env;
2110 longjmp (subshell_top_level, 1);
2111 }
2112 }
2113 }
2114}
2115
2116#if defined (PROCESS_SUBSTITUTION)
2117void
2118close_all_files ()
2119{
2120 register int i, fd_table_size;
2121
2122 fd_table_size = getdtablesize ();
2123
2124 for (i = 3; i < fd_table_size; i++)
2125 close (i);
2126}
2127#endif /* PROCESS_SUBSTITUTION */
2128
2129static void
2130close_pipes (in, out)
2131 int in, out;
2132{
2133 if (in >= 0) close (in);
2134 if (out >= 0) close (out);
2135}
2136
2137/* Redirect input and output to be from and to the specified pipes.
2138 NO_PIPE and REDIRECT_BOTH are handled correctly. */
2139static void
2140do_piping (pipe_in, pipe_out)
2141 int pipe_in, pipe_out;
2142{
2143 if (pipe_in != NO_PIPE)
2144 {
2145 dup2 (pipe_in, 0);
2146 close (pipe_in);
2147 }
2148 if (pipe_out != NO_PIPE)
2149 {
2150 dup2 (pipe_out, 1);
2151 close (pipe_out);
2152
2153 if (pipe_out == REDIRECT_BOTH)
2154 dup2 (1, 2);
2155 }
2156}
2157
2158/* Defined in flags.c. Non-zero means don't overwrite existing files. */
2159extern int noclobber;
2160
2161#define AMBIGUOUS_REDIRECT -1
2162#define NOCLOBBER_REDIRECT -2
2163#define RESTRICTED_REDIRECT -3 /* Only can happen in restricted shells. */
2164
2165/* Perform the redirections on LIST. If FOR_REAL, then actually make
2166 input and output file descriptors, otherwise just do whatever is
2167 neccessary for side effecting. INTERNAL says to remember how to
2168 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
2169 file descriptors opened in do_redirection () have their close-on-exec
2170 flag set. */
2171static int
2172do_redirections (list, for_real, internal, set_clexec)
2173 REDIRECT *list;
2174 int for_real, internal;
2175{
2176 register int error;
2177 register REDIRECT *temp = list;
2178
2179 if (internal && redirection_undo_list)
2180 {
2181 dispose_redirects (redirection_undo_list);
2182 redirection_undo_list = (REDIRECT *)NULL;
2183 }
2184
2185 while (temp)
2186 {
2187 extern char *strerror ();
2188
2189 error = do_redirection_internal (temp, for_real, internal, set_clexec);
2190
2191 if (error)
2192 {
2193 char *redirection_expand (), *itos ();
2194 char *filename;
2195
2196 if (expandable_redirection_filename (temp))
2197 {
2198 filename = redirection_expand (temp->redirectee.filename);
2199 if (!filename)
2200 filename = savestring ("");
2201 }
2202 else
2203 filename = itos (temp->redirectee.dest);
2204
2205 switch (error)
2206 {
2207 case AMBIGUOUS_REDIRECT:
2208 report_error ("%s: Ambiguous redirect", filename);
2209 break;
2210
2211 case NOCLOBBER_REDIRECT:
2212 report_error ("%s: Cannot clobber existing file", filename);
2213 break;
2214
2215#if defined (RESTRICTED_SHELL)
2216 case RESTRICTED_REDIRECT:
2217 report_error ("%s: output redirection restricted", filename);
2218 break;
2219#endif /* RESTRICTED_SHELL */
2220
2221 default:
2222 report_error ("%s: %s", filename, strerror (error));
2223 break;
2224 }
2225
2226 free (filename);
2227 return (error);
2228 }
2229
2230 temp = temp->next;
2231 }
2232 return (0);
2233}
2234
2235/* Return non-zero if the redirection pointed to by REDIRECT has a
2236 redirectee.filename that can be expanded. */
2237static int
2238expandable_redirection_filename (redirect)
2239 REDIRECT *redirect;
2240{
2241 int result;
2242
2243 switch (redirect->instruction)
2244 {
2245 case r_output_direction:
2246 case r_appending_to:
2247 case r_input_direction:
2248 case r_inputa_direction:
2249 case r_err_and_out:
2250 case r_input_output:
2251 case r_output_force:
2252 case r_duplicating_input_word:
2253 case r_duplicating_output_word:
2254 result = 1;
2255 break;
2256
2257 default:
2258 result = 0;
2259 }
2260 return (result);
2261}
2262\f
2263/* Expand the word in WORD returning a string. If WORD expands to
2264 multiple words (or no words), then return NULL. */
2265char *
2266redirection_expand (word)
2267 WORD_DESC *word;
2268{
2269 char *result;
2270 WORD_LIST *make_word_list (), *expand_words_no_vars ();
2271 WORD_LIST *tlist1, *tlist2;
2272
2273 tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
2274 tlist2 = expand_words_no_vars (tlist1);
2275 dispose_words (tlist1);
2276
2277 if (!tlist2 || tlist2->next)
2278 {
2279 /* We expanded to no words, or to more than a single word.
2280 Dispose of the word list and return NULL. */
2281 if (tlist2)
2282 dispose_words (tlist2);
2283 return ((char *)NULL);
2284 }
2285 result = string_list (tlist2);
2286 dispose_words (tlist2);
2287
2288 return (result);
2289}
2290
2291/* Do the specific redirection requested. Returns errno in case of error.
2292 If FOR_REAL is zero, then just do whatever is neccessary to produce the
2293 appropriate side effects. REMEMBERING, if non-zero, says to remember
2294 how to undo each redirection. If SET_CLEXEC is non-zero, then
2295 we set all file descriptors > 2 that we open to be close-on-exec. */
2296static int
2297do_redirection_internal (redirect, for_real, remembering, set_clexec)
2298 REDIRECT *redirect;
2299 int for_real, remembering;
2300{
2301 WORD_DESC *redirectee = redirect->redirectee.filename;
2302 int fd, redirector = redirect->redirector;
2303 char *redirectee_word;
2304 enum r_instruction ri = redirect->instruction;
2305 REDIRECT *new_redirect;
2306
2307 if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
2308 {
2309 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
2310 the redirection into a new one and continue. */
2311 redirectee_word = redirection_expand (redirectee);
2312
2313 if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
2314 {
2315 new_redirect = make_redirection (redirector, r_close_this, 0);
2316 }
2317 else if (all_digits (redirectee_word))
2318 {
2319 if (ri == r_duplicating_input_word)
2320 {
2321 new_redirect = make_redirection
2322 (redirector, r_duplicating_input, atoi (redirectee_word));
2323 }
2324 else
2325 {
2326 new_redirect = make_redirection
2327 (redirector, r_duplicating_output, atoi (redirectee_word));
2328 }
2329 }
2330 else if (ri == r_duplicating_output_word && redirector == 1)
2331 {
2332 new_redirect = make_redirection
2333 (1, r_err_and_out, make_word (redirectee_word));
2334 }
2335 else
2336 {
2337 free (redirectee_word);
2338 return (AMBIGUOUS_REDIRECT);
2339 }
2340
2341 free (redirectee_word);
2342
2343 /* Set up the variables needed by the rest of the function from the
2344 new redirection. */
2345 if (new_redirect->instruction == r_err_and_out)
2346 {
2347 char *alloca_hack;
2348
2349 /* Copy the word without allocating any memory that must be
2350 explicitly freed. */
2351 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
2352 bcopy (new_redirect->redirectee.filename,
2353 redirectee, sizeof (WORD_DESC));
2354
2355 alloca_hack = (char *)
2356 alloca (1 + strlen (new_redirect->redirectee.filename->word));
2357 redirectee->word = alloca_hack;
2358 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
2359 }
2360 else
2361 /* It's guaranteed to be an integer, and shouldn't be freed. */
2362 redirectee = new_redirect->redirectee.filename;
2363
2364 redirector = new_redirect->redirector;
2365 ri = new_redirect->instruction;
2366
2367 /* Overwrite the flags element of the old redirect with the new value. */
2368 redirect->flags = new_redirect->flags;
2369 dispose_redirects (new_redirect);
2370 }
2371
2372 switch (ri)
2373 {
2374 case r_output_direction:
2375 case r_appending_to:
2376 case r_input_direction:
2377 case r_inputa_direction:
2378 case r_err_and_out: /* command &>filename */
2379 case r_input_output:
2380 case r_output_force:
2381
2382 if (!(redirectee_word = redirection_expand (redirectee)))
2383 return (AMBIGUOUS_REDIRECT);
2384
2385#if defined (RESTRICTED_SHELL)
2386 if (restricted && (ri == r_output_direction ||
2387 ri == r_input_output ||
2388 ri == r_err_and_out ||
2389 ri == r_appending_to ||
2390 ri == r_output_force))
2391 {
2392 free(redirectee_word);
2393 return (RESTRICTED_REDIRECT);
2394 }
2395#endif /* RESTRICTED_SHELL */
2396
2397 /* If we are in noclobber mode, you are not allowed to overwrite
2398 existing files. Check first. */
2399 if (noclobber && (ri == r_output_direction ||
2400 ri == r_input_output ||
2401 ri == r_err_and_out))
2402 {
2403 struct stat buf;
2404 int stat_result;
2405
2406 stat_result = stat (redirectee_word, &buf);
2407 if ((stat_result == 0) && (S_ISREG (buf.st_mode)))
2408 {
2409 free (redirectee_word);
2410 return (NOCLOBBER_REDIRECT);
2411 }
2412 /* If the file was not there, make sure we use exclusive open so
2413 that if it's created before we open it, our open will fail. */
2414 if (stat_result != 0)
2415 redirect->flags |= O_EXCL;
2416 fd = open (redirectee_word, redirect->flags, 0666);
2417 if (fd < 0 && errno == EEXIST)
2418 {
2419 free (redirectee_word);
2420 return (NOCLOBBER_REDIRECT);
2421 }
2422 }
2423 else
2424 {
2425 fd = open (redirectee_word, redirect->flags, 0666);
2426#if defined (AFS_CREATE_BUG)
2427 if (fd < 0 && errno == EACCES)
2428 fd = open (redirectee_word, (redirect->flags & ~O_CREAT), 0666);
2429#endif /* AFS_CREATE_BUG */
2430 }
2431
2432 free (redirectee_word);
2433
2434 if (fd < 0 )
2435 return (errno);
2436
2437 if (for_real)
2438 {
2439 if (remembering)
2440 /* Only setup to undo it if the thing to undo is active. */
2441 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
2442 add_undo_redirect (redirector);
2443 else
2444 add_undo_close_redirect (redirector);
2445
2446 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
2447 return (errno);
2448
2449#if defined (BUFFERED_INPUT)
2450 if (ri == r_input_direction || ri == r_inputa_direction ||
2451 ri == r_input_output)
2452 duplicate_buffered_stream (fd, redirector);
2453#endif /* BUFFERED_INPUT */
2454
2455 /*
2456 * If we're remembering, then this is the result of a while, for
2457 * or until loop with a loop redirection, or a function/builtin
2458 * executing in the parent shell with a redirection. In the
2459 * function/builtin case, we want to set all file descriptors > 2
2460 * to be close-on-exec to duplicate the effect of the old
2461 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
2462 * both sh and ksh leave the file descriptors open across execs.
2463 * The Posix standard mentions only the exec builtin.
2464 */
2465 if (set_clexec && (redirector > 2))
2466 SET_CLOSE_ON_EXEC (redirector);
2467 }
2468
2469 if (fd != redirector)
2470 {
2471#if defined (BUFFERED_INPUT)
2472 if (ri == r_input_direction || ri == r_inputa_direction ||
2473 ri == r_input_output)
2474 close_buffered_fd (fd);
2475 else
2476#endif /* !BUFFERED_INPUT */
2477 close (fd); /* Don't close what we just opened! */
2478 }
2479
2480 /* If we are hacking both stdout and stderr, do the stderr
2481 redirection here. */
2482 if (ri == r_err_and_out)
2483 {
2484 if (for_real)
2485 {
2486 if (remembering)
2487 add_undo_redirect (2);
2488 if (dup2 (1, 2) < 0)
2489 return (errno);
2490 }
2491 }
2492 break;
2493
2494 case r_reading_until:
2495 case r_deblank_reading_until:
2496 {
2497 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
2498 the new input. Place it in a temporary file. */
2499 int document_index = 0;
2500 char *document = (char *)NULL;
2501
2502 /* Expand the text if the word that was specified had no quoting.
2503 Note that the text that we expand is treated exactly as if it
2504 were surrounded by double-quotes. */
2505
2506 if (!redirectee)
2507 document = savestring ("");
2508 else
2509 {
2510 if (!redirectee->quoted)
2511 {
2512 WORD_LIST *temp_word_list =
2513 (WORD_LIST *)expand_string (redirectee->word,
2514 Q_HERE_DOCUMENT);
2515
2516 document = string_list (temp_word_list);
2517 if (!document)
2518 document = savestring ("");
2519 dispose_words (temp_word_list);
2520 }
2521 else
2522 {
2523 document = redirectee->word;
2524 }
2525 document_index = strlen (document);
2526
2527 {
2528 char filename[40];
2529 pid_t pid = getpid ();
2530
2531 /* Make the filename for the temp file. */
2532 sprintf (filename, "/tmp/t%d-sh", pid);
2533
2534 fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
2535 if (fd < 0)
2536 {
2537 if (!redirectee->quoted)
2538 free (document);
2539 return (errno);
2540 }
2541
2542 write (fd, document, document_index);
2543 close (fd);
2544
2545 if (!redirectee->quoted)
2546 free (document);
2547
2548 /* Make the document really temporary. Also make it the
2549 input. */
2550 fd = open (filename, O_RDONLY, 0666);
2551
2552 if (unlink (filename) < 0 || fd < 0)
2553 return (errno);
2554
2555 if (for_real)
2556 {
2557 if (remembering)
2558 /* Only setup to undo it if the thing to undo is active. */
2559 if ((fd != redirector) &&
2560 (fcntl (redirector, F_GETFD, 0) != -1))
2561 add_undo_redirect (redirector);
2562 else
2563 add_undo_close_redirect (redirector);
2564
2565 if (dup2 (fd, redirector) < 0)
2566 return (errno);
2567
2568#if defined (BUFFERED_INPUT)
2569 duplicate_buffered_stream (fd, redirector);
2570#endif
2571
2572 if (set_clexec && (redirector > 2))
2573 SET_CLOSE_ON_EXEC (redirector);
2574 }
2575
2576#if defined (BUFFERED_INPUT)
2577 close_buffered_fd (fd);
2578#else
2579 close (fd);
2580#endif
2581 }
2582 }
2583 }
2584 break;
2585
2586 case r_duplicating_input:
2587 case r_duplicating_output:
2588 if (for_real && ((int)redirectee != redirector))
2589 {
2590 if (remembering)
2591 /* Only setup to undo it if the thing to undo is active. */
2592 if (fcntl (redirector, F_GETFD, 0) != -1)
2593 add_undo_redirect (redirector);
2594 else
2595 add_undo_close_redirect (redirector);
2596
2597 /* This is correct. 2>&1 means dup2 (1, 2); */
2598 if (dup2 ((int)redirectee, redirector) < 0)
2599 return (errno);
2600
2601#if defined (BUFFERED_INPUT)
2602 if (ri == r_duplicating_input)
2603 duplicate_buffered_stream ((int)redirectee, redirector);
2604#endif /* BUFFERED_INPUT */
2605
2606 /* First duplicate the close-on-exec state of redirectee. dup2
2607 leaves the flag unset on the new descriptor, which means it
2608 stays open. Only set the close-on-exec bit for file descriptors
2609 greater than 2 in any case, since 0-2 should always be open
2610 unless closed by something like `exec 2<&-'. */
2611 /* if ((already_set || set_unconditionally) && (ok_to_set))
2612 set_it () */
2613 if (((fcntl ((int)redirectee, F_GETFD, 0) == 1) || set_clexec) &&
2614 (redirector > 2))
2615 SET_CLOSE_ON_EXEC (redirector);
2616 }
2617 break;
2618
2619 case r_close_this:
2620 if (for_real)
2621 {
2622 if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
2623 add_undo_redirect (redirector);
2624
2625#if defined (BUFFERED_INPUT)
2626 close_buffered_fd (redirector);
2627#else /* !BUFFERED_INPUT */
2628 close (redirector);
2629#endif /* !BUFFERED_INPUT */
2630 }
2631 break;
2632 }
2633 return (0);
2634}
2635
2636#define SHELL_FD_BASE 10
2637
2638/* Remember the file descriptor associated with the slot FD,
2639 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
2640 before it is executed. */
2641static int
2642add_undo_redirect (fd)
2643 int fd;
2644{
2645 int new_fd, clexec_flag;
2646 REDIRECT *new_redirect, *closer;
2647
2648 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
2649
2650 if (new_fd < 0)
2651 {
2652 file_error ("redirection error");
2653 return (-1);
2654 }
2655 else
2656 {
2657 clexec_flag = fcntl (fd, F_GETFD, 0);
2658 closer = make_redirection (new_fd, r_close_this, 0);
2659 new_redirect = make_redirection (fd, r_duplicating_input, new_fd);
2660 new_redirect->next = closer;
2661 closer->next = redirection_undo_list;
2662 redirection_undo_list = new_redirect;
2663 /*
2664 * File descriptors used only for saving others should always be
2665 * marked close-on-exec. Unfortunately, we have to preserve the
2666 * close-on-exec state of the file descriptor we are saving, since
2667 * fcntl (F_DUPFD) sets the new file descriptor to remain open
2668 * across execs. If, however, the file descriptor whose state we
2669 * are saving is <= 2, we can just set the close-on-exec flag,
2670 * because file descriptors 0-2 should always be open-on-exec,
2671 * and the restore above in do_redirection() will take care of it.
2672 */
2673 if (clexec_flag || fd < 3)
2674 SET_CLOSE_ON_EXEC (new_fd);
2675 }
2676 return (0);
2677}
2678
2679/* Set up to close FD when we are finished with the current command
2680 and its redirections. */
2681static void
2682add_undo_close_redirect (fd)
2683 int fd;
2684{
2685 REDIRECT *closer;
2686
2687 closer = make_redirection (fd, r_close_this, 0);
2688 closer->next = redirection_undo_list;
2689 redirection_undo_list = closer;
2690}
2691
2692intern_function (name, function)
2693 WORD_DESC *name;
2694 COMMAND *function;
2695{
2696 SHELL_VAR *var;
2697
2698 if (!check_identifier (name))
2699 return (EXECUTION_FAILURE);
2700
2701 var = find_function (name->word);
2702 if (var && readonly_p (var))
2703 {
2704 report_error ("%s: readonly function", var->name);
2705 return (EXECUTION_FAILURE);
2706 }
2707
2708 bind_function (name->word, function);
2709 return (EXECUTION_SUCCESS);
2710}
2711
2712/* Make sure that identifier is a valid shell identifier, i.e.
2713 does not contain a dollar sign, nor is quoted in any way. Nor
2714 does it consist of all digits. */
2715check_identifier (word)
2716 WORD_DESC *word;
2717{
2718 if (word->dollar_present || word->quoted || all_digits (word->word))
2719 {
2720 report_error ("`%s' is not a valid identifier", word->word);
2721 return (0);
2722 }
2723 else
2724 return (1);
2725}
2726
2727#define u_mode_bits(x) (((x) & 0000700) >> 6)
2728#define g_mode_bits(x) (((x) & 0000070) >> 3)
2729#define o_mode_bits(x) (((x) & 0000007) >> 0)
2730#define X_BIT(x) (x & 1)
2731
2732/* Return some flags based on information about this file.
2733 The EXISTS bit is non-zero if the file is found.
2734 The EXECABLE bit is non-zero the file is executble.
2735 Zero is returned if the file is not found. */
2736int
2737file_status (name)
2738 char *name;
2739{
2740 struct stat finfo;
2741 static int user_id = -1;
2742
2743 /* Determine whether this file exists or not. */
2744 if (stat (name, &finfo) < 0)
2745 return (0);
2746
2747 /* If the file is a directory, then it is not "executable" in the
2748 sense of the shell. */
2749 if (S_ISDIR (finfo.st_mode))
2750 return (FS_EXISTS);
2751
2752 /* Find out if the file is actually executable. By definition, the
2753 only other criteria is that the file has an execute bit set that
2754 we can use. */
2755 if (user_id == -1)
2756 user_id = geteuid ();
2757
2758 /* Root only requires execute permission for any of owner, group or
2759 others to be able to exec a file. */
2760 if (user_id == 0)
2761 {
2762 int bits;
2763
2764 bits = (u_mode_bits (finfo.st_mode) |
2765 g_mode_bits (finfo.st_mode) |
2766 o_mode_bits (finfo.st_mode));
2767
2768 if (X_BIT (bits))
2769 return (FS_EXISTS | FS_EXECABLE);
2770 }
2771
2772 /* If we are the owner of the file, the owner execute bit applies. */
2773 if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
2774 return (FS_EXISTS | FS_EXECABLE);
2775
2776 /* If we are in the owning group, the group permissions apply. */
2777 if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
2778 return (FS_EXISTS | FS_EXECABLE);
2779
2780 /* If `others' have execute permission to the file, then so do we,
2781 since we are also `others'. */
2782 if (X_BIT (o_mode_bits (finfo.st_mode)))
2783 return (FS_EXISTS | FS_EXECABLE);
2784 else
2785 return (FS_EXISTS);
2786}
2787
2788/* Return non-zero if FILE exists and is executable.
2789 Note that this function is the definition of what an
2790 executable file is; do not change this unless YOU know
2791 what an executable file is. */
2792int
2793executable_file (file)
2794 char *file;
2795{
2796 if (file_status (file) & FS_EXECABLE)
2797 return (1);
2798 else
2799 return (0);
2800}
2801
2802/* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
2803 encounters a `.' as the directory pathname while scanning the
2804 list of possible pathnames; i.e., if `.' comes before the directory
2805 containing the file of interest. */
2806int dot_found_in_search = 0;
2807
2808/* Locate the executable file referenced by NAME, searching along
2809 the contents of the shell PATH variable. Return a new string
2810 which is the full pathname to the file, or NULL if the file
2811 couldn't be found. If a file is found that isn't executable,
2812 and that is the only match, then return that. */
2813char *
2814find_user_command (name)
2815 char *name;
2816{
2817 return (find_user_command_internal (name, FS_EXEC_PREFERRED));
2818}
2819
2820/* Locate the file referenced by NAME, searching along the contents
2821 of the shell PATH variable. Return a new string which is the full
2822 pathname to the file, or NULL if the file couldn't be found. This
2823 returns the first file found. */
2824char *
2825find_path_file (name)
2826 char *name;
2827{
2828 return (find_user_command_internal (name, FS_EXISTS));
2829}
2830
2831static char *
2832find_user_command_internal (name, flags)
2833 char *name;
2834 int flags;
2835{
2836 char *path_list = (char *)NULL;
2837 SHELL_VAR *var;
2838
2839 /* Search for the value of PATH in both the temporary environment, and
2840 in the regular list of variables. */
2841 if (var = find_variable_internal ("PATH", 1))
2842 path_list = value_cell (var);
2843
2844 if (!path_list)
2845 return (savestring (name));
2846
2847 return (find_user_command_in_path (name, path_list, flags));
2848}
2849
2850/* Return the next element from PATH_LIST, a colon separated list of
2851 paths. PATH_INDEX_POINTER is the address of an index into PATH_LIST;
2852 the index is modified by this function.
2853 Return the next element of PATH_LIST or NULL if there are no more. */
2854static char *
2855get_next_path_element (path_list, path_index_pointer)
2856 char *path_list;
2857 int *path_index_pointer;
2858{
2859 extern char *extract_colon_unit ();
2860 char *path;
2861
2862 path = extract_colon_unit (path_list, path_index_pointer);
2863
2864 if (!path)
2865 return (path);
2866
2867 if (!*path)
2868 {
2869 free (path);
2870 path = savestring (".");
2871 }
2872
2873 return (path);
2874}
2875
2876char *
2877user_command_matches (name, flags, state)
2878 char *name;
2879 int flags, state;
2880{
2881 register int i;
2882 char *path_list;
2883 int path_index;
2884 char *path_element;
2885 char *match;
2886 static char **match_list = NULL;
2887 static int match_list_size = 0;
2888 static int match_index = 0;
2889
2890 if (!state)
2891 {
2892 /* Create the list of matches. */
2893 if (!match_list)
2894 {
2895 match_list =
2896 (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
2897
2898 for (i = 0; i < match_list_size; i++)
2899 match_list[i] = 0;
2900 }
2901
2902 /* Clear out the old match list. */
2903 for (i = 0; i < match_list_size; i++)
2904 match_list[i] = NULL;
2905
2906 /* We haven't found any files yet. */
2907 match_index = 0;
2908
2909 path_list = get_string_value ("PATH");
2910 path_index = 0;
2911
2912 while (path_list && path_list[path_index])
2913 {
2914 char *find_user_command_in_path ();
2915
2916 path_element = get_next_path_element (path_list, &path_index);
2917
2918 if (!path_element)
2919 break;
2920
2921 match = find_user_command_in_path (name, path_element, flags);
2922
2923 free (path_element);
2924
2925 if (!match)
2926 continue;
2927
2928 if (match_index + 1 == match_list_size)
2929 match_list = (char **)xrealloc
2930 (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
2931 match_list[match_index++] = match;
2932 match_list[match_index] = (char *)NULL;
2933 }
2934
2935 /* We haven't returned any strings yet. */
2936 match_index = 0;
2937 }
2938
2939 match = match_list[match_index];
2940
2941 if (match)
2942 match_index++;
2943
2944 return (match);
2945}
2946
2947/* Return 1 if PATH1 and PATH2 are the same file. This is kind of
2948 expensive. If non-NULL STP1 and STP2 point to stat structures
2949 corresponding to PATH1 and PATH2, respectively. */
2950int
2951same_file (path1, path2, stp1, stp2)
2952 char *path1, *path2;
2953 struct stat *stp1, *stp2;
2954{
2955 struct stat st1, st2;
2956
2957 if (stp1 == NULL)
2958 {
2959 if (stat (path1, &st1) != 0)
2960 return (0);
2961 stp1 = &st1;
2962 }
2963
2964 if (stp2 == NULL)
2965 {
2966 if (stat (path2, &st2) != 0)
2967 return (0);
2968 stp2 = &st2;
2969 }
2970
2971 return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
2972}
2973
2974/* This does the dirty work for find_path_file () and find_user_command ().
2975 NAME is the name of the file to search for.
2976 PATH_LIST is a colon separated list of directories to search.
2977 FLAGS contains bit fields which control the files which are eligible.
2978 Some values are:
2979 FS_EXEC_ONLY: The file must be an executable to be found.
2980 FS_EXEC_PREFERRED: If we can't find an executable, then the
2981 the first file matching NAME will do.
2982 FS_EXISTS: The first file found will do.
2983*/
2984static char *
2985find_user_command_in_path (name, path_list, flags)
2986 char *name;
2987 char *path_list;
2988 int flags;
2989{
2990 char *full_path, *path, *file_to_lose_on;
2991 int status, path_index, name_len;
2992 struct stat finfo;
2993
2994 name_len = strlen (name);
2995
2996 /* The file name which we would try to execute, except that it isn't
2997 possible to execute it. This is the first file that matches the
2998 name that we are looking for while we are searching $PATH for a
2999 suitable one to execute. If we cannot find a suitable executable
3000 file, then we use this one. */
3001 file_to_lose_on = (char *)NULL;
3002
3003 /* We haven't started looking, so we certainly haven't seen
3004 a `.' as the directory path yet. */
3005 dot_found_in_search = 0;
3006
3007 if (absolute_program (name))
3008 {
3009 full_path = (char *)xmalloc (1 + name_len);
3010 strcpy (full_path, name);
3011
3012 status = file_status (full_path);
3013
3014 if (!(status & FS_EXISTS))
3015 return (0);
3016
3017 if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
3018 return (full_path);
3019 else
3020 {
3021 free (full_path);
3022 return ((char *)NULL);
3023 }
3024 }
3025
3026 /* Find out the location of the current working directory. */
3027 stat (".", &finfo);
3028
3029 path_index = 0;
3030 while (path_list && path_list[path_index])
3031 {
3032 /* Allow the user to interrupt out of a lengthy path search. */
3033 QUIT;
3034
3035 path = get_next_path_element (path_list, &path_index);
3036
3037 if (!path)
3038 break;
3039
3040 if (*path == '~')
3041 {
3042 char *tilde_expand ();
3043 char *t = tilde_expand (path);
3044 free (path);
3045 path = t;
3046 }
3047
3048 /* Remember the location of "." in the path, in all its forms
3049 (as long as they begin with a `.', e.g. `./.') */
3050 if ((*path == '.') &&
3051 same_file (".", path, &finfo, (struct stat *)NULL))
3052 dot_found_in_search = 1;
3053
3054 full_path = (char *)xmalloc (2 + strlen (path) + name_len);
3055 sprintf (full_path, "%s/%s", path, name);
3056 free (path);
3057
3058 status = file_status (full_path);
3059
3060 if (!(status & FS_EXISTS))
3061 goto next_file;
3062
3063 /* The file exists. If the caller simply wants the first file,
3064 here it is. */
3065 if (flags & FS_EXISTS)
3066 return (full_path);
3067
3068 /* If the file is executable, then it satisfies the cases of
3069 EXEC_ONLY and EXEC_PREFERRED. Return this file unconditionally. */
3070 if (status & FS_EXECABLE)
3071 {
3072 if (file_to_lose_on)
3073 free (file_to_lose_on);
3074
3075 return (full_path);
3076 }
3077
3078 /* The file is not executable, but it does exist. If we prefer
3079 an executable, then remember this one if it is the first one
3080 we have found. */
3081 if (flags & FS_EXEC_PREFERRED)
3082 {
3083 if (!file_to_lose_on)
3084 file_to_lose_on = savestring (full_path);
3085 }
3086
3087 next_file:
3088 free (full_path);
3089 }
3090
3091 /* We didn't find exactly what the user was looking for. Return
3092 the contents of FILE_TO_LOSE_ON which is NULL when the search
3093 required an executable, or non-NULL if a file was found and the
3094 search would accept a non-executable as a last resort. */
3095 return (file_to_lose_on);
3096}
3097
3098/* Given a string containing units of information separated by colons,
3099 return the next one pointed to by INDX, or NULL if there are no more.
3100 Advance INDX to the character after the colon. */
3101char *
3102extract_colon_unit (string, indx)
3103 char *string;
3104 int *indx;
3105{
3106 int i, start;
3107
3108 i = *indx;
3109
3110 if (!string || (i >= strlen (string)))
3111 return ((char *)NULL);
3112
3113 /* Each call to this routine leaves the index pointing at a colon if
3114 there is more to the path. If I is > 0, then increment past the
3115 `:'. If I is 0, then the path has a leading colon. Trailing colons
3116 are handled OK by the `else' part of the if statement; an empty
3117 string is returned in that case. */
3118 if (i && string[i] == ':')
3119 i++;
3120
3121 start = i;
3122
3123 while (string[i] && string[i] != ':') i++;
3124
3125 *indx = i;
3126
3127 if (i == start)
3128 {
3129 if (string[i])
3130 (*indx)++;
3131
3132 /* Return "" in the case of a trailing `:'. */
3133 return (savestring (""));
3134 }
3135 else
3136 {
3137 char *value;
3138
3139 value = (char *)xmalloc (1 + (i - start));
3140 strncpy (value, &string[start], (i - start));
3141 value [i - start] = '\0';
3142
3143 return (value);
3144 }
3145}
3146
3147/* Return non-zero if the characters from SAMPLE are not all valid
3148 characters to be found in the first line of a shell script. We
3149 check up to the first newline, or SAMPLE_LEN, whichever comes first.
3150 All of the characters must be printable or whitespace. */
3151
3152#if !defined (isspace)
3153#define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
3154#endif
3155
3156#if !defined (isprint)
3157#define isprint(c) (isletter(c) || digit(c) || ispunct(c))
3158#endif
3159
3160int
3161check_binary_file (sample, sample_len)
3162 unsigned char *sample;
3163 int sample_len;
3164{
3165 register int i;
3166
3167 for (i = 0; i < sample_len; i++)
3168 {
3169 if (sample[i] == '\n')
3170 break;
3171
3172 if (!isspace (sample[i]) && !isprint (sample[i]))
3173 return (1);
3174 }
3175 return (0);
3176}