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