Bash-4.3 distribution sources and documentation
[platform/upstream/bash.git] / builtins / evalstring.c
1 /* evalstring.c - evaluate a string as one or more shell commands. */
2
3 /* Copyright (C) 1996-2012 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
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation, either version 3 of the License, or
10    (at your option) any later version.
11
12    Bash is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Bash.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <config.h>
22
23 #if defined (HAVE_UNISTD_H)
24 #  ifdef _MINIX
25 #    include <sys/types.h>
26 #  endif
27 #  include <unistd.h>
28 #endif
29
30 #include <stdio.h>
31 #include <signal.h>
32
33 #include <errno.h>
34
35 #include "filecntl.h"
36 #include "../bashansi.h"
37
38 #include "../shell.h"
39 #include "../jobs.h"
40 #include "../builtins.h"
41 #include "../flags.h"
42 #include "../input.h"
43 #include "../execute_cmd.h"
44 #include "../redir.h"
45 #include "../trap.h"
46 #include "../bashintl.h"
47
48 #include <y.tab.h>
49
50 #if defined (HISTORY)
51 #  include "../bashhist.h"
52 #endif
53
54 #include "common.h"
55 #include "builtext.h"
56
57 #if !defined (errno)
58 extern int errno;
59 #endif
60
61 #define IS_BUILTIN(s)   (builtin_address_internal(s, 0) != (struct builtin *)NULL)
62
63 extern int indirection_level, subshell_environment;
64 extern int line_number, line_number_for_err_trap;
65 extern int current_token, shell_eof_token;
66 extern int last_command_exit_value;
67 extern int running_trap;
68 extern int loop_level;
69 extern int executing_list;
70 extern int comsub_ignore_return;
71 extern int posixly_correct;
72 extern int return_catch_flag, return_catch_value;
73 extern sh_builtin_func_t *this_shell_builtin;
74 extern char *the_printed_command_except_trap;
75
76 int parse_and_execute_level = 0;
77
78 static int cat_file __P((REDIRECT *));
79
80 #define PE_TAG "parse_and_execute top"
81 #define PS_TAG "parse_string top"
82
83 #if defined (HISTORY)
84 static void
85 set_history_remembering ()
86 {
87   remember_on_history = enable_history_list;
88 }
89 #endif
90
91 static void
92 restore_lastcom (x)
93      char *x;
94 {
95   FREE (the_printed_command_except_trap);
96   the_printed_command_except_trap = x;
97 }
98
99 /* How to force parse_and_execute () to clean up after itself. */
100 void
101 parse_and_execute_cleanup ()
102 {
103   if (running_trap)
104     {
105       run_trap_cleanup (running_trap - 1);
106       unfreeze_jobs_list ();
107     }
108
109   if (have_unwind_protects ())
110      run_unwind_frame (PE_TAG);
111   else
112     parse_and_execute_level = 0;                        /* XXX */
113 }
114
115 static void
116 parse_prologue (string, flags, tag)
117      char *string;
118      int flags;
119      char *tag;
120 {
121   char *orig_string, *lastcom;
122   int x;
123
124   orig_string = string;
125   /* Unwind protect this invocation of parse_and_execute (). */
126   begin_unwind_frame (tag);
127   unwind_protect_int (parse_and_execute_level);
128   unwind_protect_jmp_buf (top_level);
129   unwind_protect_int (indirection_level);
130   unwind_protect_int (line_number);
131   unwind_protect_int (line_number_for_err_trap);
132   unwind_protect_int (loop_level);
133   unwind_protect_int (executing_list);
134   unwind_protect_int (comsub_ignore_return);
135   if (flags & (SEVAL_NONINT|SEVAL_INTERACT))
136     unwind_protect_int (interactive);
137
138 #if defined (HISTORY)
139   if (parse_and_execute_level == 0)
140     add_unwind_protect (set_history_remembering, (char *)NULL);
141   else
142     unwind_protect_int (remember_on_history);   /* can be used in scripts */
143 #  if defined (BANG_HISTORY)
144   if (interactive_shell)
145     unwind_protect_int (history_expansion_inhibited);
146 #  endif /* BANG_HISTORY */
147 #endif /* HISTORY */
148
149   if (interactive_shell)
150     {
151       x = get_current_prompt_level ();
152       add_unwind_protect (set_current_prompt_level, x);
153     }
154
155   if (the_printed_command_except_trap)
156     {
157       lastcom = savestring (the_printed_command_except_trap);
158       add_unwind_protect (restore_lastcom, lastcom);
159     }
160
161   add_unwind_protect (pop_stream, (char *)NULL);
162   if (parser_expanding_alias ())
163     add_unwind_protect (parser_restore_alias, (char *)NULL);
164
165   if (orig_string && ((flags & SEVAL_NOFREE) == 0))
166     add_unwind_protect (xfree, orig_string);
167   end_unwind_frame ();
168
169   if (flags & (SEVAL_NONINT|SEVAL_INTERACT))
170     interactive = (flags & SEVAL_NONINT) ? 0 : 1;
171
172 #if defined (HISTORY)
173   if (flags & SEVAL_NOHIST)
174     bash_history_disable ();
175 #endif /* HISTORY */
176 }
177
178 /* Parse and execute the commands in STRING.  Returns whatever
179    execute_command () returns.  This frees STRING.  FLAGS is a
180    flags word; look in common.h for the possible values.  Actions
181    are:
182         (flags & SEVAL_NONINT) -> interactive = 0;
183         (flags & SEVAL_INTERACT) -> interactive = 1;
184         (flags & SEVAL_NOHIST) -> call bash_history_disable ()
185         (flags & SEVAL_NOFREE) -> don't free STRING when finished
186         (flags & SEVAL_RESETLINE) -> reset line_number to 1
187 */
188
189 int
190 parse_and_execute (string, from_file, flags)
191      char *string;
192      const char *from_file;
193      int flags;
194 {
195   int code, lreset;
196   volatile int should_jump_to_top_level, last_result;
197   COMMAND *volatile command;
198   volatile sigset_t pe_sigmask;
199
200   parse_prologue (string, flags, PE_TAG);
201
202   parse_and_execute_level++;
203
204   lreset = flags & SEVAL_RESETLINE;
205
206 #if defined (HAVE_POSIX_SIGNALS)
207   /* If we longjmp and are going to go on, use this to restore signal mask */
208   sigemptyset (&pe_sigmask);
209   sigprocmask (SIG_BLOCK, (sigset_t *)NULL, &pe_sigmask);
210 #endif
211
212   /* Reset the line number if the caller wants us to.  If we don't reset the
213      line number, we have to subtract one, because we will add one just
214      before executing the next command (resetting the line number sets it to
215      0; the first line number is 1). */
216   push_stream (lreset);
217   if (parser_expanding_alias ())
218     /* push current shell_input_line */
219     parser_save_alias ();
220   
221   if (lreset == 0)
222     line_number--;
223     
224   indirection_level++;
225
226   code = should_jump_to_top_level = 0;
227   last_result = EXECUTION_SUCCESS;
228
229   with_input_from_string (string, from_file);
230   while (*(bash_input.location.string))
231     {
232       command = (COMMAND *)NULL;
233
234       if (interrupt_state)
235         {
236           last_result = EXECUTION_FAILURE;
237           break;
238         }
239
240       /* Provide a location for functions which `longjmp (top_level)' to
241          jump to.  This prevents errors in substitution from restarting
242          the reader loop directly, for example. */
243       code = setjmp_nosigs (top_level);
244
245       if (code)
246         {
247           should_jump_to_top_level = 0;
248           switch (code)
249             {
250             case ERREXIT:
251               /* variable_context -> 0 is what eval.c:reader_loop() does in
252                  these circumstances.  Don't bother with cleanup here because
253                  we don't want to run the function execution cleanup stuff
254                  that will cause pop_context and other functions to run.
255                  XXX - change that if we want the function context to be
256                  unwound. */
257               if (exit_immediately_on_error && variable_context)
258                 {
259                   discard_unwind_frame ("pe_dispose");
260                   variable_context = 0; /* not in a function */
261                 }
262               should_jump_to_top_level = 1;
263               goto out;
264             case FORCE_EOF:           
265             case EXITPROG:
266               if (command)
267                 run_unwind_frame ("pe_dispose");
268               /* Remember to call longjmp (top_level) after the old
269                  value for it is restored. */
270               should_jump_to_top_level = 1;
271               goto out;
272
273             case DISCARD:
274               if (command)
275                 run_unwind_frame ("pe_dispose");
276               last_result = last_command_exit_value = EXECUTION_FAILURE; /* XXX */
277               if (subshell_environment)
278                 {
279                   should_jump_to_top_level = 1;
280                   goto out;
281                 }
282               else
283                 {
284 #if 0
285                   dispose_command (command);    /* pe_dispose does this */
286 #endif
287 #if defined (HAVE_POSIX_SIGNALS)
288                   sigprocmask (SIG_SETMASK, &pe_sigmask, (sigset_t *)NULL);
289 #endif
290                   continue;
291                 }
292
293             default:
294               command_error ("parse_and_execute", CMDERR_BADJUMP, code, 0);
295               break;
296             }
297         }
298           
299       if (parse_command () == 0)
300         {
301           if ((flags & SEVAL_PARSEONLY) || (interactive_shell == 0 && read_but_dont_execute))
302             {
303               last_result = EXECUTION_SUCCESS;
304               dispose_command (global_command);
305               global_command = (COMMAND *)NULL;
306             }
307           else if (command = global_command)
308             {
309               struct fd_bitmap *bitmap;
310
311               bitmap = new_fd_bitmap (FD_BITMAP_SIZE);
312               begin_unwind_frame ("pe_dispose");
313               add_unwind_protect (dispose_fd_bitmap, bitmap);
314               add_unwind_protect (dispose_command, command);    /* XXX */
315
316               global_command = (COMMAND *)NULL;
317
318               if ((subshell_environment & SUBSHELL_COMSUB) && comsub_ignore_return)
319                 command->flags |= CMD_IGNORE_RETURN;
320
321 #if defined (ONESHOT)
322               /*
323                * IF
324                *   we were invoked as `bash -c' (startup_state == 2) AND
325                *   parse_and_execute has not been called recursively AND
326                *   we're not running a trap AND
327                *   we have parsed the full command (string == '\0') AND
328                *   we're not going to run the exit trap AND
329                *   we have a simple command without redirections AND
330                *   the command is not being timed AND
331                *   the command's return status is not being inverted
332                * THEN
333                *   tell the execution code that we don't need to fork
334                */
335               if (startup_state == 2 && parse_and_execute_level == 1 &&
336                   running_trap == 0 &&
337                   *bash_input.location.string == '\0' &&
338                   command->type == cm_simple &&
339                   signal_is_trapped (EXIT_TRAP) == 0 &&
340                   command->redirects == 0 && command->value.Simple->redirects == 0 &&
341                   ((command->flags & CMD_TIME_PIPELINE) == 0) &&
342                   ((command->flags & CMD_INVERT_RETURN) == 0))
343                 {
344                   command->flags |= CMD_NO_FORK;
345                   command->value.Simple->flags |= CMD_NO_FORK;
346                 }
347 #endif /* ONESHOT */
348
349               /* See if this is a candidate for $( <file ). */
350               if (startup_state == 2 &&
351                   (subshell_environment & SUBSHELL_COMSUB) &&
352                   *bash_input.location.string == '\0' &&
353                   command->type == cm_simple && !command->redirects &&
354                   (command->flags & CMD_TIME_PIPELINE) == 0 &&
355                   command->value.Simple->words == 0 &&
356                   command->value.Simple->redirects &&
357                   command->value.Simple->redirects->next == 0 &&
358                   command->value.Simple->redirects->instruction == r_input_direction &&
359                   command->value.Simple->redirects->redirector.dest == 0)
360                 {
361                   int r;
362                   r = cat_file (command->value.Simple->redirects);
363                   last_result = (r < 0) ? EXECUTION_FAILURE : EXECUTION_SUCCESS;
364                 }
365               else
366                 last_result = execute_command_internal
367                                 (command, 0, NO_PIPE, NO_PIPE, bitmap);
368               dispose_command (command);
369               dispose_fd_bitmap (bitmap);
370               discard_unwind_frame ("pe_dispose");
371             }
372         }
373       else
374         {
375           last_result = EXECUTION_FAILURE;
376
377           if (interactive_shell == 0 && this_shell_builtin &&
378               (this_shell_builtin == source_builtin || this_shell_builtin == eval_builtin) &&
379               last_command_exit_value == EX_BADSYNTAX && posixly_correct)
380             {
381               should_jump_to_top_level = 1;
382               code = ERREXIT;
383               last_command_exit_value = EX_BADUSAGE;
384             }
385
386           /* Since we are shell compatible, syntax errors in a script
387              abort the execution of the script.  Right? */
388           break;
389         }
390     }
391
392  out:
393
394   run_unwind_frame (PE_TAG);
395
396   if (interrupt_state && parse_and_execute_level == 0)
397     {
398       /* An interrupt during non-interactive execution in an
399          interactive shell (e.g. via $PROMPT_COMMAND) should
400          not cause the shell to exit. */
401       interactive = interactive_shell;
402       throw_to_top_level ();
403     }
404
405   if (should_jump_to_top_level)
406     jump_to_top_level (code);
407
408   return (last_result);
409 }
410
411 /* Parse a command contained in STRING according to FLAGS and return the
412    number of characters consumed from the string.  If non-NULL, set *ENDP
413    to the position in the string where the parse ended.  Used to validate
414    command substitutions during parsing to obey Posix rules about finding
415    the end of the command and balancing parens. */
416 int
417 parse_string (string, from_file, flags, endp)
418      char *string;
419      const char *from_file;
420      int flags;
421      char **endp;
422 {
423   int code, nc;
424   volatile int should_jump_to_top_level;
425   COMMAND *volatile command, *oglobal;
426   char *ostring;
427   volatile sigset_t ps_sigmask;
428
429   parse_prologue (string, flags, PS_TAG);
430
431 #if defined (HAVE_POSIX_SIGNALS)
432   /* If we longjmp and are going to go on, use this to restore signal mask */
433   sigemptyset (&ps_sigmask);
434   sigprocmask (SIG_BLOCK, (sigset_t *)NULL, &ps_sigmask);
435 #endif
436
437 /* itrace("parse_string: `%s'", string); */
438   /* Reset the line number if the caller wants us to.  If we don't reset the
439      line number, we have to subtract one, because we will add one just
440      before executing the next command (resetting the line number sets it to
441      0; the first line number is 1). */
442   push_stream (0);
443   if (parser_expanding_alias ())
444     /* push current shell_input_line */
445     parser_save_alias ();
446
447   code = should_jump_to_top_level = 0;
448   oglobal = global_command;
449   ostring = string;
450
451   with_input_from_string (string, from_file);
452   while (*(bash_input.location.string))
453     {
454       command = (COMMAND *)NULL;
455
456 #if 0
457       if (interrupt_state)
458         break;
459 #endif
460
461       /* Provide a location for functions which `longjmp (top_level)' to
462          jump to. */
463       code = setjmp_nosigs (top_level);
464
465       if (code)
466         {
467 #if defined (DEBUG)
468 itrace("parse_string: longjmp executed: code = %d", code);
469 #endif
470           should_jump_to_top_level = 0;
471           switch (code)
472             {
473             case FORCE_EOF:
474             case ERREXIT:
475             case EXITPROG:
476             case DISCARD:               /* XXX */
477               if (command)
478                 dispose_command (command);
479               /* Remember to call longjmp (top_level) after the old
480                  value for it is restored. */
481               should_jump_to_top_level = 1;
482               goto out;
483
484             default:
485 #if defined (HAVE_POSIX_SIGNALS)
486               sigprocmask (SIG_SETMASK, &ps_sigmask, (sigset_t *)NULL);
487 #endif
488               command_error ("parse_string", CMDERR_BADJUMP, code, 0);
489               break;
490             }
491         }
492           
493       if (parse_command () == 0)
494         {
495           dispose_command (global_command);
496           global_command = (COMMAND *)NULL;
497         }
498       else
499         {
500           if ((flags & SEVAL_NOLONGJMP) == 0)
501             {
502               should_jump_to_top_level = 1;
503               code = DISCARD;
504             }
505           else
506             reset_parser ();    /* XXX - sets token_to_read */
507           break;
508         }
509
510       if (current_token == yacc_EOF || current_token == shell_eof_token)
511           break;
512     }
513
514  out:
515
516   global_command = oglobal;
517   nc = bash_input.location.string - ostring;
518   if (endp)
519     *endp = bash_input.location.string;
520
521   run_unwind_frame (PS_TAG);
522
523   if (should_jump_to_top_level)
524     jump_to_top_level (code);
525
526   return (nc);
527 }
528
529 /* Handle a $( < file ) command substitution.  This expands the filename,
530    returning errors as appropriate, then just cats the file to the standard
531    output. */
532 static int
533 cat_file (r)
534      REDIRECT *r;
535 {
536   char *fn;
537   int fd, rval;
538
539   if (r->instruction != r_input_direction)
540     return -1;
541
542   /* Get the filename. */
543   if (posixly_correct && !interactive_shell)
544     disallow_filename_globbing++;
545   fn = redirection_expand (r->redirectee.filename);
546   if (posixly_correct && !interactive_shell)
547     disallow_filename_globbing--;
548
549   if (fn == 0)
550     {
551       redirection_error (r, AMBIGUOUS_REDIRECT);
552       return -1;
553     }
554
555   fd = open(fn, O_RDONLY);
556   if (fd < 0)
557     {
558       file_error (fn);
559       free (fn);
560       return -1;
561     }
562
563   rval = zcatfd (fd, 1, fn);
564
565   free (fn);
566   close (fd);
567
568   return (rval);
569 }
570
571 int
572 evalstring (string, from_file, flags)
573      char *string;
574      const char *from_file;
575      int flags;
576 {
577   volatile int r, rflag, rcatch;
578
579   rcatch = 0;
580   rflag = return_catch_flag;
581   /* If we are in a place where `return' is valid, we have to catch
582      `eval "... return"' and make sure parse_and_execute cleans up. Then
583      we can trampoline to the previous saved return_catch location. */
584   if (rflag)
585     {
586       begin_unwind_frame ("evalstring");
587
588       unwind_protect_int (return_catch_flag);
589       unwind_protect_jmp_buf (return_catch);
590
591       return_catch_flag++;      /* increment so we have a counter */
592       rcatch = setjmp_nosigs (return_catch);
593     }
594
595   if (rcatch)
596     {
597       parse_and_execute_cleanup ();
598       r = return_catch_value;
599     }
600   else
601     /* Note that parse_and_execute () frees the string it is passed. */
602     r = parse_and_execute (string, from_file, flags);
603
604   if (rflag)
605     {
606       run_unwind_frame ("evalstring");
607       if (rcatch && return_catch_flag)
608         {
609           return_catch_value = r;
610           longjmp (return_catch, 1);
611         }
612     }
613     
614   return (r);
615 }