Contents of /tags/mkinitrd-6_1_1/busybox/shell/hush.c
Parent Directory | Revision Log
Revision 841 -
(show annotations)
(download)
Mon May 4 16:31:54 2009 UTC (15 years, 4 months ago) by niro
File MIME type: text/plain
File size: 136421 byte(s)
Mon May 4 16:31:54 2009 UTC (15 years, 4 months ago) by niro
File MIME type: text/plain
File size: 136421 byte(s)
tagged 'mkinitrd-6_1_1'
1 | /* vi: set sw=4 ts=4: */ |
2 | /* |
3 | * sh.c -- a prototype Bourne shell grammar parser |
4 | * Intended to follow the original Thompson and Ritchie |
5 | * "small and simple is beautiful" philosophy, which |
6 | * incidentally is a good match to today's BusyBox. |
7 | * |
8 | * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org> |
9 | * |
10 | * Credits: |
11 | * The parser routines proper are all original material, first |
12 | * written Dec 2000 and Jan 2001 by Larry Doolittle. The |
13 | * execution engine, the builtins, and much of the underlying |
14 | * support has been adapted from busybox-0.49pre's lash, which is |
15 | * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org> |
16 | * written by Erik Andersen <andersen@codepoet.org>. That, in turn, |
17 | * is based in part on ladsh.c, by Michael K. Johnson and Erik W. |
18 | * Troan, which they placed in the public domain. I don't know |
19 | * how much of the Johnson/Troan code has survived the repeated |
20 | * rewrites. |
21 | * |
22 | * Other credits: |
23 | * o_addchr() derived from similar w_addchar function in glibc-2.2. |
24 | * setup_redirect(), redirect_opt_num(), and big chunks of main() |
25 | * and many builtins derived from contributions by Erik Andersen |
26 | * miscellaneous bugfixes from Matt Kraai. |
27 | * |
28 | * There are two big (and related) architecture differences between |
29 | * this parser and the lash parser. One is that this version is |
30 | * actually designed from the ground up to understand nearly all |
31 | * of the Bourne grammar. The second, consequential change is that |
32 | * the parser and input reader have been turned inside out. Now, |
33 | * the parser is in control, and asks for input as needed. The old |
34 | * way had the input reader in control, and it asked for parsing to |
35 | * take place as needed. The new way makes it much easier to properly |
36 | * handle the recursion implicit in the various substitutions, especially |
37 | * across continuation lines. |
38 | * |
39 | * Bash grammar not implemented: (how many of these were in original sh?) |
40 | * $_ |
41 | * &> and >& redirection of stdout+stderr |
42 | * Brace Expansion |
43 | * Tilde Expansion |
44 | * fancy forms of Parameter Expansion |
45 | * aliases |
46 | * Arithmetic Expansion |
47 | * <(list) and >(list) Process Substitution |
48 | * reserved words: select, function |
49 | * Here Documents ( << word ) |
50 | * Functions |
51 | * Major bugs: |
52 | * job handling woefully incomplete and buggy (improved --vda) |
53 | * to-do: |
54 | * port selected bugfixes from post-0.49 busybox lash - done? |
55 | * change { and } from special chars to reserved words |
56 | * builtins: return, trap, ulimit |
57 | * test magic exec with redirection only |
58 | * check setting of global_argc and global_argv |
59 | * follow IFS rules more precisely, including update semantics |
60 | * figure out what to do with backslash-newline |
61 | * propagate syntax errors, die on resource errors? |
62 | * continuation lines, both explicit and implicit - done? |
63 | * memory leak finding and plugging - done? |
64 | * maybe change charmap[] to use 2-bit entries |
65 | * |
66 | * Licensed under the GPL v2 or later, see the file LICENSE in this tarball. |
67 | */ |
68 | |
69 | #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */ |
70 | #include <glob.h> |
71 | /* #include <dmalloc.h> */ |
72 | #if ENABLE_HUSH_CASE |
73 | #include <fnmatch.h> |
74 | #endif |
75 | |
76 | #define HUSH_VER_STR "0.91" |
77 | |
78 | #if !BB_MMU && ENABLE_HUSH_TICK |
79 | //#undef ENABLE_HUSH_TICK |
80 | //#define ENABLE_HUSH_TICK 0 |
81 | #warning On NOMMU, hush command substitution is dangerous. |
82 | #warning Dont use it for commands which produce lots of output. |
83 | #warning For more info see shell/hush.c, generate_stream_from_list(). |
84 | #endif |
85 | |
86 | #if !BB_MMU && ENABLE_HUSH_JOB |
87 | #undef ENABLE_HUSH_JOB |
88 | #define ENABLE_HUSH_JOB 0 |
89 | #endif |
90 | |
91 | #if !ENABLE_HUSH_INTERACTIVE |
92 | #undef ENABLE_FEATURE_EDITING |
93 | #define ENABLE_FEATURE_EDITING 0 |
94 | #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT |
95 | #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0 |
96 | #endif |
97 | |
98 | |
99 | /* Keep unconditionally on for now */ |
100 | #define HUSH_DEBUG 1 |
101 | /* In progress... */ |
102 | #define ENABLE_HUSH_FUNCTIONS 0 |
103 | |
104 | |
105 | /* If you comment out one of these below, it will be #defined later |
106 | * to perform debug printfs to stderr: */ |
107 | #define debug_printf(...) do {} while (0) |
108 | /* Finer-grained debug switches */ |
109 | #define debug_printf_parse(...) do {} while (0) |
110 | #define debug_print_tree(a, b) do {} while (0) |
111 | #define debug_printf_exec(...) do {} while (0) |
112 | #define debug_printf_env(...) do {} while (0) |
113 | #define debug_printf_jobs(...) do {} while (0) |
114 | #define debug_printf_expand(...) do {} while (0) |
115 | #define debug_printf_glob(...) do {} while (0) |
116 | #define debug_printf_list(...) do {} while (0) |
117 | #define debug_printf_subst(...) do {} while (0) |
118 | #define debug_printf_clean(...) do {} while (0) |
119 | |
120 | #ifndef debug_printf |
121 | #define debug_printf(...) fprintf(stderr, __VA_ARGS__) |
122 | #endif |
123 | |
124 | #ifndef debug_printf_parse |
125 | #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__) |
126 | #endif |
127 | |
128 | #ifndef debug_printf_exec |
129 | #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__) |
130 | #endif |
131 | |
132 | #ifndef debug_printf_env |
133 | #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__) |
134 | #endif |
135 | |
136 | #ifndef debug_printf_jobs |
137 | #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__) |
138 | #define DEBUG_JOBS 1 |
139 | #else |
140 | #define DEBUG_JOBS 0 |
141 | #endif |
142 | |
143 | #ifndef debug_printf_expand |
144 | #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__) |
145 | #define DEBUG_EXPAND 1 |
146 | #else |
147 | #define DEBUG_EXPAND 0 |
148 | #endif |
149 | |
150 | #ifndef debug_printf_glob |
151 | #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__) |
152 | #define DEBUG_GLOB 1 |
153 | #else |
154 | #define DEBUG_GLOB 0 |
155 | #endif |
156 | |
157 | #ifndef debug_printf_list |
158 | #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__) |
159 | #endif |
160 | |
161 | #ifndef debug_printf_subst |
162 | #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__) |
163 | #endif |
164 | |
165 | #ifndef debug_printf_clean |
166 | /* broken, of course, but OK for testing */ |
167 | static const char *indenter(int i) |
168 | { |
169 | static const char blanks[] ALIGN1 = |
170 | " "; |
171 | return &blanks[sizeof(blanks) - i - 1]; |
172 | } |
173 | #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__) |
174 | #define DEBUG_CLEAN 1 |
175 | #endif |
176 | |
177 | #if DEBUG_EXPAND |
178 | static void debug_print_strings(const char *prefix, char **vv) |
179 | { |
180 | fprintf(stderr, "%s:\n", prefix); |
181 | while (*vv) |
182 | fprintf(stderr, " '%s'\n", *vv++); |
183 | } |
184 | #else |
185 | #define debug_print_strings(prefix, vv) ((void)0) |
186 | #endif |
187 | |
188 | /* |
189 | * Leak hunting. Use hush_leaktool.sh for post-processing. |
190 | */ |
191 | #ifdef FOR_HUSH_LEAKTOOL |
192 | /* suppress "warning: no previous prototype..." */ |
193 | void *xxmalloc(int lineno, size_t size); |
194 | void *xxrealloc(int lineno, void *ptr, size_t size); |
195 | char *xxstrdup(int lineno, const char *str); |
196 | void xxfree(void *ptr); |
197 | void *xxmalloc(int lineno, size_t size) |
198 | { |
199 | void *ptr = xmalloc((size + 0xff) & ~0xff); |
200 | fprintf(stderr, "line %d: malloc %p\n", lineno, ptr); |
201 | return ptr; |
202 | } |
203 | void *xxrealloc(int lineno, void *ptr, size_t size) |
204 | { |
205 | ptr = xrealloc(ptr, (size + 0xff) & ~0xff); |
206 | fprintf(stderr, "line %d: realloc %p\n", lineno, ptr); |
207 | return ptr; |
208 | } |
209 | char *xxstrdup(int lineno, const char *str) |
210 | { |
211 | char *ptr = xstrdup(str); |
212 | fprintf(stderr, "line %d: strdup %p\n", lineno, ptr); |
213 | return ptr; |
214 | } |
215 | void xxfree(void *ptr) |
216 | { |
217 | fprintf(stderr, "free %p\n", ptr); |
218 | free(ptr); |
219 | } |
220 | #define xmalloc(s) xxmalloc(__LINE__, s) |
221 | #define xrealloc(p, s) xxrealloc(__LINE__, p, s) |
222 | #define xstrdup(s) xxstrdup(__LINE__, s) |
223 | #define free(p) xxfree(p) |
224 | #endif |
225 | |
226 | |
227 | /* Do we support ANY keywords? */ |
228 | #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE |
229 | #define HAS_KEYWORDS 1 |
230 | #define IF_HAS_KEYWORDS(...) __VA_ARGS__ |
231 | #define IF_HAS_NO_KEYWORDS(...) |
232 | #else |
233 | #define HAS_KEYWORDS 0 |
234 | #define IF_HAS_KEYWORDS(...) |
235 | #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__ |
236 | #endif |
237 | |
238 | |
239 | #define SPECIAL_VAR_SYMBOL 3 |
240 | #define PARSEFLAG_EXIT_FROM_LOOP 1 |
241 | |
242 | typedef enum redir_type { |
243 | REDIRECT_INPUT = 1, |
244 | REDIRECT_OVERWRITE = 2, |
245 | REDIRECT_APPEND = 3, |
246 | REDIRECT_HEREIS = 4, |
247 | REDIRECT_IO = 5 |
248 | } redir_type; |
249 | |
250 | /* The descrip member of this structure is only used to make |
251 | * debugging output pretty */ |
252 | static const struct { |
253 | int mode; |
254 | signed char default_fd; |
255 | char descrip[3]; |
256 | } redir_table[] = { |
257 | { 0, 0, "()" }, |
258 | { O_RDONLY, 0, "<" }, |
259 | { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" }, |
260 | { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" }, |
261 | { O_RDONLY, -1, "<<" }, |
262 | { O_RDWR, 1, "<>" } |
263 | }; |
264 | |
265 | typedef enum pipe_style { |
266 | PIPE_SEQ = 1, |
267 | PIPE_AND = 2, |
268 | PIPE_OR = 3, |
269 | PIPE_BG = 4, |
270 | } pipe_style; |
271 | |
272 | typedef enum reserved_style { |
273 | RES_NONE = 0, |
274 | #if ENABLE_HUSH_IF |
275 | RES_IF , |
276 | RES_THEN , |
277 | RES_ELIF , |
278 | RES_ELSE , |
279 | RES_FI , |
280 | #endif |
281 | #if ENABLE_HUSH_LOOPS |
282 | RES_FOR , |
283 | RES_WHILE , |
284 | RES_UNTIL , |
285 | RES_DO , |
286 | RES_DONE , |
287 | #endif |
288 | #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE |
289 | RES_IN , |
290 | #endif |
291 | #if ENABLE_HUSH_CASE |
292 | RES_CASE , |
293 | /* two pseudo-keywords support contrived "case" syntax: */ |
294 | RES_MATCH , /* "word)" */ |
295 | RES_CASEI , /* "this command is inside CASE" */ |
296 | RES_ESAC , |
297 | #endif |
298 | RES_XXXX , |
299 | RES_SNTX |
300 | } reserved_style; |
301 | |
302 | struct redir_struct { |
303 | struct redir_struct *next; |
304 | char *rd_filename; /* filename */ |
305 | int fd; /* file descriptor being redirected */ |
306 | int dup; /* -1, or file descriptor being duplicated */ |
307 | smallint /*enum redir_type*/ rd_type; |
308 | }; |
309 | |
310 | struct command { |
311 | pid_t pid; /* 0 if exited */ |
312 | int assignment_cnt; /* how many argv[i] are assignments? */ |
313 | smallint is_stopped; /* is the command currently running? */ |
314 | smallint grp_type; |
315 | struct pipe *group; /* if non-NULL, this "prog" is {} group, |
316 | * subshell, or a compound statement */ |
317 | char **argv; /* command name and arguments */ |
318 | struct redir_struct *redirects; /* I/O redirections */ |
319 | }; |
320 | /* argv vector may contain variable references (^Cvar^C, ^C0^C etc) |
321 | * and on execution these are substituted with their values. |
322 | * Substitution can make _several_ words out of one argv[n]! |
323 | * Example: argv[0]=='.^C*^C.' here: echo .$*. |
324 | * References of the form ^C`cmd arg^C are `cmd arg` substitutions. |
325 | */ |
326 | #define GRP_NORMAL 0 |
327 | #define GRP_SUBSHELL 1 |
328 | #if ENABLE_HUSH_FUNCTIONS |
329 | #define GRP_FUNCTION 2 |
330 | #endif |
331 | |
332 | struct pipe { |
333 | struct pipe *next; |
334 | int num_cmds; /* total number of commands in job */ |
335 | int alive_cmds; /* number of commands running (not exited) */ |
336 | int stopped_cmds; /* number of commands alive, but stopped */ |
337 | #if ENABLE_HUSH_JOB |
338 | int jobid; /* job number */ |
339 | pid_t pgrp; /* process group ID for the job */ |
340 | char *cmdtext; /* name of job */ |
341 | #endif |
342 | struct command *cmds; /* array of commands in pipe */ |
343 | smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */ |
344 | IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */ |
345 | IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */ |
346 | }; |
347 | |
348 | /* This holds pointers to the various results of parsing */ |
349 | struct parse_context { |
350 | struct command *command; |
351 | struct pipe *list_head; |
352 | struct pipe *pipe; |
353 | struct redir_struct *pending_redirect; |
354 | #if HAS_KEYWORDS |
355 | smallint ctx_res_w; |
356 | smallint ctx_inverted; /* "! cmd | cmd" */ |
357 | #if ENABLE_HUSH_CASE |
358 | smallint ctx_dsemicolon; /* ";;" seen */ |
359 | #endif |
360 | int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */ |
361 | struct parse_context *stack; |
362 | #endif |
363 | }; |
364 | |
365 | /* On program start, environ points to initial environment. |
366 | * putenv adds new pointers into it, unsetenv removes them. |
367 | * Neither of these (de)allocates the strings. |
368 | * setenv allocates new strings in malloc space and does putenv, |
369 | * and thus setenv is unusable (leaky) for shell's purposes */ |
370 | #define setenv(...) setenv_is_leaky_dont_use() |
371 | struct variable { |
372 | struct variable *next; |
373 | char *varstr; /* points to "name=" portion */ |
374 | int max_len; /* if > 0, name is part of initial env; else name is malloced */ |
375 | smallint flg_export; /* putenv should be done on this var */ |
376 | smallint flg_read_only; |
377 | }; |
378 | |
379 | typedef struct o_string { |
380 | char *data; |
381 | int length; /* position where data is appended */ |
382 | int maxlen; |
383 | /* Misnomer! it's not "quoting", it's "protection against globbing"! |
384 | * (by prepending \ to *, ?, [ and to \ too) */ |
385 | smallint o_quote; |
386 | smallint o_glob; |
387 | smallint nonnull; |
388 | smallint has_empty_slot; |
389 | smallint o_assignment; /* 0:maybe, 1:yes, 2:no */ |
390 | } o_string; |
391 | enum { |
392 | MAYBE_ASSIGNMENT = 0, |
393 | DEFINITELY_ASSIGNMENT = 1, |
394 | NOT_ASSIGNMENT = 2, |
395 | WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */ |
396 | }; |
397 | /* Used for initialization: o_string foo = NULL_O_STRING; */ |
398 | #define NULL_O_STRING { NULL } |
399 | |
400 | /* I can almost use ordinary FILE*. Is open_memstream() universally |
401 | * available? Where is it documented? */ |
402 | typedef struct in_str { |
403 | const char *p; |
404 | /* eof_flag=1: last char in ->p is really an EOF */ |
405 | char eof_flag; /* meaningless if ->p == NULL */ |
406 | char peek_buf[2]; |
407 | #if ENABLE_HUSH_INTERACTIVE |
408 | smallint promptme; |
409 | smallint promptmode; /* 0: PS1, 1: PS2 */ |
410 | #endif |
411 | FILE *file; |
412 | int (*get) (struct in_str *); |
413 | int (*peek) (struct in_str *); |
414 | } in_str; |
415 | #define i_getch(input) ((input)->get(input)) |
416 | #define i_peek(input) ((input)->peek(input)) |
417 | |
418 | enum { |
419 | CHAR_ORDINARY = 0, |
420 | CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */ |
421 | CHAR_IFS = 2, /* treated as ordinary if quoted */ |
422 | CHAR_SPECIAL = 3, /* example: $ */ |
423 | }; |
424 | |
425 | enum { |
426 | BC_BREAK = 1, |
427 | BC_CONTINUE = 2, |
428 | }; |
429 | |
430 | |
431 | /* "Globals" within this file */ |
432 | |
433 | /* Sorted roughly by size (smaller offsets == smaller code) */ |
434 | struct globals { |
435 | #if ENABLE_HUSH_INTERACTIVE |
436 | /* 'interactive_fd' is a fd# open to ctty, if we have one |
437 | * _AND_ if we decided to act interactively */ |
438 | int interactive_fd; |
439 | const char *PS1; |
440 | const char *PS2; |
441 | #endif |
442 | #if ENABLE_FEATURE_EDITING |
443 | line_input_t *line_input_state; |
444 | #endif |
445 | pid_t root_pid; |
446 | pid_t last_bg_pid; |
447 | #if ENABLE_HUSH_JOB |
448 | int run_list_level; |
449 | pid_t saved_tty_pgrp; |
450 | int last_jobid; |
451 | struct pipe *job_list; |
452 | struct pipe *toplevel_list; |
453 | smallint ctrl_z_flag; |
454 | #endif |
455 | #if ENABLE_HUSH_LOOPS |
456 | smallint flag_break_continue; |
457 | #endif |
458 | smallint fake_mode; |
459 | /* these three support $?, $#, and $1 */ |
460 | smalluint last_return_code; |
461 | /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */ |
462 | smalluint global_args_malloced; |
463 | /* how many non-NULL argv's we have. NB: $# + 1 */ |
464 | int global_argc; |
465 | char **global_argv; |
466 | #if ENABLE_HUSH_LOOPS |
467 | unsigned depth_break_continue; |
468 | unsigned depth_of_loop; |
469 | #endif |
470 | const char *ifs; |
471 | const char *cwd; |
472 | struct variable *top_var; /* = &G.shell_ver (set in main()) */ |
473 | struct variable shell_ver; |
474 | #if ENABLE_FEATURE_SH_STANDALONE |
475 | struct nofork_save_area nofork_save; |
476 | #endif |
477 | #if ENABLE_HUSH_JOB |
478 | sigjmp_buf toplevel_jb; |
479 | #endif |
480 | unsigned char charmap[256]; |
481 | char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2]; |
482 | }; |
483 | |
484 | #define G (*ptr_to_globals) |
485 | /* Not #defining name to G.name - this quickly gets unwieldy |
486 | * (too many defines). Also, I actually prefer to see when a variable |
487 | * is global, thus "G." prefix is a useful hint */ |
488 | #define INIT_G() do { \ |
489 | SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \ |
490 | } while (0) |
491 | |
492 | |
493 | #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n" |
494 | |
495 | #if 1 |
496 | /* Normal */ |
497 | static void syntax(const char *msg) |
498 | { |
499 | #if ENABLE_HUSH_INTERACTIVE |
500 | /* Was using fancy stuff: |
501 | * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...) |
502 | * but it SEGVs. ?! Oh well... explicit temp ptr works around that */ |
503 | void FAST_FUNC (*fp)(const char *s, ...); |
504 | fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die); |
505 | fp(msg ? "%s: %s" : "syntax error", "syntax error", msg); |
506 | #else |
507 | bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg); |
508 | #endif |
509 | } |
510 | |
511 | #else |
512 | /* Debug */ |
513 | static void syntax_lineno(int line) |
514 | { |
515 | #if ENABLE_HUSH_INTERACTIVE |
516 | void FAST_FUNC (*fp)(const char *s, ...); |
517 | fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die); |
518 | fp("syntax error hush.c:%d", line); |
519 | #else |
520 | bb_error_msg_and_die("syntax error hush.c:%d", line); |
521 | #endif |
522 | } |
523 | #define syntax(str) syntax_lineno(__LINE__) |
524 | #endif |
525 | |
526 | /* Index of subroutines: */ |
527 | /* in_str manipulations: */ |
528 | static int static_get(struct in_str *i); |
529 | static int static_peek(struct in_str *i); |
530 | static int file_get(struct in_str *i); |
531 | static int file_peek(struct in_str *i); |
532 | static void setup_file_in_str(struct in_str *i, FILE *f); |
533 | static void setup_string_in_str(struct in_str *i, const char *s); |
534 | /* "run" the final data structures: */ |
535 | #if !defined(DEBUG_CLEAN) |
536 | #define free_pipe_list(head, indent) free_pipe_list(head) |
537 | #define free_pipe(pi, indent) free_pipe(pi) |
538 | #endif |
539 | static int free_pipe_list(struct pipe *head, int indent); |
540 | static int free_pipe(struct pipe *pi, int indent); |
541 | /* really run the final data structures: */ |
542 | typedef struct nommu_save_t { |
543 | char **new_env; |
544 | char **old_env; |
545 | char **argv; |
546 | } nommu_save_t; |
547 | #if BB_MMU |
548 | #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \ |
549 | pseudo_exec_argv(argv, assignment_cnt, argv_expanded) |
550 | #define pseudo_exec(nommu_save, command, argv_expanded) \ |
551 | pseudo_exec(command, argv_expanded) |
552 | #endif |
553 | static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN; |
554 | static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN; |
555 | static int setup_redirects(struct command *prog, int squirrel[]); |
556 | static int run_list(struct pipe *pi); |
557 | static int run_pipe(struct pipe *pi); |
558 | /* data structure manipulation: */ |
559 | static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input); |
560 | static void initialize_context(struct parse_context *ctx); |
561 | static int done_word(o_string *dest, struct parse_context *ctx); |
562 | static int done_command(struct parse_context *ctx); |
563 | static void done_pipe(struct parse_context *ctx, pipe_style type); |
564 | /* primary string parsing: */ |
565 | static int redirect_dup_num(struct in_str *input); |
566 | static int redirect_opt_num(o_string *o); |
567 | #if ENABLE_HUSH_TICK |
568 | static int process_command_subs(o_string *dest, |
569 | struct in_str *input, const char *subst_end); |
570 | #endif |
571 | static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch); |
572 | static const char *lookup_param(const char *src); |
573 | static int handle_dollar(o_string *dest, |
574 | struct in_str *input); |
575 | static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger); |
576 | /* setup: */ |
577 | static int parse_and_run_stream(struct in_str *inp, int parse_flag); |
578 | static int parse_and_run_string(const char *s, int parse_flag); |
579 | static int parse_and_run_file(FILE *f); |
580 | /* job management: */ |
581 | static int checkjobs(struct pipe* fg_pipe); |
582 | #if ENABLE_HUSH_JOB |
583 | static int checkjobs_and_fg_shell(struct pipe* fg_pipe); |
584 | static void insert_bg_job(struct pipe *pi); |
585 | static void remove_bg_job(struct pipe *pi); |
586 | static void delete_finished_bg_job(struct pipe *pi); |
587 | #else |
588 | int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */ |
589 | #endif |
590 | /* local variable support */ |
591 | static char **expand_strvec_to_strvec(char **argv); |
592 | /* used for eval */ |
593 | static char *expand_strvec_to_string(char **argv); |
594 | /* used for expansion of right hand of assignments */ |
595 | static char *expand_string_to_string(const char *str); |
596 | static struct variable *get_local_var(const char *name); |
597 | static int set_local_var(char *str, int flg_export); |
598 | static void unset_local_var(const char *name); |
599 | |
600 | |
601 | static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR; |
602 | |
603 | |
604 | static int glob_needed(const char *s) |
605 | { |
606 | while (*s) { |
607 | if (*s == '\\') |
608 | s++; |
609 | if (*s == '*' || *s == '[' || *s == '?') |
610 | return 1; |
611 | s++; |
612 | } |
613 | return 0; |
614 | } |
615 | |
616 | static int is_assignment(const char *s) |
617 | { |
618 | if (!s || !(isalpha(*s) || *s == '_')) |
619 | return 0; |
620 | s++; |
621 | while (isalnum(*s) || *s == '_') |
622 | s++; |
623 | return *s == '='; |
624 | } |
625 | |
626 | /* Replace each \x with x in place, return ptr past NUL. */ |
627 | static char *unbackslash(char *src) |
628 | { |
629 | char *dst = src; |
630 | while (1) { |
631 | if (*src == '\\') |
632 | src++; |
633 | if ((*dst++ = *src++) == '\0') |
634 | break; |
635 | } |
636 | return dst; |
637 | } |
638 | |
639 | static char **add_strings_to_strings(char **strings, char **add, int need_to_dup) |
640 | { |
641 | int i; |
642 | unsigned count1; |
643 | unsigned count2; |
644 | char **v; |
645 | |
646 | v = strings; |
647 | count1 = 0; |
648 | if (v) { |
649 | while (*v) { |
650 | count1++; |
651 | v++; |
652 | } |
653 | } |
654 | count2 = 0; |
655 | v = add; |
656 | while (*v) { |
657 | count2++; |
658 | v++; |
659 | } |
660 | v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*)); |
661 | v[count1 + count2] = NULL; |
662 | i = count2; |
663 | while (--i >= 0) |
664 | v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]); |
665 | return v; |
666 | } |
667 | |
668 | static char **add_string_to_strings(char **strings, char *add) |
669 | { |
670 | char *v[2]; |
671 | v[0] = add; |
672 | v[1] = NULL; |
673 | return add_strings_to_strings(strings, v, /*dup:*/ 0); |
674 | } |
675 | |
676 | static void putenv_all(char **strings) |
677 | { |
678 | if (!strings) |
679 | return; |
680 | while (*strings) { |
681 | debug_printf_env("putenv '%s'\n", *strings); |
682 | putenv(*strings++); |
683 | } |
684 | } |
685 | |
686 | static char **putenv_all_and_save_old(char **strings) |
687 | { |
688 | char **old = NULL; |
689 | char **s = strings; |
690 | |
691 | if (!strings) |
692 | return old; |
693 | while (*strings) { |
694 | char *v, *eq; |
695 | |
696 | eq = strchr(*strings, '='); |
697 | if (eq) { |
698 | *eq = '\0'; |
699 | v = getenv(*strings); |
700 | *eq = '='; |
701 | if (v) { |
702 | /* v points to VAL in VAR=VAL, go back to VAR */ |
703 | v -= (eq - *strings) + 1; |
704 | old = add_string_to_strings(old, v); |
705 | } |
706 | } |
707 | strings++; |
708 | } |
709 | putenv_all(s); |
710 | return old; |
711 | } |
712 | |
713 | static void free_strings_and_unsetenv(char **strings, int unset) |
714 | { |
715 | char **v; |
716 | |
717 | if (!strings) |
718 | return; |
719 | |
720 | v = strings; |
721 | while (*v) { |
722 | if (unset) { |
723 | char *copy; |
724 | /* *strchrnul(*v, '=') = '\0'; -- BAD |
725 | * In case *v was putenv'ed, we can't |
726 | * unsetenv(*v) after taking out '=': |
727 | * it won't work, env is modified by taking out! |
728 | * horror :( */ |
729 | copy = xstrndup(*v, strchrnul(*v, '=') - *v); |
730 | debug_printf_env("unsetenv '%s'\n", copy); |
731 | unsetenv(copy); |
732 | free(copy); |
733 | } |
734 | free(*v++); |
735 | } |
736 | free(strings); |
737 | } |
738 | |
739 | static void free_strings(char **strings) |
740 | { |
741 | free_strings_and_unsetenv(strings, 0); |
742 | } |
743 | |
744 | |
745 | /* Function prototypes for builtins */ |
746 | static int builtin_cd(char **argv); |
747 | static int builtin_echo(char **argv); |
748 | static int builtin_eval(char **argv); |
749 | static int builtin_exec(char **argv); |
750 | static int builtin_exit(char **argv); |
751 | static int builtin_export(char **argv); |
752 | #if ENABLE_HUSH_JOB |
753 | static int builtin_fg_bg(char **argv); |
754 | static int builtin_jobs(char **argv); |
755 | #endif |
756 | #if ENABLE_HUSH_HELP |
757 | static int builtin_help(char **argv); |
758 | #endif |
759 | static int builtin_pwd(char **argv); |
760 | static int builtin_read(char **argv); |
761 | static int builtin_test(char **argv); |
762 | static int builtin_true(char **argv); |
763 | static int builtin_set(char **argv); |
764 | static int builtin_shift(char **argv); |
765 | static int builtin_source(char **argv); |
766 | static int builtin_umask(char **argv); |
767 | static int builtin_unset(char **argv); |
768 | #if ENABLE_HUSH_LOOPS |
769 | static int builtin_break(char **argv); |
770 | static int builtin_continue(char **argv); |
771 | #endif |
772 | //static int builtin_not_written(char **argv); |
773 | |
774 | /* Table of built-in functions. They can be forked or not, depending on |
775 | * context: within pipes, they fork. As simple commands, they do not. |
776 | * When used in non-forking context, they can change global variables |
777 | * in the parent shell process. If forked, of course they cannot. |
778 | * For example, 'unset foo | whatever' will parse and run, but foo will |
779 | * still be set at the end. */ |
780 | struct built_in_command { |
781 | const char *cmd; |
782 | int (*function)(char **argv); |
783 | #if ENABLE_HUSH_HELP |
784 | const char *descr; |
785 | #define BLTIN(cmd, func, help) { cmd, func, help } |
786 | #else |
787 | #define BLTIN(cmd, func, help) { cmd, func } |
788 | #endif |
789 | }; |
790 | |
791 | /* For now, echo and test are unconditionally enabled. |
792 | * Maybe make it configurable? */ |
793 | static const struct built_in_command bltins[] = { |
794 | BLTIN("." , builtin_source, "Run commands in a file"), |
795 | BLTIN(":" , builtin_true, "No-op"), |
796 | BLTIN("[" , builtin_test, "Test condition"), |
797 | BLTIN("[[" , builtin_test, "Test condition"), |
798 | #if ENABLE_HUSH_JOB |
799 | BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"), |
800 | #endif |
801 | #if ENABLE_HUSH_LOOPS |
802 | BLTIN("break" , builtin_break, "Exit from a loop"), |
803 | #endif |
804 | BLTIN("cd" , builtin_cd, "Change directory"), |
805 | #if ENABLE_HUSH_LOOPS |
806 | BLTIN("continue", builtin_continue, "Start new loop iteration"), |
807 | #endif |
808 | BLTIN("echo" , builtin_echo, "Write to stdout"), |
809 | BLTIN("eval" , builtin_eval, "Construct and run shell command"), |
810 | BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"), |
811 | BLTIN("exit" , builtin_exit, "Exit"), |
812 | BLTIN("export", builtin_export, "Set environment variable"), |
813 | #if ENABLE_HUSH_JOB |
814 | BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"), |
815 | BLTIN("jobs" , builtin_jobs, "List active jobs"), |
816 | #endif |
817 | BLTIN("pwd" , builtin_pwd, "Print current directory"), |
818 | BLTIN("read" , builtin_read, "Input environment variable"), |
819 | // BLTIN("return", builtin_not_written, "Return from a function"), |
820 | BLTIN("set" , builtin_set, "Set/unset shell local variables"), |
821 | BLTIN("shift" , builtin_shift, "Shift positional parameters"), |
822 | // BLTIN("trap" , builtin_not_written, "Trap signals"), |
823 | BLTIN("test" , builtin_test, "Test condition"), |
824 | // BLTIN("ulimit", builtin_not_written, "Control resource limits"), |
825 | BLTIN("umask" , builtin_umask, "Set file creation mask"), |
826 | BLTIN("unset" , builtin_unset, "Unset environment variable"), |
827 | #if ENABLE_HUSH_HELP |
828 | BLTIN("help" , builtin_help, "List shell built-in commands"), |
829 | #endif |
830 | }; |
831 | |
832 | |
833 | /* Signals are grouped, we handle them in batches */ |
834 | static void set_misc_sighandler(void (*handler)(int)) |
835 | { |
836 | bb_signals(0 |
837 | + (1 << SIGINT) |
838 | + (1 << SIGQUIT) |
839 | + (1 << SIGTERM) |
840 | , handler); |
841 | } |
842 | |
843 | #if ENABLE_HUSH_JOB |
844 | |
845 | static void set_fatal_sighandler(void (*handler)(int)) |
846 | { |
847 | bb_signals(0 |
848 | + (1 << SIGILL) |
849 | + (1 << SIGTRAP) |
850 | + (1 << SIGABRT) |
851 | + (1 << SIGFPE) |
852 | + (1 << SIGBUS) |
853 | + (1 << SIGSEGV) |
854 | /* bash 3.2 seems to handle these just like 'fatal' ones */ |
855 | + (1 << SIGHUP) |
856 | + (1 << SIGPIPE) |
857 | + (1 << SIGALRM) |
858 | , handler); |
859 | } |
860 | static void set_jobctrl_sighandler(void (*handler)(int)) |
861 | { |
862 | bb_signals(0 |
863 | + (1 << SIGTSTP) |
864 | + (1 << SIGTTIN) |
865 | + (1 << SIGTTOU) |
866 | , handler); |
867 | } |
868 | /* SIGCHLD is special and handled separately */ |
869 | |
870 | static void set_every_sighandler(void (*handler)(int)) |
871 | { |
872 | set_fatal_sighandler(handler); |
873 | set_jobctrl_sighandler(handler); |
874 | set_misc_sighandler(handler); |
875 | signal(SIGCHLD, handler); |
876 | } |
877 | |
878 | static void handler_ctrl_c(int sig UNUSED_PARAM) |
879 | { |
880 | debug_printf_jobs("got sig %d\n", sig); |
881 | // as usual we can have all kinds of nasty problems with leaked malloc data here |
882 | siglongjmp(G.toplevel_jb, 1); |
883 | } |
884 | |
885 | static void handler_ctrl_z(int sig UNUSED_PARAM) |
886 | { |
887 | pid_t pid; |
888 | |
889 | debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid()); |
890 | pid = fork(); |
891 | if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */ |
892 | return; |
893 | G.ctrl_z_flag = 1; |
894 | if (!pid) { /* child */ |
895 | if (ENABLE_HUSH_JOB) |
896 | die_sleep = 0; /* let nofork's xfuncs die */ |
897 | bb_setpgrp(); |
898 | debug_printf_jobs("set pgrp for child %d ok\n", getpid()); |
899 | set_every_sighandler(SIG_DFL); |
900 | raise(SIGTSTP); /* resend TSTP so that child will be stopped */ |
901 | debug_printf_jobs("returning in child\n"); |
902 | /* return to nofork, it will eventually exit now, |
903 | * not return back to shell */ |
904 | return; |
905 | } |
906 | /* parent */ |
907 | /* finish filling up pipe info */ |
908 | G.toplevel_list->pgrp = pid; /* child is in its own pgrp */ |
909 | G.toplevel_list->cmds[0].pid = pid; |
910 | /* parent needs to longjmp out of running nofork. |
911 | * we will "return" exitcode 0, with child put in background */ |
912 | // as usual we can have all kinds of nasty problems with leaked malloc data here |
913 | debug_printf_jobs("siglongjmp in parent\n"); |
914 | siglongjmp(G.toplevel_jb, 1); |
915 | } |
916 | |
917 | /* Restores tty foreground process group, and exits. |
918 | * May be called as signal handler for fatal signal |
919 | * (will faithfully resend signal to itself, producing correct exit state) |
920 | * or called directly with -EXITCODE. |
921 | * We also call it if xfunc is exiting. */ |
922 | static void sigexit(int sig) NORETURN; |
923 | static void sigexit(int sig) |
924 | { |
925 | /* Disable all signals: job control, SIGPIPE, etc. */ |
926 | sigprocmask_allsigs(SIG_BLOCK); |
927 | |
928 | #if ENABLE_HUSH_INTERACTIVE |
929 | if (G.interactive_fd) |
930 | tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp); |
931 | #endif |
932 | |
933 | /* Not a signal, just exit */ |
934 | if (sig <= 0) |
935 | _exit(- sig); |
936 | |
937 | kill_myself_with_sig(sig); /* does not return */ |
938 | } |
939 | |
940 | /* Restores tty foreground process group, and exits. */ |
941 | static void hush_exit(int exitcode) NORETURN; |
942 | static void hush_exit(int exitcode) |
943 | { |
944 | fflush(NULL); /* flush all streams */ |
945 | sigexit(- (exitcode & 0xff)); |
946 | } |
947 | |
948 | #else /* !JOB */ |
949 | |
950 | #define set_fatal_sighandler(handler) ((void)0) |
951 | #define set_jobctrl_sighandler(handler) ((void)0) |
952 | #define hush_exit(e) exit(e) |
953 | |
954 | #endif /* JOB */ |
955 | |
956 | |
957 | static const char *set_cwd(void) |
958 | { |
959 | if (G.cwd == bb_msg_unknown) |
960 | G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */ |
961 | G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd); |
962 | if (!G.cwd) |
963 | G.cwd = bb_msg_unknown; |
964 | return G.cwd; |
965 | } |
966 | |
967 | |
968 | /* |
969 | * o_string support |
970 | */ |
971 | #define B_CHUNK (32 * sizeof(char*)) |
972 | |
973 | static void o_reset(o_string *o) |
974 | { |
975 | o->length = 0; |
976 | o->nonnull = 0; |
977 | if (o->data) |
978 | o->data[0] = '\0'; |
979 | } |
980 | |
981 | static void o_free(o_string *o) |
982 | { |
983 | free(o->data); |
984 | memset(o, 0, sizeof(*o)); |
985 | } |
986 | |
987 | static void o_grow_by(o_string *o, int len) |
988 | { |
989 | if (o->length + len > o->maxlen) { |
990 | o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK); |
991 | o->data = xrealloc(o->data, 1 + o->maxlen); |
992 | } |
993 | } |
994 | |
995 | static void o_addchr(o_string *o, int ch) |
996 | { |
997 | debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o); |
998 | o_grow_by(o, 1); |
999 | o->data[o->length] = ch; |
1000 | o->length++; |
1001 | o->data[o->length] = '\0'; |
1002 | } |
1003 | |
1004 | static void o_addstr(o_string *o, const char *str, int len) |
1005 | { |
1006 | o_grow_by(o, len); |
1007 | memcpy(&o->data[o->length], str, len); |
1008 | o->length += len; |
1009 | o->data[o->length] = '\0'; |
1010 | } |
1011 | |
1012 | static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len) |
1013 | { |
1014 | while (len) { |
1015 | o_addchr(o, *str); |
1016 | if (*str++ == '\\' |
1017 | && (*str != '*' && *str != '?' && *str != '[') |
1018 | ) { |
1019 | o_addchr(o, '\\'); |
1020 | } |
1021 | len--; |
1022 | } |
1023 | } |
1024 | |
1025 | /* My analysis of quoting semantics tells me that state information |
1026 | * is associated with a destination, not a source. |
1027 | */ |
1028 | static void o_addqchr(o_string *o, int ch) |
1029 | { |
1030 | int sz = 1; |
1031 | char *found = strchr("*?[\\", ch); |
1032 | if (found) |
1033 | sz++; |
1034 | o_grow_by(o, sz); |
1035 | if (found) { |
1036 | o->data[o->length] = '\\'; |
1037 | o->length++; |
1038 | } |
1039 | o->data[o->length] = ch; |
1040 | o->length++; |
1041 | o->data[o->length] = '\0'; |
1042 | } |
1043 | |
1044 | static void o_addQchr(o_string *o, int ch) |
1045 | { |
1046 | int sz = 1; |
1047 | if (o->o_quote && strchr("*?[\\", ch)) { |
1048 | sz++; |
1049 | o->data[o->length] = '\\'; |
1050 | o->length++; |
1051 | } |
1052 | o_grow_by(o, sz); |
1053 | o->data[o->length] = ch; |
1054 | o->length++; |
1055 | o->data[o->length] = '\0'; |
1056 | } |
1057 | |
1058 | static void o_addQstr(o_string *o, const char *str, int len) |
1059 | { |
1060 | if (!o->o_quote) { |
1061 | o_addstr(o, str, len); |
1062 | return; |
1063 | } |
1064 | while (len) { |
1065 | char ch; |
1066 | int sz; |
1067 | int ordinary_cnt = strcspn(str, "*?[\\"); |
1068 | if (ordinary_cnt > len) /* paranoia */ |
1069 | ordinary_cnt = len; |
1070 | o_addstr(o, str, ordinary_cnt); |
1071 | if (ordinary_cnt == len) |
1072 | return; |
1073 | str += ordinary_cnt; |
1074 | len -= ordinary_cnt + 1; /* we are processing + 1 char below */ |
1075 | |
1076 | ch = *str++; |
1077 | sz = 1; |
1078 | if (ch) { /* it is necessarily one of "*?[\\" */ |
1079 | sz++; |
1080 | o->data[o->length] = '\\'; |
1081 | o->length++; |
1082 | } |
1083 | o_grow_by(o, sz); |
1084 | o->data[o->length] = ch; |
1085 | o->length++; |
1086 | o->data[o->length] = '\0'; |
1087 | } |
1088 | } |
1089 | |
1090 | /* A special kind of o_string for $VAR and `cmd` expansion. |
1091 | * It contains char* list[] at the beginning, which is grown in 16 element |
1092 | * increments. Actual string data starts at the next multiple of 16 * (char*). |
1093 | * list[i] contains an INDEX (int!) into this string data. |
1094 | * It means that if list[] needs to grow, data needs to be moved higher up |
1095 | * but list[i]'s need not be modified. |
1096 | * NB: remembering how many list[i]'s you have there is crucial. |
1097 | * o_finalize_list() operation post-processes this structure - calculates |
1098 | * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well. |
1099 | */ |
1100 | #if DEBUG_EXPAND || DEBUG_GLOB |
1101 | static void debug_print_list(const char *prefix, o_string *o, int n) |
1102 | { |
1103 | char **list = (char**)o->data; |
1104 | int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]); |
1105 | int i = 0; |
1106 | fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n", |
1107 | prefix, list, n, string_start, o->length, o->maxlen); |
1108 | while (i < n) { |
1109 | fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i], |
1110 | o->data + (int)list[i] + string_start, |
1111 | o->data + (int)list[i] + string_start); |
1112 | i++; |
1113 | } |
1114 | if (n) { |
1115 | const char *p = o->data + (int)list[n - 1] + string_start; |
1116 | fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data); |
1117 | } |
1118 | } |
1119 | #else |
1120 | #define debug_print_list(prefix, o, n) ((void)0) |
1121 | #endif |
1122 | |
1123 | /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value |
1124 | * in list[n] so that it points past last stored byte so far. |
1125 | * It returns n+1. */ |
1126 | static int o_save_ptr_helper(o_string *o, int n) |
1127 | { |
1128 | char **list = (char**)o->data; |
1129 | int string_start; |
1130 | int string_len; |
1131 | |
1132 | if (!o->has_empty_slot) { |
1133 | string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]); |
1134 | string_len = o->length - string_start; |
1135 | if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */ |
1136 | debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start); |
1137 | /* list[n] points to string_start, make space for 16 more pointers */ |
1138 | o->maxlen += 0x10 * sizeof(list[0]); |
1139 | o->data = xrealloc(o->data, o->maxlen + 1); |
1140 | list = (char**)o->data; |
1141 | memmove(list + n + 0x10, list + n, string_len); |
1142 | o->length += 0x10 * sizeof(list[0]); |
1143 | } else |
1144 | debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start); |
1145 | } else { |
1146 | /* We have empty slot at list[n], reuse without growth */ |
1147 | string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */ |
1148 | string_len = o->length - string_start; |
1149 | debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start); |
1150 | o->has_empty_slot = 0; |
1151 | } |
1152 | list[n] = (char*)(ptrdiff_t)string_len; |
1153 | return n + 1; |
1154 | } |
1155 | |
1156 | /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */ |
1157 | static int o_get_last_ptr(o_string *o, int n) |
1158 | { |
1159 | char **list = (char**)o->data; |
1160 | int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]); |
1161 | |
1162 | return ((int)(ptrdiff_t)list[n-1]) + string_start; |
1163 | } |
1164 | |
1165 | /* o_glob performs globbing on last list[], saving each result |
1166 | * as a new list[]. */ |
1167 | static int o_glob(o_string *o, int n) |
1168 | { |
1169 | glob_t globdata; |
1170 | int gr; |
1171 | char *pattern; |
1172 | |
1173 | debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data); |
1174 | if (!o->data) |
1175 | return o_save_ptr_helper(o, n); |
1176 | pattern = o->data + o_get_last_ptr(o, n); |
1177 | debug_printf_glob("glob pattern '%s'\n", pattern); |
1178 | if (!glob_needed(pattern)) { |
1179 | literal: |
1180 | o->length = unbackslash(pattern) - o->data; |
1181 | debug_printf_glob("glob pattern '%s' is literal\n", pattern); |
1182 | return o_save_ptr_helper(o, n); |
1183 | } |
1184 | |
1185 | memset(&globdata, 0, sizeof(globdata)); |
1186 | gr = glob(pattern, 0, NULL, &globdata); |
1187 | debug_printf_glob("glob('%s'):%d\n", pattern, gr); |
1188 | if (gr == GLOB_NOSPACE) |
1189 | bb_error_msg_and_die("out of memory during glob"); |
1190 | if (gr == GLOB_NOMATCH) { |
1191 | globfree(&globdata); |
1192 | goto literal; |
1193 | } |
1194 | if (gr != 0) { /* GLOB_ABORTED ? */ |
1195 | //TODO: testcase for bad glob pattern behavior |
1196 | bb_error_msg("glob(3) error %d on '%s'", gr, pattern); |
1197 | } |
1198 | if (globdata.gl_pathv && globdata.gl_pathv[0]) { |
1199 | char **argv = globdata.gl_pathv; |
1200 | o->length = pattern - o->data; /* "forget" pattern */ |
1201 | while (1) { |
1202 | o_addstr(o, *argv, strlen(*argv) + 1); |
1203 | n = o_save_ptr_helper(o, n); |
1204 | argv++; |
1205 | if (!*argv) |
1206 | break; |
1207 | } |
1208 | } |
1209 | globfree(&globdata); |
1210 | if (DEBUG_GLOB) |
1211 | debug_print_list("o_glob returning", o, n); |
1212 | return n; |
1213 | } |
1214 | |
1215 | /* If o->o_glob == 1, glob the string so far remembered. |
1216 | * Otherwise, just finish current list[] and start new */ |
1217 | static int o_save_ptr(o_string *o, int n) |
1218 | { |
1219 | if (o->o_glob) { /* if globbing is requested */ |
1220 | /* If o->has_empty_slot, list[n] was already globbed |
1221 | * (if it was requested back then when it was filled) |
1222 | * so don't do that again! */ |
1223 | if (!o->has_empty_slot) |
1224 | return o_glob(o, n); /* o_save_ptr_helper is inside */ |
1225 | } |
1226 | return o_save_ptr_helper(o, n); |
1227 | } |
1228 | |
1229 | /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */ |
1230 | static char **o_finalize_list(o_string *o, int n) |
1231 | { |
1232 | char **list; |
1233 | int string_start; |
1234 | |
1235 | n = o_save_ptr(o, n); /* force growth for list[n] if necessary */ |
1236 | if (DEBUG_EXPAND) |
1237 | debug_print_list("finalized", o, n); |
1238 | debug_printf_expand("finalized n:%d\n", n); |
1239 | list = (char**)o->data; |
1240 | string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]); |
1241 | list[--n] = NULL; |
1242 | while (n) { |
1243 | n--; |
1244 | list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start; |
1245 | } |
1246 | return list; |
1247 | } |
1248 | |
1249 | |
1250 | /* |
1251 | * in_str support |
1252 | */ |
1253 | static int static_get(struct in_str *i) |
1254 | { |
1255 | int ch = *i->p++; |
1256 | if (ch == '\0') return EOF; |
1257 | return ch; |
1258 | } |
1259 | |
1260 | static int static_peek(struct in_str *i) |
1261 | { |
1262 | return *i->p; |
1263 | } |
1264 | |
1265 | #if ENABLE_HUSH_INTERACTIVE |
1266 | |
1267 | #if ENABLE_FEATURE_EDITING |
1268 | static void cmdedit_set_initial_prompt(void) |
1269 | { |
1270 | #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT |
1271 | G.PS1 = NULL; |
1272 | #else |
1273 | G.PS1 = getenv("PS1"); |
1274 | if (G.PS1 == NULL) |
1275 | G.PS1 = "\\w \\$ "; |
1276 | #endif |
1277 | } |
1278 | #endif /* EDITING */ |
1279 | |
1280 | static const char* setup_prompt_string(int promptmode) |
1281 | { |
1282 | const char *prompt_str; |
1283 | debug_printf("setup_prompt_string %d ", promptmode); |
1284 | #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT |
1285 | /* Set up the prompt */ |
1286 | if (promptmode == 0) { /* PS1 */ |
1287 | free((char*)G.PS1); |
1288 | G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#'); |
1289 | prompt_str = G.PS1; |
1290 | } else { |
1291 | prompt_str = G.PS2; |
1292 | } |
1293 | #else |
1294 | prompt_str = (promptmode == 0) ? G.PS1 : G.PS2; |
1295 | #endif |
1296 | debug_printf("result '%s'\n", prompt_str); |
1297 | return prompt_str; |
1298 | } |
1299 | |
1300 | static void get_user_input(struct in_str *i) |
1301 | { |
1302 | int r; |
1303 | const char *prompt_str; |
1304 | |
1305 | prompt_str = setup_prompt_string(i->promptmode); |
1306 | #if ENABLE_FEATURE_EDITING |
1307 | /* Enable command line editing only while a command line |
1308 | * is actually being read */ |
1309 | do { |
1310 | r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state); |
1311 | } while (r == 0); /* repeat if Ctrl-C */ |
1312 | i->eof_flag = (r < 0); |
1313 | if (i->eof_flag) { /* EOF/error detected */ |
1314 | G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */ |
1315 | G.user_input_buf[1] = '\0'; |
1316 | } |
1317 | #else |
1318 | fputs(prompt_str, stdout); |
1319 | fflush(stdout); |
1320 | G.user_input_buf[0] = r = fgetc(i->file); |
1321 | /*G.user_input_buf[1] = '\0'; - already is and never changed */ |
1322 | i->eof_flag = (r == EOF); |
1323 | #endif |
1324 | i->p = G.user_input_buf; |
1325 | } |
1326 | |
1327 | #endif /* INTERACTIVE */ |
1328 | |
1329 | /* This is the magic location that prints prompts |
1330 | * and gets data back from the user */ |
1331 | static int file_get(struct in_str *i) |
1332 | { |
1333 | int ch; |
1334 | |
1335 | /* If there is data waiting, eat it up */ |
1336 | if (i->p && *i->p) { |
1337 | #if ENABLE_HUSH_INTERACTIVE |
1338 | take_cached: |
1339 | #endif |
1340 | ch = *i->p++; |
1341 | if (i->eof_flag && !*i->p) |
1342 | ch = EOF; |
1343 | } else { |
1344 | /* need to double check i->file because we might be doing something |
1345 | * more complicated by now, like sourcing or substituting. */ |
1346 | #if ENABLE_HUSH_INTERACTIVE |
1347 | if (G.interactive_fd && i->promptme && i->file == stdin) { |
1348 | do { |
1349 | get_user_input(i); |
1350 | } while (!*i->p); /* need non-empty line */ |
1351 | i->promptmode = 1; /* PS2 */ |
1352 | i->promptme = 0; |
1353 | goto take_cached; |
1354 | } |
1355 | #endif |
1356 | ch = fgetc(i->file); |
1357 | } |
1358 | debug_printf("file_get: got a '%c' %d\n", ch, ch); |
1359 | #if ENABLE_HUSH_INTERACTIVE |
1360 | if (ch == '\n') |
1361 | i->promptme = 1; |
1362 | #endif |
1363 | return ch; |
1364 | } |
1365 | |
1366 | /* All the callers guarantee this routine will never be |
1367 | * used right after a newline, so prompting is not needed. |
1368 | */ |
1369 | static int file_peek(struct in_str *i) |
1370 | { |
1371 | int ch; |
1372 | if (i->p && *i->p) { |
1373 | if (i->eof_flag && !i->p[1]) |
1374 | return EOF; |
1375 | return *i->p; |
1376 | } |
1377 | ch = fgetc(i->file); |
1378 | i->eof_flag = (ch == EOF); |
1379 | i->peek_buf[0] = ch; |
1380 | i->peek_buf[1] = '\0'; |
1381 | i->p = i->peek_buf; |
1382 | debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p); |
1383 | return ch; |
1384 | } |
1385 | |
1386 | static void setup_file_in_str(struct in_str *i, FILE *f) |
1387 | { |
1388 | i->peek = file_peek; |
1389 | i->get = file_get; |
1390 | #if ENABLE_HUSH_INTERACTIVE |
1391 | i->promptme = 1; |
1392 | i->promptmode = 0; /* PS1 */ |
1393 | #endif |
1394 | i->file = f; |
1395 | i->p = NULL; |
1396 | } |
1397 | |
1398 | static void setup_string_in_str(struct in_str *i, const char *s) |
1399 | { |
1400 | i->peek = static_peek; |
1401 | i->get = static_get; |
1402 | #if ENABLE_HUSH_INTERACTIVE |
1403 | i->promptme = 1; |
1404 | i->promptmode = 0; /* PS1 */ |
1405 | #endif |
1406 | i->p = s; |
1407 | i->eof_flag = 0; |
1408 | } |
1409 | |
1410 | |
1411 | /* squirrel != NULL means we squirrel away copies of stdin, stdout, |
1412 | * and stderr if they are redirected. */ |
1413 | static int setup_redirects(struct command *prog, int squirrel[]) |
1414 | { |
1415 | int openfd, mode; |
1416 | struct redir_struct *redir; |
1417 | |
1418 | for (redir = prog->redirects; redir; redir = redir->next) { |
1419 | if (redir->dup == -1 && redir->rd_filename == NULL) { |
1420 | /* something went wrong in the parse. Pretend it didn't happen */ |
1421 | continue; |
1422 | } |
1423 | if (redir->dup == -1) { |
1424 | char *p; |
1425 | mode = redir_table[redir->rd_type].mode; |
1426 | //TODO: check redir for names like '\\' |
1427 | p = expand_string_to_string(redir->rd_filename); |
1428 | openfd = open_or_warn(p, mode); |
1429 | free(p); |
1430 | if (openfd < 0) { |
1431 | /* this could get lost if stderr has been redirected, but |
1432 | bash and ash both lose it as well (though zsh doesn't!) */ |
1433 | return 1; |
1434 | } |
1435 | } else { |
1436 | openfd = redir->dup; |
1437 | } |
1438 | |
1439 | if (openfd != redir->fd) { |
1440 | if (squirrel && redir->fd < 3) { |
1441 | squirrel[redir->fd] = dup(redir->fd); |
1442 | } |
1443 | if (openfd == -3) { |
1444 | //close(openfd); // close(-3) ??! |
1445 | } else { |
1446 | dup2(openfd, redir->fd); |
1447 | if (redir->dup == -1) |
1448 | close(openfd); |
1449 | } |
1450 | } |
1451 | } |
1452 | return 0; |
1453 | } |
1454 | |
1455 | static void restore_redirects(int squirrel[]) |
1456 | { |
1457 | int i, fd; |
1458 | for (i = 0; i < 3; i++) { |
1459 | fd = squirrel[i]; |
1460 | if (fd != -1) { |
1461 | /* We simply die on error */ |
1462 | xmove_fd(fd, i); |
1463 | } |
1464 | } |
1465 | } |
1466 | |
1467 | static char **expand_assignments(char **argv, int count) |
1468 | { |
1469 | int i; |
1470 | char **p = NULL; |
1471 | /* Expand assignments into one string each */ |
1472 | for (i = 0; i < count; i++) { |
1473 | p = add_string_to_strings(p, expand_string_to_string(argv[i])); |
1474 | } |
1475 | return p; |
1476 | } |
1477 | |
1478 | /* Called after [v]fork() in run_pipe(), or from builtin_exec(). |
1479 | * Never returns. |
1480 | * XXX no exit() here. If you don't exec, use _exit instead. |
1481 | * The at_exit handlers apparently confuse the calling process, |
1482 | * in particular stdin handling. Not sure why? -- because of vfork! (vda) */ |
1483 | static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) |
1484 | { |
1485 | int rcode; |
1486 | char **new_env; |
1487 | const struct built_in_command *x; |
1488 | |
1489 | /* If a variable is assigned in a forest, and nobody listens, |
1490 | * was it ever really set? |
1491 | */ |
1492 | if (!argv[assignment_cnt]) |
1493 | _exit(EXIT_SUCCESS); |
1494 | |
1495 | new_env = expand_assignments(argv, assignment_cnt); |
1496 | #if BB_MMU |
1497 | putenv_all(new_env); |
1498 | free(new_env); /* optional */ |
1499 | #else |
1500 | nommu_save->new_env = new_env; |
1501 | nommu_save->old_env = putenv_all_and_save_old(new_env); |
1502 | #endif |
1503 | if (argv_expanded) { |
1504 | argv = argv_expanded; |
1505 | } else { |
1506 | argv = expand_strvec_to_strvec(argv); |
1507 | #if !BB_MMU |
1508 | nommu_save->argv = argv; |
1509 | #endif |
1510 | } |
1511 | |
1512 | /* |
1513 | * Check if the command matches any of the builtins. |
1514 | * Depending on context, this might be redundant. But it's |
1515 | * easier to waste a few CPU cycles than it is to figure out |
1516 | * if this is one of those cases. |
1517 | */ |
1518 | for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) { |
1519 | if (strcmp(argv[0], x->cmd) == 0) { |
1520 | debug_printf_exec("running builtin '%s'\n", argv[0]); |
1521 | rcode = x->function(argv); |
1522 | fflush(stdout); |
1523 | _exit(rcode); |
1524 | } |
1525 | } |
1526 | |
1527 | /* Check if the command matches any busybox applets */ |
1528 | #if ENABLE_FEATURE_SH_STANDALONE |
1529 | if (strchr(argv[0], '/') == NULL) { |
1530 | int a = find_applet_by_name(argv[0]); |
1531 | if (a >= 0) { |
1532 | if (APPLET_IS_NOEXEC(a)) { |
1533 | debug_printf_exec("running applet '%s'\n", argv[0]); |
1534 | // is it ok that run_applet_no_and_exit() does exit(), not _exit()? |
1535 | run_applet_no_and_exit(a, argv); |
1536 | } |
1537 | /* re-exec ourselves with the new arguments */ |
1538 | debug_printf_exec("re-execing applet '%s'\n", argv[0]); |
1539 | execvp(bb_busybox_exec_path, argv); |
1540 | /* If they called chroot or otherwise made the binary no longer |
1541 | * executable, fall through */ |
1542 | } |
1543 | } |
1544 | #endif |
1545 | |
1546 | debug_printf_exec("execing '%s'\n", argv[0]); |
1547 | execvp(argv[0], argv); |
1548 | bb_perror_msg("can't exec '%s'", argv[0]); |
1549 | _exit(EXIT_FAILURE); |
1550 | } |
1551 | |
1552 | /* Called after [v]fork() in run_pipe() |
1553 | */ |
1554 | static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) |
1555 | { |
1556 | if (command->argv) |
1557 | pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded); |
1558 | |
1559 | if (command->group) { |
1560 | #if !BB_MMU |
1561 | bb_error_msg_and_die("nested lists are not supported on NOMMU"); |
1562 | #else |
1563 | int rcode; |
1564 | debug_printf_exec("pseudo_exec: run_list\n"); |
1565 | rcode = run_list(command->group); |
1566 | /* OK to leak memory by not calling free_pipe_list, |
1567 | * since this process is about to exit */ |
1568 | _exit(rcode); |
1569 | #endif |
1570 | } |
1571 | |
1572 | /* Can happen. See what bash does with ">foo" by itself. */ |
1573 | debug_printf("trying to pseudo_exec null command\n"); |
1574 | _exit(EXIT_SUCCESS); |
1575 | } |
1576 | |
1577 | #if ENABLE_HUSH_JOB |
1578 | static const char *get_cmdtext(struct pipe *pi) |
1579 | { |
1580 | char **argv; |
1581 | char *p; |
1582 | int len; |
1583 | |
1584 | /* This is subtle. ->cmdtext is created only on first backgrounding. |
1585 | * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...) |
1586 | * On subsequent bg argv is trashed, but we won't use it */ |
1587 | if (pi->cmdtext) |
1588 | return pi->cmdtext; |
1589 | argv = pi->cmds[0].argv; |
1590 | if (!argv || !argv[0]) { |
1591 | pi->cmdtext = xzalloc(1); |
1592 | return pi->cmdtext; |
1593 | } |
1594 | |
1595 | len = 0; |
1596 | do len += strlen(*argv) + 1; while (*++argv); |
1597 | pi->cmdtext = p = xmalloc(len); |
1598 | argv = pi->cmds[0].argv; |
1599 | do { |
1600 | len = strlen(*argv); |
1601 | memcpy(p, *argv, len); |
1602 | p += len; |
1603 | *p++ = ' '; |
1604 | } while (*++argv); |
1605 | p[-1] = '\0'; |
1606 | return pi->cmdtext; |
1607 | } |
1608 | |
1609 | static void insert_bg_job(struct pipe *pi) |
1610 | { |
1611 | struct pipe *thejob; |
1612 | int i; |
1613 | |
1614 | /* Linear search for the ID of the job to use */ |
1615 | pi->jobid = 1; |
1616 | for (thejob = G.job_list; thejob; thejob = thejob->next) |
1617 | if (thejob->jobid >= pi->jobid) |
1618 | pi->jobid = thejob->jobid + 1; |
1619 | |
1620 | /* Add thejob to the list of running jobs */ |
1621 | if (!G.job_list) { |
1622 | thejob = G.job_list = xmalloc(sizeof(*thejob)); |
1623 | } else { |
1624 | for (thejob = G.job_list; thejob->next; thejob = thejob->next) |
1625 | continue; |
1626 | thejob->next = xmalloc(sizeof(*thejob)); |
1627 | thejob = thejob->next; |
1628 | } |
1629 | |
1630 | /* Physically copy the struct job */ |
1631 | memcpy(thejob, pi, sizeof(struct pipe)); |
1632 | thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds); |
1633 | /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */ |
1634 | for (i = 0; i < pi->num_cmds; i++) { |
1635 | // TODO: do we really need to have so many fields which are just dead weight |
1636 | // at execution stage? |
1637 | thejob->cmds[i].pid = pi->cmds[i].pid; |
1638 | /* all other fields are not used and stay zero */ |
1639 | } |
1640 | thejob->next = NULL; |
1641 | thejob->cmdtext = xstrdup(get_cmdtext(pi)); |
1642 | |
1643 | /* We don't wait for background thejobs to return -- append it |
1644 | to the list of backgrounded thejobs and leave it alone */ |
1645 | printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext); |
1646 | G.last_bg_pid = thejob->cmds[0].pid; |
1647 | G.last_jobid = thejob->jobid; |
1648 | } |
1649 | |
1650 | static void remove_bg_job(struct pipe *pi) |
1651 | { |
1652 | struct pipe *prev_pipe; |
1653 | |
1654 | if (pi == G.job_list) { |
1655 | G.job_list = pi->next; |
1656 | } else { |
1657 | prev_pipe = G.job_list; |
1658 | while (prev_pipe->next != pi) |
1659 | prev_pipe = prev_pipe->next; |
1660 | prev_pipe->next = pi->next; |
1661 | } |
1662 | if (G.job_list) |
1663 | G.last_jobid = G.job_list->jobid; |
1664 | else |
1665 | G.last_jobid = 0; |
1666 | } |
1667 | |
1668 | /* Remove a backgrounded job */ |
1669 | static void delete_finished_bg_job(struct pipe *pi) |
1670 | { |
1671 | remove_bg_job(pi); |
1672 | pi->stopped_cmds = 0; |
1673 | free_pipe(pi, 0); |
1674 | free(pi); |
1675 | } |
1676 | #endif /* JOB */ |
1677 | |
1678 | /* Check to see if any processes have exited -- if they |
1679 | * have, figure out why and see if a job has completed */ |
1680 | static int checkjobs(struct pipe* fg_pipe) |
1681 | { |
1682 | int attributes; |
1683 | int status; |
1684 | #if ENABLE_HUSH_JOB |
1685 | struct pipe *pi; |
1686 | #endif |
1687 | pid_t childpid; |
1688 | int rcode = 0; |
1689 | |
1690 | attributes = WUNTRACED; |
1691 | if (fg_pipe == NULL) |
1692 | attributes |= WNOHANG; |
1693 | |
1694 | /* Do we do this right? |
1695 | * bash-3.00# sleep 20 | false |
1696 | * <ctrl-Z pressed> |
1697 | * [3]+ Stopped sleep 20 | false |
1698 | * bash-3.00# echo $? |
1699 | * 1 <========== bg pipe is not fully done, but exitcode is already known! |
1700 | */ |
1701 | |
1702 | //FIXME: non-interactive bash does not continue even if all processes in fg pipe |
1703 | //are stopped. Testcase: "cat | cat" in a script (not on command line) |
1704 | // + killall -STOP cat |
1705 | |
1706 | wait_more: |
1707 | // TODO: safe_waitpid? |
1708 | while ((childpid = waitpid(-1, &status, attributes)) > 0) { |
1709 | int i; |
1710 | const int dead = WIFEXITED(status) || WIFSIGNALED(status); |
1711 | #if DEBUG_JOBS |
1712 | if (WIFSTOPPED(status)) |
1713 | debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n", |
1714 | childpid, WSTOPSIG(status), WEXITSTATUS(status)); |
1715 | if (WIFSIGNALED(status)) |
1716 | debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n", |
1717 | childpid, WTERMSIG(status), WEXITSTATUS(status)); |
1718 | if (WIFEXITED(status)) |
1719 | debug_printf_jobs("pid %d exited, exitcode %d\n", |
1720 | childpid, WEXITSTATUS(status)); |
1721 | #endif |
1722 | /* Were we asked to wait for fg pipe? */ |
1723 | if (fg_pipe) { |
1724 | for (i = 0; i < fg_pipe->num_cmds; i++) { |
1725 | debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid); |
1726 | if (fg_pipe->cmds[i].pid != childpid) |
1727 | continue; |
1728 | /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */ |
1729 | if (dead) { |
1730 | fg_pipe->cmds[i].pid = 0; |
1731 | fg_pipe->alive_cmds--; |
1732 | if (i == fg_pipe->num_cmds - 1) { |
1733 | /* last process gives overall exitstatus */ |
1734 | rcode = WEXITSTATUS(status); |
1735 | IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;) |
1736 | } |
1737 | } else { |
1738 | fg_pipe->cmds[i].is_stopped = 1; |
1739 | fg_pipe->stopped_cmds++; |
1740 | } |
1741 | debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n", |
1742 | fg_pipe->alive_cmds, fg_pipe->stopped_cmds); |
1743 | if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) { |
1744 | /* All processes in fg pipe have exited/stopped */ |
1745 | #if ENABLE_HUSH_JOB |
1746 | if (fg_pipe->alive_cmds) |
1747 | insert_bg_job(fg_pipe); |
1748 | #endif |
1749 | return rcode; |
1750 | } |
1751 | /* There are still running processes in the fg pipe */ |
1752 | goto wait_more; /* do waitpid again */ |
1753 | } |
1754 | /* it wasnt fg_pipe, look for process in bg pipes */ |
1755 | } |
1756 | |
1757 | #if ENABLE_HUSH_JOB |
1758 | /* We asked to wait for bg or orphaned children */ |
1759 | /* No need to remember exitcode in this case */ |
1760 | for (pi = G.job_list; pi; pi = pi->next) { |
1761 | for (i = 0; i < pi->num_cmds; i++) { |
1762 | if (pi->cmds[i].pid == childpid) |
1763 | goto found_pi_and_prognum; |
1764 | } |
1765 | } |
1766 | /* Happens when shell is used as init process (init=/bin/sh) */ |
1767 | debug_printf("checkjobs: pid %d was not in our list!\n", childpid); |
1768 | continue; /* do waitpid again */ |
1769 | |
1770 | found_pi_and_prognum: |
1771 | if (dead) { |
1772 | /* child exited */ |
1773 | pi->cmds[i].pid = 0; |
1774 | pi->alive_cmds--; |
1775 | if (!pi->alive_cmds) { |
1776 | printf(JOB_STATUS_FORMAT, pi->jobid, |
1777 | "Done", pi->cmdtext); |
1778 | delete_finished_bg_job(pi); |
1779 | } |
1780 | } else { |
1781 | /* child stopped */ |
1782 | pi->cmds[i].is_stopped = 1; |
1783 | pi->stopped_cmds++; |
1784 | } |
1785 | #endif |
1786 | } /* while (waitpid succeeds)... */ |
1787 | |
1788 | /* wait found no children or failed */ |
1789 | |
1790 | if (childpid && errno != ECHILD) |
1791 | bb_perror_msg("waitpid"); |
1792 | return rcode; |
1793 | } |
1794 | |
1795 | #if ENABLE_HUSH_JOB |
1796 | static int checkjobs_and_fg_shell(struct pipe* fg_pipe) |
1797 | { |
1798 | pid_t p; |
1799 | int rcode = checkjobs(fg_pipe); |
1800 | /* Job finished, move the shell to the foreground */ |
1801 | p = getpgid(0); /* pgid of our process */ |
1802 | debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p); |
1803 | tcsetpgrp(G.interactive_fd, p); |
1804 | return rcode; |
1805 | } |
1806 | #endif |
1807 | |
1808 | /* run_pipe() starts all the jobs, but doesn't wait for anything |
1809 | * to finish. See checkjobs(). |
1810 | * |
1811 | * return code is normally -1, when the caller has to wait for children |
1812 | * to finish to determine the exit status of the pipe. If the pipe |
1813 | * is a simple builtin command, however, the action is done by the |
1814 | * time run_pipe returns, and the exit code is provided as the |
1815 | * return value. |
1816 | * |
1817 | * The input of the pipe is always stdin, the output is always |
1818 | * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus, |
1819 | * because it tries to avoid running the command substitution in |
1820 | * subshell, when that is in fact necessary. The subshell process |
1821 | * now has its stdout directed to the input of the appropriate pipe, |
1822 | * so this routine is noticeably simpler. |
1823 | * |
1824 | * Returns -1 only if started some children. IOW: we have to |
1825 | * mask out retvals of builtins etc with 0xff! |
1826 | */ |
1827 | static int run_pipe(struct pipe *pi) |
1828 | { |
1829 | int i; |
1830 | int nextin; |
1831 | int pipefds[2]; /* pipefds[0] is for reading */ |
1832 | struct command *command; |
1833 | char **argv_expanded; |
1834 | char **argv; |
1835 | const struct built_in_command *x; |
1836 | char *p; |
1837 | /* it is not always needed, but we aim to smaller code */ |
1838 | int squirrel[] = { -1, -1, -1 }; |
1839 | int rcode; |
1840 | const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG); |
1841 | |
1842 | debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg); |
1843 | |
1844 | #if ENABLE_HUSH_JOB |
1845 | pi->pgrp = -1; |
1846 | #endif |
1847 | pi->alive_cmds = 1; |
1848 | pi->stopped_cmds = 0; |
1849 | |
1850 | /* Check if this is a simple builtin (not part of a pipe). |
1851 | * Builtins within pipes have to fork anyway, and are handled in |
1852 | * pseudo_exec. "echo foo | read bar" doesn't work on bash, either. |
1853 | */ |
1854 | command = &(pi->cmds[0]); |
1855 | |
1856 | #if ENABLE_HUSH_FUNCTIONS |
1857 | if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) { |
1858 | /* We "execute" function definition */ |
1859 | bb_error_msg("here we ought to remember function definition, and go on"); |
1860 | return EXIT_SUCCESS; |
1861 | } |
1862 | #endif |
1863 | |
1864 | if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) { |
1865 | debug_printf("non-subshell grouping\n"); |
1866 | setup_redirects(command, squirrel); |
1867 | debug_printf_exec(": run_list\n"); |
1868 | rcode = run_list(command->group) & 0xff; |
1869 | restore_redirects(squirrel); |
1870 | debug_printf_exec("run_pipe return %d\n", rcode); |
1871 | IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;) |
1872 | return rcode; |
1873 | } |
1874 | |
1875 | argv = command->argv; |
1876 | argv_expanded = NULL; |
1877 | |
1878 | if (single_and_fg && argv != NULL) { |
1879 | char **new_env = NULL; |
1880 | char **old_env = NULL; |
1881 | |
1882 | i = command->assignment_cnt; |
1883 | if (i != 0 && argv[i] == NULL) { |
1884 | /* assignments, but no command: set local environment */ |
1885 | for (i = 0; argv[i] != NULL; i++) { |
1886 | debug_printf("local environment set: %s\n", argv[i]); |
1887 | p = expand_string_to_string(argv[i]); |
1888 | set_local_var(p, 0); |
1889 | } |
1890 | return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */ |
1891 | } |
1892 | |
1893 | /* Expand the rest into (possibly) many strings each */ |
1894 | argv_expanded = expand_strvec_to_strvec(argv + i); |
1895 | |
1896 | for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) { |
1897 | if (strcmp(argv_expanded[0], x->cmd) != 0) |
1898 | continue; |
1899 | if (x->function == builtin_exec && argv_expanded[1] == NULL) { |
1900 | debug_printf("exec with redirects only\n"); |
1901 | setup_redirects(command, NULL); |
1902 | rcode = EXIT_SUCCESS; |
1903 | goto clean_up_and_ret1; |
1904 | } |
1905 | debug_printf("builtin inline %s\n", argv_expanded[0]); |
1906 | /* XXX setup_redirects acts on file descriptors, not FILEs. |
1907 | * This is perfect for work that comes after exec(). |
1908 | * Is it really safe for inline use? Experimentally, |
1909 | * things seem to work with glibc. */ |
1910 | setup_redirects(command, squirrel); |
1911 | new_env = expand_assignments(argv, command->assignment_cnt); |
1912 | old_env = putenv_all_and_save_old(new_env); |
1913 | debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]); |
1914 | rcode = x->function(argv_expanded) & 0xff; |
1915 | #if ENABLE_FEATURE_SH_STANDALONE |
1916 | clean_up_and_ret: |
1917 | #endif |
1918 | restore_redirects(squirrel); |
1919 | free_strings_and_unsetenv(new_env, 1); |
1920 | putenv_all(old_env); |
1921 | free(old_env); /* not free_strings()! */ |
1922 | clean_up_and_ret1: |
1923 | free(argv_expanded); |
1924 | IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;) |
1925 | debug_printf_exec("run_pipe return %d\n", rcode); |
1926 | return rcode; |
1927 | } |
1928 | #if ENABLE_FEATURE_SH_STANDALONE |
1929 | i = find_applet_by_name(argv_expanded[0]); |
1930 | if (i >= 0 && APPLET_IS_NOFORK(i)) { |
1931 | setup_redirects(command, squirrel); |
1932 | save_nofork_data(&G.nofork_save); |
1933 | new_env = expand_assignments(argv, command->assignment_cnt); |
1934 | old_env = putenv_all_and_save_old(new_env); |
1935 | debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]); |
1936 | rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded); |
1937 | goto clean_up_and_ret; |
1938 | } |
1939 | #endif |
1940 | } |
1941 | |
1942 | /* NB: argv_expanded may already be created, and that |
1943 | * might include `cmd` runs! Do not rerun it! We *must* |
1944 | * use argv_expanded if it's non-NULL */ |
1945 | |
1946 | /* Disable job control signals for shell (parent) and |
1947 | * for initial child code after fork */ |
1948 | set_jobctrl_sighandler(SIG_IGN); |
1949 | |
1950 | /* Going to fork a child per each pipe member */ |
1951 | pi->alive_cmds = 0; |
1952 | nextin = 0; |
1953 | |
1954 | for (i = 0; i < pi->num_cmds; i++) { |
1955 | #if !BB_MMU |
1956 | volatile nommu_save_t nommu_save; |
1957 | nommu_save.new_env = NULL; |
1958 | nommu_save.old_env = NULL; |
1959 | nommu_save.argv = NULL; |
1960 | #endif |
1961 | command = &(pi->cmds[i]); |
1962 | if (command->argv) { |
1963 | debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]); |
1964 | } else |
1965 | debug_printf_exec(": pipe member with no argv\n"); |
1966 | |
1967 | /* pipes are inserted between pairs of commands */ |
1968 | pipefds[0] = 0; |
1969 | pipefds[1] = 1; |
1970 | if ((i + 1) < pi->num_cmds) |
1971 | xpipe(pipefds); |
1972 | |
1973 | command->pid = BB_MMU ? fork() : vfork(); |
1974 | if (!command->pid) { /* child */ |
1975 | if (ENABLE_HUSH_JOB) |
1976 | die_sleep = 0; /* let nofork's xfuncs die */ |
1977 | #if ENABLE_HUSH_JOB |
1978 | /* Every child adds itself to new process group |
1979 | * with pgid == pid_of_first_child_in_pipe */ |
1980 | if (G.run_list_level == 1 && G.interactive_fd) { |
1981 | pid_t pgrp; |
1982 | /* Don't do pgrp restore anymore on fatal signals */ |
1983 | set_fatal_sighandler(SIG_DFL); |
1984 | pgrp = pi->pgrp; |
1985 | if (pgrp < 0) /* true for 1st process only */ |
1986 | pgrp = getpid(); |
1987 | if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) { |
1988 | /* We do it in *every* child, not just first, |
1989 | * to avoid races */ |
1990 | tcsetpgrp(G.interactive_fd, pgrp); |
1991 | } |
1992 | } |
1993 | #endif |
1994 | xmove_fd(nextin, 0); |
1995 | xmove_fd(pipefds[1], 1); /* write end */ |
1996 | if (pipefds[0] > 1) |
1997 | close(pipefds[0]); /* read end */ |
1998 | /* Like bash, explicit redirects override pipes, |
1999 | * and the pipe fd is available for dup'ing. */ |
2000 | setup_redirects(command, NULL); |
2001 | |
2002 | /* Restore default handlers just prior to exec */ |
2003 | set_jobctrl_sighandler(SIG_DFL); |
2004 | set_misc_sighandler(SIG_DFL); |
2005 | signal(SIGCHLD, SIG_DFL); |
2006 | /* Stores to nommu_save list of env vars putenv'ed |
2007 | * (NOMMU, on MMU we don't need that) */ |
2008 | /* cast away volatility... */ |
2009 | pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded); |
2010 | /* pseudo_exec() does not return */ |
2011 | } |
2012 | /* parent */ |
2013 | #if !BB_MMU |
2014 | /* Clean up after vforked child */ |
2015 | free(nommu_save.argv); |
2016 | free_strings_and_unsetenv(nommu_save.new_env, 1); |
2017 | putenv_all(nommu_save.old_env); |
2018 | #endif |
2019 | free(argv_expanded); |
2020 | argv_expanded = NULL; |
2021 | if (command->pid < 0) { /* [v]fork failed */ |
2022 | /* Clearly indicate, was it fork or vfork */ |
2023 | bb_perror_msg(BB_MMU ? "fork" : "vfork"); |
2024 | } else { |
2025 | pi->alive_cmds++; |
2026 | #if ENABLE_HUSH_JOB |
2027 | /* Second and next children need to know pid of first one */ |
2028 | if (pi->pgrp < 0) |
2029 | pi->pgrp = command->pid; |
2030 | #endif |
2031 | } |
2032 | |
2033 | if (i) |
2034 | close(nextin); |
2035 | if ((i + 1) < pi->num_cmds) |
2036 | close(pipefds[1]); /* write end */ |
2037 | /* Pass read (output) pipe end to next iteration */ |
2038 | nextin = pipefds[0]; |
2039 | } |
2040 | |
2041 | if (!pi->alive_cmds) { |
2042 | debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n"); |
2043 | return 1; |
2044 | } |
2045 | |
2046 | debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds); |
2047 | return -1; |
2048 | } |
2049 | |
2050 | #ifndef debug_print_tree |
2051 | static void debug_print_tree(struct pipe *pi, int lvl) |
2052 | { |
2053 | static const char *const PIPE[] = { |
2054 | [PIPE_SEQ] = "SEQ", |
2055 | [PIPE_AND] = "AND", |
2056 | [PIPE_OR ] = "OR" , |
2057 | [PIPE_BG ] = "BG" , |
2058 | }; |
2059 | static const char *RES[] = { |
2060 | [RES_NONE ] = "NONE" , |
2061 | #if ENABLE_HUSH_IF |
2062 | [RES_IF ] = "IF" , |
2063 | [RES_THEN ] = "THEN" , |
2064 | [RES_ELIF ] = "ELIF" , |
2065 | [RES_ELSE ] = "ELSE" , |
2066 | [RES_FI ] = "FI" , |
2067 | #endif |
2068 | #if ENABLE_HUSH_LOOPS |
2069 | [RES_FOR ] = "FOR" , |
2070 | [RES_WHILE] = "WHILE", |
2071 | [RES_UNTIL] = "UNTIL", |
2072 | [RES_DO ] = "DO" , |
2073 | [RES_DONE ] = "DONE" , |
2074 | #endif |
2075 | #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE |
2076 | [RES_IN ] = "IN" , |
2077 | #endif |
2078 | #if ENABLE_HUSH_CASE |
2079 | [RES_CASE ] = "CASE" , |
2080 | [RES_MATCH] = "MATCH", |
2081 | [RES_CASEI] = "CASEI", |
2082 | [RES_ESAC ] = "ESAC" , |
2083 | #endif |
2084 | [RES_XXXX ] = "XXXX" , |
2085 | [RES_SNTX ] = "SNTX" , |
2086 | }; |
2087 | static const char *const GRPTYPE[] = { |
2088 | "()", |
2089 | "{}", |
2090 | #if ENABLE_HUSH_FUNCTIONS |
2091 | "func()", |
2092 | #endif |
2093 | }; |
2094 | |
2095 | int pin, prn; |
2096 | |
2097 | pin = 0; |
2098 | while (pi) { |
2099 | fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "", |
2100 | pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]); |
2101 | prn = 0; |
2102 | while (prn < pi->num_cmds) { |
2103 | struct command *command = &pi->cmds[prn]; |
2104 | char **argv = command->argv; |
2105 | |
2106 | fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt); |
2107 | if (command->group) { |
2108 | fprintf(stderr, " group %s: (argv=%p)\n", |
2109 | GRPTYPE[command->grp_type], |
2110 | argv); |
2111 | debug_print_tree(command->group, lvl+1); |
2112 | prn++; |
2113 | continue; |
2114 | } |
2115 | if (argv) while (*argv) { |
2116 | fprintf(stderr, " '%s'", *argv); |
2117 | argv++; |
2118 | } |
2119 | fprintf(stderr, "\n"); |
2120 | prn++; |
2121 | } |
2122 | pi = pi->next; |
2123 | pin++; |
2124 | } |
2125 | } |
2126 | #endif |
2127 | |
2128 | /* NB: called by pseudo_exec, and therefore must not modify any |
2129 | * global data until exec/_exit (we can be a child after vfork!) */ |
2130 | static int run_list(struct pipe *pi) |
2131 | { |
2132 | #if ENABLE_HUSH_CASE |
2133 | char *case_word = NULL; |
2134 | #endif |
2135 | #if ENABLE_HUSH_LOOPS |
2136 | struct pipe *loop_top = NULL; |
2137 | char *for_varname = NULL; |
2138 | char **for_lcur = NULL; |
2139 | char **for_list = NULL; |
2140 | #endif |
2141 | smallint flag_skip = 1; |
2142 | smalluint rcode = 0; /* probably just for compiler */ |
2143 | #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE |
2144 | smalluint cond_code = 0; |
2145 | #else |
2146 | enum { cond_code = 0, }; |
2147 | #endif |
2148 | /*enum reserved_style*/ smallint rword = RES_NONE; |
2149 | /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX; |
2150 | |
2151 | debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1); |
2152 | |
2153 | #if ENABLE_HUSH_LOOPS |
2154 | /* Check syntax for "for" */ |
2155 | for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) { |
2156 | if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN) |
2157 | continue; |
2158 | /* current word is FOR or IN (BOLD in comments below) */ |
2159 | if (cpipe->next == NULL) { |
2160 | syntax("malformed for"); |
2161 | debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level); |
2162 | return 1; |
2163 | } |
2164 | /* "FOR v; do ..." and "for v IN a b; do..." are ok */ |
2165 | if (cpipe->next->res_word == RES_DO) |
2166 | continue; |
2167 | /* next word is not "do". It must be "in" then ("FOR v in ...") */ |
2168 | if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */ |
2169 | || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */ |
2170 | ) { |
2171 | syntax("malformed for"); |
2172 | debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level); |
2173 | return 1; |
2174 | } |
2175 | } |
2176 | #endif |
2177 | |
2178 | /* Past this point, all code paths should jump to ret: label |
2179 | * in order to return, no direct "return" statements please. |
2180 | * This helps to ensure that no memory is leaked. */ |
2181 | |
2182 | #if ENABLE_HUSH_JOB |
2183 | /* Example of nested list: "while true; do { sleep 1 | exit 2; } done". |
2184 | * We are saving state before entering outermost list ("while...done") |
2185 | * so that ctrl-Z will correctly background _entire_ outermost list, |
2186 | * not just a part of it (like "sleep 1 | exit 2") */ |
2187 | if (++G.run_list_level == 1 && G.interactive_fd) { |
2188 | if (sigsetjmp(G.toplevel_jb, 1)) { |
2189 | /* ctrl-Z forked and we are parent; or ctrl-C. |
2190 | * Sighandler has longjmped us here */ |
2191 | signal(SIGINT, SIG_IGN); |
2192 | signal(SIGTSTP, SIG_IGN); |
2193 | /* Restore level (we can be coming from deep inside |
2194 | * nested levels) */ |
2195 | G.run_list_level = 1; |
2196 | #if ENABLE_FEATURE_SH_STANDALONE |
2197 | if (G.nofork_save.saved) { /* if save area is valid */ |
2198 | debug_printf_jobs("exiting nofork early\n"); |
2199 | restore_nofork_data(&G.nofork_save); |
2200 | } |
2201 | #endif |
2202 | if (G.ctrl_z_flag) { |
2203 | /* ctrl-Z has forked and stored pid of the child in pi->pid. |
2204 | * Remember this child as background job */ |
2205 | insert_bg_job(pi); |
2206 | } else { |
2207 | /* ctrl-C. We just stop doing whatever we were doing */ |
2208 | bb_putchar('\n'); |
2209 | } |
2210 | USE_HUSH_LOOPS(loop_top = NULL;) |
2211 | USE_HUSH_LOOPS(G.depth_of_loop = 0;) |
2212 | rcode = 0; |
2213 | goto ret; |
2214 | } |
2215 | /* ctrl-Z handler will store pid etc in pi */ |
2216 | G.toplevel_list = pi; |
2217 | G.ctrl_z_flag = 0; |
2218 | #if ENABLE_FEATURE_SH_STANDALONE |
2219 | G.nofork_save.saved = 0; /* in case we will run a nofork later */ |
2220 | #endif |
2221 | signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z); |
2222 | signal(SIGINT, handler_ctrl_c); |
2223 | } |
2224 | #endif /* JOB */ |
2225 | |
2226 | /* Go through list of pipes, (maybe) executing them. */ |
2227 | for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) { |
2228 | IF_HAS_KEYWORDS(rword = pi->res_word;) |
2229 | IF_HAS_NO_KEYWORDS(rword = RES_NONE;) |
2230 | debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n", |
2231 | rword, cond_code, skip_more_for_this_rword); |
2232 | #if ENABLE_HUSH_LOOPS |
2233 | if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR) |
2234 | && loop_top == NULL /* avoid bumping G.depth_of_loop twice */ |
2235 | ) { |
2236 | /* start of a loop: remember where loop starts */ |
2237 | loop_top = pi; |
2238 | G.depth_of_loop++; |
2239 | } |
2240 | #endif |
2241 | if (rword == skip_more_for_this_rword && flag_skip) { |
2242 | if (pi->followup == PIPE_SEQ) |
2243 | flag_skip = 0; |
2244 | /* it is "<false> && CMD" or "<true> || CMD" |
2245 | * and we should not execute CMD */ |
2246 | continue; |
2247 | } |
2248 | flag_skip = 1; |
2249 | skip_more_for_this_rword = RES_XXXX; |
2250 | #if ENABLE_HUSH_IF |
2251 | if (cond_code) { |
2252 | if (rword == RES_THEN) { |
2253 | /* "if <false> THEN cmd": skip cmd */ |
2254 | continue; |
2255 | } |
2256 | } else { |
2257 | if (rword == RES_ELSE || rword == RES_ELIF) { |
2258 | /* "if <true> then ... ELSE/ELIF cmd": |
2259 | * skip cmd and all following ones */ |
2260 | break; |
2261 | } |
2262 | } |
2263 | #endif |
2264 | #if ENABLE_HUSH_LOOPS |
2265 | if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */ |
2266 | if (!for_lcur) { |
2267 | /* first loop through for */ |
2268 | |
2269 | static const char encoded_dollar_at[] ALIGN1 = { |
2270 | SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0' |
2271 | }; /* encoded representation of "$@" */ |
2272 | static const char *const encoded_dollar_at_argv[] = { |
2273 | encoded_dollar_at, NULL |
2274 | }; /* argv list with one element: "$@" */ |
2275 | char **vals; |
2276 | |
2277 | vals = (char**)encoded_dollar_at_argv; |
2278 | if (pi->next->res_word == RES_IN) { |
2279 | /* if no variable values after "in" we skip "for" */ |
2280 | if (!pi->next->cmds[0].argv) |
2281 | break; |
2282 | vals = pi->next->cmds[0].argv; |
2283 | } /* else: "for var; do..." -> assume "$@" list */ |
2284 | /* create list of variable values */ |
2285 | debug_print_strings("for_list made from", vals); |
2286 | for_list = expand_strvec_to_strvec(vals); |
2287 | for_lcur = for_list; |
2288 | debug_print_strings("for_list", for_list); |
2289 | for_varname = pi->cmds[0].argv[0]; |
2290 | pi->cmds[0].argv[0] = NULL; |
2291 | } |
2292 | free(pi->cmds[0].argv[0]); |
2293 | if (!*for_lcur) { |
2294 | /* "for" loop is over, clean up */ |
2295 | free(for_list); |
2296 | for_list = NULL; |
2297 | for_lcur = NULL; |
2298 | pi->cmds[0].argv[0] = for_varname; |
2299 | break; |
2300 | } |
2301 | /* insert next value from for_lcur */ |
2302 | //TODO: does it need escaping? |
2303 | pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++); |
2304 | pi->cmds[0].assignment_cnt = 1; |
2305 | } |
2306 | if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */ |
2307 | continue; |
2308 | if (rword == RES_DONE) { |
2309 | continue; /* "done" has no cmds too */ |
2310 | } |
2311 | #endif |
2312 | #if ENABLE_HUSH_CASE |
2313 | if (rword == RES_CASE) { |
2314 | case_word = expand_strvec_to_string(pi->cmds->argv); |
2315 | continue; |
2316 | } |
2317 | if (rword == RES_MATCH) { |
2318 | char **argv; |
2319 | |
2320 | if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */ |
2321 | break; |
2322 | /* all prev words didn't match, does this one match? */ |
2323 | argv = pi->cmds->argv; |
2324 | while (*argv) { |
2325 | char *pattern = expand_string_to_string(*argv); |
2326 | /* TODO: which FNM_xxx flags to use? */ |
2327 | cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0); |
2328 | free(pattern); |
2329 | if (cond_code == 0) { /* match! we will execute this branch */ |
2330 | free(case_word); /* make future "word)" stop */ |
2331 | case_word = NULL; |
2332 | break; |
2333 | } |
2334 | argv++; |
2335 | } |
2336 | continue; |
2337 | } |
2338 | if (rword == RES_CASEI) { /* inside of a case branch */ |
2339 | if (cond_code != 0) |
2340 | continue; /* not matched yet, skip this pipe */ |
2341 | } |
2342 | #endif |
2343 | if (pi->num_cmds == 0) |
2344 | continue; |
2345 | |
2346 | /* After analyzing all keywords and conditions, we decided |
2347 | * to execute this pipe. NB: has to do checkjobs(NULL) |
2348 | * after run_pipe() to collect any background children, |
2349 | * even if list execution is to be stopped. */ |
2350 | debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds); |
2351 | { |
2352 | int r; |
2353 | #if ENABLE_HUSH_LOOPS |
2354 | G.flag_break_continue = 0; |
2355 | #endif |
2356 | rcode = r = run_pipe(pi); /* NB: rcode is a smallint */ |
2357 | if (r != -1) { |
2358 | /* we only ran a builtin: rcode is already known |
2359 | * and we don't need to wait for anything. */ |
2360 | #if ENABLE_HUSH_LOOPS |
2361 | /* was it "break" or "continue"? */ |
2362 | if (G.flag_break_continue) { |
2363 | smallint fbc = G.flag_break_continue; |
2364 | /* we might fall into outer *loop*, |
2365 | * don't want to break it too */ |
2366 | if (loop_top) { |
2367 | G.depth_break_continue--; |
2368 | if (G.depth_break_continue == 0) |
2369 | G.flag_break_continue = 0; |
2370 | /* else: e.g. "continue 2" should *break* once, *then* continue */ |
2371 | } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */ |
2372 | if (G.depth_break_continue != 0 || fbc == BC_BREAK) |
2373 | goto check_jobs_and_break; |
2374 | /* "continue": simulate end of loop */ |
2375 | rword = RES_DONE; |
2376 | continue; |
2377 | } |
2378 | #endif |
2379 | } else if (pi->followup == PIPE_BG) { |
2380 | /* what does bash do with attempts to background builtins? */ |
2381 | /* even bash 3.2 doesn't do that well with nested bg: |
2382 | * try "{ { sleep 10; echo DEEP; } & echo HERE; } &". |
2383 | * I'm NOT treating inner &'s as jobs */ |
2384 | #if ENABLE_HUSH_JOB |
2385 | if (G.run_list_level == 1) |
2386 | insert_bg_job(pi); |
2387 | #endif |
2388 | rcode = 0; /* EXIT_SUCCESS */ |
2389 | } else { |
2390 | #if ENABLE_HUSH_JOB |
2391 | if (G.run_list_level == 1 && G.interactive_fd) { |
2392 | /* waits for completion, then fg's main shell */ |
2393 | rcode = checkjobs_and_fg_shell(pi); |
2394 | debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode); |
2395 | } else |
2396 | #endif |
2397 | { /* this one just waits for completion */ |
2398 | rcode = checkjobs(pi); |
2399 | debug_printf_exec(": checkjobs returned %d\n", rcode); |
2400 | } |
2401 | } |
2402 | } |
2403 | debug_printf_exec(": setting last_return_code=%d\n", rcode); |
2404 | G.last_return_code = rcode; |
2405 | |
2406 | /* Analyze how result affects subsequent commands */ |
2407 | #if ENABLE_HUSH_IF |
2408 | if (rword == RES_IF || rword == RES_ELIF) |
2409 | cond_code = rcode; |
2410 | #endif |
2411 | #if ENABLE_HUSH_LOOPS |
2412 | if (rword == RES_WHILE) { |
2413 | if (rcode) { |
2414 | rcode = 0; /* "while false; do...done" - exitcode 0 */ |
2415 | goto check_jobs_and_break; |
2416 | } |
2417 | } |
2418 | if (rword == RES_UNTIL) { |
2419 | if (!rcode) { |
2420 | check_jobs_and_break: |
2421 | checkjobs(NULL); |
2422 | break; |
2423 | } |
2424 | } |
2425 | #endif |
2426 | if ((rcode == 0 && pi->followup == PIPE_OR) |
2427 | || (rcode != 0 && pi->followup == PIPE_AND) |
2428 | ) { |
2429 | skip_more_for_this_rword = rword; |
2430 | } |
2431 | checkjobs(NULL); |
2432 | } /* for (pi) */ |
2433 | |
2434 | #if ENABLE_HUSH_JOB |
2435 | if (G.ctrl_z_flag) { |
2436 | /* ctrl-Z forked somewhere in the past, we are the child, |
2437 | * and now we completed running the list. Exit. */ |
2438 | //TODO: _exit? |
2439 | exit(rcode); |
2440 | } |
2441 | ret: |
2442 | if (!--G.run_list_level && G.interactive_fd) { |
2443 | signal(SIGTSTP, SIG_IGN); |
2444 | signal(SIGINT, SIG_IGN); |
2445 | } |
2446 | #endif |
2447 | debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode); |
2448 | #if ENABLE_HUSH_LOOPS |
2449 | if (loop_top) |
2450 | G.depth_of_loop--; |
2451 | free(for_list); |
2452 | #endif |
2453 | #if ENABLE_HUSH_CASE |
2454 | free(case_word); |
2455 | #endif |
2456 | return rcode; |
2457 | } |
2458 | |
2459 | /* return code is the exit status of the pipe */ |
2460 | static int free_pipe(struct pipe *pi, int indent) |
2461 | { |
2462 | char **p; |
2463 | struct command *command; |
2464 | struct redir_struct *r, *rnext; |
2465 | int a, i, ret_code = 0; |
2466 | |
2467 | if (pi->stopped_cmds > 0) |
2468 | return ret_code; |
2469 | debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid()); |
2470 | for (i = 0; i < pi->num_cmds; i++) { |
2471 | command = &pi->cmds[i]; |
2472 | debug_printf_clean("%s command %d:\n", indenter(indent), i); |
2473 | if (command->argv) { |
2474 | for (a = 0, p = command->argv; *p; a++, p++) { |
2475 | debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p); |
2476 | } |
2477 | free_strings(command->argv); |
2478 | command->argv = NULL; |
2479 | } else if (command->group) { |
2480 | debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type); |
2481 | ret_code = free_pipe_list(command->group, indent+3); |
2482 | debug_printf_clean("%s end group\n", indenter(indent)); |
2483 | } else { |
2484 | debug_printf_clean("%s (nil)\n", indenter(indent)); |
2485 | } |
2486 | for (r = command->redirects; r; r = rnext) { |
2487 | debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip); |
2488 | if (r->dup == -1) { |
2489 | /* guard against the case >$FOO, where foo is unset or blank */ |
2490 | if (r->rd_filename) { |
2491 | debug_printf_clean(" %s\n", r->rd_filename); |
2492 | free(r->rd_filename); |
2493 | r->rd_filename = NULL; |
2494 | } |
2495 | } else { |
2496 | debug_printf_clean("&%d\n", r->dup); |
2497 | } |
2498 | rnext = r->next; |
2499 | free(r); |
2500 | } |
2501 | command->redirects = NULL; |
2502 | } |
2503 | free(pi->cmds); /* children are an array, they get freed all at once */ |
2504 | pi->cmds = NULL; |
2505 | #if ENABLE_HUSH_JOB |
2506 | free(pi->cmdtext); |
2507 | pi->cmdtext = NULL; |
2508 | #endif |
2509 | return ret_code; |
2510 | } |
2511 | |
2512 | static int free_pipe_list(struct pipe *head, int indent) |
2513 | { |
2514 | int rcode = 0; /* if list has no members */ |
2515 | struct pipe *pi, *next; |
2516 | |
2517 | for (pi = head; pi; pi = next) { |
2518 | #if HAS_KEYWORDS |
2519 | debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word); |
2520 | #endif |
2521 | rcode = free_pipe(pi, indent); |
2522 | debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup); |
2523 | next = pi->next; |
2524 | /*pi->next = NULL;*/ |
2525 | free(pi); |
2526 | } |
2527 | return rcode; |
2528 | } |
2529 | |
2530 | /* Select which version we will use */ |
2531 | static int run_and_free_list(struct pipe *pi) |
2532 | { |
2533 | int rcode = 0; |
2534 | debug_printf_exec("run_and_free_list entered\n"); |
2535 | if (!G.fake_mode) { |
2536 | debug_printf_exec(": run_list with %d members\n", pi->num_cmds); |
2537 | rcode = run_list(pi); |
2538 | } |
2539 | /* free_pipe_list has the side effect of clearing memory. |
2540 | * In the long run that function can be merged with run_list, |
2541 | * but doing that now would hobble the debugging effort. */ |
2542 | free_pipe_list(pi, /* indent: */ 0); |
2543 | debug_printf_exec("run_and_free_list return %d\n", rcode); |
2544 | return rcode; |
2545 | } |
2546 | |
2547 | |
2548 | /* expand_strvec_to_strvec() takes a list of strings, expands |
2549 | * all variable references within and returns a pointer to |
2550 | * a list of expanded strings, possibly with larger number |
2551 | * of strings. (Think VAR="a b"; echo $VAR). |
2552 | * This new list is allocated as a single malloc block. |
2553 | * NULL-terminated list of char* pointers is at the beginning of it, |
2554 | * followed by strings themself. |
2555 | * Caller can deallocate entire list by single free(list). */ |
2556 | |
2557 | /* Store given string, finalizing the word and starting new one whenever |
2558 | * we encounter IFS char(s). This is used for expanding variable values. |
2559 | * End-of-string does NOT finalize word: think about 'echo -$VAR-' */ |
2560 | static int expand_on_ifs(o_string *output, int n, const char *str) |
2561 | { |
2562 | while (1) { |
2563 | int word_len = strcspn(str, G.ifs); |
2564 | if (word_len) { |
2565 | if (output->o_quote || !output->o_glob) |
2566 | o_addQstr(output, str, word_len); |
2567 | else /* protect backslashes against globbing up :) */ |
2568 | o_addstr_duplicate_backslash(output, str, word_len); |
2569 | str += word_len; |
2570 | } |
2571 | if (!*str) /* EOL - do not finalize word */ |
2572 | break; |
2573 | o_addchr(output, '\0'); |
2574 | debug_print_list("expand_on_ifs", output, n); |
2575 | n = o_save_ptr(output, n); |
2576 | str += strspn(str, G.ifs); /* skip ifs chars */ |
2577 | } |
2578 | debug_print_list("expand_on_ifs[1]", output, n); |
2579 | return n; |
2580 | } |
2581 | |
2582 | /* Expand all variable references in given string, adding words to list[] |
2583 | * at n, n+1,... positions. Return updated n (so that list[n] is next one |
2584 | * to be filled). This routine is extremely tricky: has to deal with |
2585 | * variables/parameters with whitespace, $* and $@, and constructs like |
2586 | * 'echo -$*-'. If you play here, you must run testsuite afterwards! */ |
2587 | static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask) |
2588 | { |
2589 | /* or_mask is either 0 (normal case) or 0x80 |
2590 | * (expansion of right-hand side of assignment == 1-element expand. |
2591 | * It will also do no globbing, and thus we must not backslash-quote!) */ |
2592 | |
2593 | char first_ch, ored_ch; |
2594 | int i; |
2595 | const char *val; |
2596 | char *p; |
2597 | |
2598 | ored_ch = 0; |
2599 | |
2600 | debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg); |
2601 | debug_print_list("expand_vars_to_list", output, n); |
2602 | n = o_save_ptr(output, n); |
2603 | debug_print_list("expand_vars_to_list[0]", output, n); |
2604 | |
2605 | while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) { |
2606 | #if ENABLE_HUSH_TICK |
2607 | o_string subst_result = NULL_O_STRING; |
2608 | #endif |
2609 | o_addstr(output, arg, p - arg); |
2610 | debug_print_list("expand_vars_to_list[1]", output, n); |
2611 | arg = ++p; |
2612 | p = strchr(p, SPECIAL_VAR_SYMBOL); |
2613 | |
2614 | first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */ |
2615 | /* "$@" is special. Even if quoted, it can still |
2616 | * expand to nothing (not even an empty string) */ |
2617 | if ((first_ch & 0x7f) != '@') |
2618 | ored_ch |= first_ch; |
2619 | val = NULL; |
2620 | switch (first_ch & 0x7f) { |
2621 | /* Highest bit in first_ch indicates that var is double-quoted */ |
2622 | case '$': /* pid */ |
2623 | val = utoa(G.root_pid); |
2624 | break; |
2625 | case '!': /* bg pid */ |
2626 | val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)""; |
2627 | break; |
2628 | case '?': /* exitcode */ |
2629 | val = utoa(G.last_return_code); |
2630 | break; |
2631 | case '#': /* argc */ |
2632 | val = utoa(G.global_argc ? G.global_argc-1 : 0); |
2633 | break; |
2634 | case '*': |
2635 | case '@': |
2636 | i = 1; |
2637 | if (!G.global_argv[i]) |
2638 | break; |
2639 | ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */ |
2640 | if (!(first_ch & 0x80)) { /* unquoted $* or $@ */ |
2641 | smallint sv = output->o_quote; |
2642 | /* unquoted var's contents should be globbed, so don't quote */ |
2643 | output->o_quote = 0; |
2644 | while (G.global_argv[i]) { |
2645 | n = expand_on_ifs(output, n, G.global_argv[i]); |
2646 | debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1); |
2647 | if (G.global_argv[i++][0] && G.global_argv[i]) { |
2648 | /* this argv[] is not empty and not last: |
2649 | * put terminating NUL, start new word */ |
2650 | o_addchr(output, '\0'); |
2651 | debug_print_list("expand_vars_to_list[2]", output, n); |
2652 | n = o_save_ptr(output, n); |
2653 | debug_print_list("expand_vars_to_list[3]", output, n); |
2654 | } |
2655 | } |
2656 | output->o_quote = sv; |
2657 | } else |
2658 | /* If or_mask is nonzero, we handle assignment 'a=....$@.....' |
2659 | * and in this case should treat it like '$*' - see 'else...' below */ |
2660 | if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */ |
2661 | while (1) { |
2662 | o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i])); |
2663 | if (++i >= G.global_argc) |
2664 | break; |
2665 | o_addchr(output, '\0'); |
2666 | debug_print_list("expand_vars_to_list[4]", output, n); |
2667 | n = o_save_ptr(output, n); |
2668 | } |
2669 | } else { /* quoted $*: add as one word */ |
2670 | while (1) { |
2671 | o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i])); |
2672 | if (!G.global_argv[++i]) |
2673 | break; |
2674 | if (G.ifs[0]) |
2675 | o_addchr(output, G.ifs[0]); |
2676 | } |
2677 | } |
2678 | break; |
2679 | case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */ |
2680 | /* "Empty variable", used to make "" etc to not disappear */ |
2681 | arg++; |
2682 | ored_ch = 0x80; |
2683 | break; |
2684 | #if ENABLE_HUSH_TICK |
2685 | case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */ |
2686 | struct in_str input; |
2687 | *p = '\0'; |
2688 | arg++; |
2689 | //TODO: can we just stuff it into "output" directly? |
2690 | debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch); |
2691 | setup_string_in_str(&input, arg); |
2692 | process_command_subs(&subst_result, &input, NULL); |
2693 | debug_printf_subst("SUBST RES '%s'\n", subst_result.data); |
2694 | val = subst_result.data; |
2695 | goto store_val; |
2696 | } |
2697 | #endif |
2698 | default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */ |
2699 | *p = '\0'; |
2700 | arg[0] = first_ch & 0x7f; |
2701 | if (isdigit(arg[0])) { |
2702 | i = xatoi_u(arg); |
2703 | if (i < G.global_argc) |
2704 | val = G.global_argv[i]; |
2705 | /* else val remains NULL: $N with too big N */ |
2706 | } else |
2707 | val = lookup_param(arg); |
2708 | arg[0] = first_ch; |
2709 | #if ENABLE_HUSH_TICK |
2710 | store_val: |
2711 | #endif |
2712 | *p = SPECIAL_VAR_SYMBOL; |
2713 | if (!(first_ch & 0x80)) { /* unquoted $VAR */ |
2714 | debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote); |
2715 | if (val) { |
2716 | /* unquoted var's contents should be globbed, so don't quote */ |
2717 | smallint sv = output->o_quote; |
2718 | output->o_quote = 0; |
2719 | n = expand_on_ifs(output, n, val); |
2720 | val = NULL; |
2721 | output->o_quote = sv; |
2722 | } |
2723 | } else { /* quoted $VAR, val will be appended below */ |
2724 | debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote); |
2725 | } |
2726 | } |
2727 | if (val) { |
2728 | o_addQstr(output, val, strlen(val)); |
2729 | } |
2730 | |
2731 | #if ENABLE_HUSH_TICK |
2732 | o_free(&subst_result); |
2733 | #endif |
2734 | arg = ++p; |
2735 | } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */ |
2736 | |
2737 | if (arg[0]) { |
2738 | debug_print_list("expand_vars_to_list[a]", output, n); |
2739 | /* this part is literal, and it was already pre-quoted |
2740 | * if needed (much earlier), do not use o_addQstr here! */ |
2741 | o_addstr(output, arg, strlen(arg) + 1); |
2742 | debug_print_list("expand_vars_to_list[b]", output, n); |
2743 | } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */ |
2744 | && !(ored_ch & 0x80) /* and all vars were not quoted. */ |
2745 | ) { |
2746 | n--; |
2747 | /* allow to reuse list[n] later without re-growth */ |
2748 | output->has_empty_slot = 1; |
2749 | } else { |
2750 | o_addchr(output, '\0'); |
2751 | } |
2752 | return n; |
2753 | } |
2754 | |
2755 | static char **expand_variables(char **argv, int or_mask) |
2756 | { |
2757 | int n; |
2758 | char **list; |
2759 | char **v; |
2760 | o_string output = NULL_O_STRING; |
2761 | |
2762 | if (or_mask & 0x100) { |
2763 | output.o_quote = 1; /* protect against globbing for "$var" */ |
2764 | /* (unquoted $var will temporarily switch it off) */ |
2765 | output.o_glob = 1; |
2766 | } |
2767 | |
2768 | n = 0; |
2769 | v = argv; |
2770 | while (*v) { |
2771 | n = expand_vars_to_list(&output, n, *v, (char)or_mask); |
2772 | v++; |
2773 | } |
2774 | debug_print_list("expand_variables", &output, n); |
2775 | |
2776 | /* output.data (malloced in one block) gets returned in "list" */ |
2777 | list = o_finalize_list(&output, n); |
2778 | debug_print_strings("expand_variables[1]", list); |
2779 | return list; |
2780 | } |
2781 | |
2782 | static char **expand_strvec_to_strvec(char **argv) |
2783 | { |
2784 | return expand_variables(argv, 0x100); |
2785 | } |
2786 | |
2787 | /* Used for expansion of right hand of assignments */ |
2788 | /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs |
2789 | * "v=/bin/c*" */ |
2790 | static char *expand_string_to_string(const char *str) |
2791 | { |
2792 | char *argv[2], **list; |
2793 | |
2794 | argv[0] = (char*)str; |
2795 | argv[1] = NULL; |
2796 | list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */ |
2797 | if (HUSH_DEBUG) |
2798 | if (!list[0] || list[1]) |
2799 | bb_error_msg_and_die("BUG in varexp2"); |
2800 | /* actually, just move string 2*sizeof(char*) bytes back */ |
2801 | strcpy((char*)list, list[0]); |
2802 | debug_printf_expand("string_to_string='%s'\n", (char*)list); |
2803 | return (char*)list; |
2804 | } |
2805 | |
2806 | /* Used for "eval" builtin */ |
2807 | static char* expand_strvec_to_string(char **argv) |
2808 | { |
2809 | char **list; |
2810 | |
2811 | list = expand_variables(argv, 0x80); |
2812 | /* Convert all NULs to spaces */ |
2813 | if (list[0]) { |
2814 | int n = 1; |
2815 | while (list[n]) { |
2816 | if (HUSH_DEBUG) |
2817 | if (list[n-1] + strlen(list[n-1]) + 1 != list[n]) |
2818 | bb_error_msg_and_die("BUG in varexp3"); |
2819 | list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */ |
2820 | n++; |
2821 | } |
2822 | } |
2823 | strcpy((char*)list, list[0]); |
2824 | debug_printf_expand("strvec_to_string='%s'\n", (char*)list); |
2825 | return (char*)list; |
2826 | } |
2827 | |
2828 | |
2829 | /* Used to get/check local shell variables */ |
2830 | static struct variable *get_local_var(const char *name) |
2831 | { |
2832 | struct variable *cur; |
2833 | int len; |
2834 | |
2835 | if (!name) |
2836 | return NULL; |
2837 | len = strlen(name); |
2838 | for (cur = G.top_var; cur; cur = cur->next) { |
2839 | if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=') |
2840 | return cur; |
2841 | } |
2842 | return NULL; |
2843 | } |
2844 | |
2845 | /* str holds "NAME=VAL" and is expected to be malloced. |
2846 | * We take ownership of it. */ |
2847 | static int set_local_var(char *str, int flg_export) |
2848 | { |
2849 | struct variable *cur; |
2850 | char *value; |
2851 | int name_len; |
2852 | |
2853 | value = strchr(str, '='); |
2854 | if (!value) { /* not expected to ever happen? */ |
2855 | free(str); |
2856 | return -1; |
2857 | } |
2858 | |
2859 | name_len = value - str + 1; /* including '=' */ |
2860 | cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */ |
2861 | while (1) { |
2862 | if (strncmp(cur->varstr, str, name_len) != 0) { |
2863 | if (!cur->next) { |
2864 | /* Bail out. Note that now cur points |
2865 | * to last var in linked list */ |
2866 | break; |
2867 | } |
2868 | cur = cur->next; |
2869 | continue; |
2870 | } |
2871 | /* We found an existing var with this name */ |
2872 | *value = '\0'; |
2873 | if (cur->flg_read_only) { |
2874 | bb_error_msg("%s: readonly variable", str); |
2875 | free(str); |
2876 | return -1; |
2877 | } |
2878 | debug_printf_env("%s: unsetenv '%s'\n", __func__, str); |
2879 | unsetenv(str); /* just in case */ |
2880 | *value = '='; |
2881 | if (strcmp(cur->varstr, str) == 0) { |
2882 | free_and_exp: |
2883 | free(str); |
2884 | goto exp; |
2885 | } |
2886 | if (cur->max_len >= strlen(str)) { |
2887 | /* This one is from startup env, reuse space */ |
2888 | strcpy(cur->varstr, str); |
2889 | goto free_and_exp; |
2890 | } |
2891 | /* max_len == 0 signifies "malloced" var, which we can |
2892 | * (and has to) free */ |
2893 | if (!cur->max_len) |
2894 | free(cur->varstr); |
2895 | cur->max_len = 0; |
2896 | goto set_str_and_exp; |
2897 | } |
2898 | |
2899 | /* Not found - create next variable struct */ |
2900 | cur->next = xzalloc(sizeof(*cur)); |
2901 | cur = cur->next; |
2902 | |
2903 | set_str_and_exp: |
2904 | cur->varstr = str; |
2905 | exp: |
2906 | if (flg_export) |
2907 | cur->flg_export = 1; |
2908 | if (cur->flg_export) { |
2909 | debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr); |
2910 | return putenv(cur->varstr); |
2911 | } |
2912 | return 0; |
2913 | } |
2914 | |
2915 | static void unset_local_var(const char *name) |
2916 | { |
2917 | struct variable *cur; |
2918 | struct variable *prev = prev; /* for gcc */ |
2919 | int name_len; |
2920 | |
2921 | if (!name) |
2922 | return; |
2923 | name_len = strlen(name); |
2924 | cur = G.top_var; |
2925 | while (cur) { |
2926 | if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') { |
2927 | if (cur->flg_read_only) { |
2928 | bb_error_msg("%s: readonly variable", name); |
2929 | return; |
2930 | } |
2931 | /* prev is ok to use here because 1st variable, HUSH_VERSION, |
2932 | * is ro, and we cannot reach this code on the 1st pass */ |
2933 | prev->next = cur->next; |
2934 | debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr); |
2935 | unsetenv(cur->varstr); |
2936 | if (!cur->max_len) |
2937 | free(cur->varstr); |
2938 | free(cur); |
2939 | return; |
2940 | } |
2941 | prev = cur; |
2942 | cur = cur->next; |
2943 | } |
2944 | } |
2945 | |
2946 | /* The src parameter allows us to peek forward to a possible &n syntax |
2947 | * for file descriptor duplication, e.g., "2>&1". |
2948 | * Return code is 0 normally, 1 if a syntax error is detected in src. |
2949 | * Resource errors (in xmalloc) cause the process to exit */ |
2950 | static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, |
2951 | struct in_str *input) |
2952 | { |
2953 | struct command *command = ctx->command; |
2954 | struct redir_struct *redir = command->redirects; |
2955 | struct redir_struct *last_redir = NULL; |
2956 | |
2957 | /* Create a new redir_struct and drop it onto the end of the linked list */ |
2958 | while (redir) { |
2959 | last_redir = redir; |
2960 | redir = redir->next; |
2961 | } |
2962 | redir = xzalloc(sizeof(struct redir_struct)); |
2963 | /* redir->next = NULL; */ |
2964 | /* redir->rd_filename = NULL; */ |
2965 | if (last_redir) { |
2966 | last_redir->next = redir; |
2967 | } else { |
2968 | command->redirects = redir; |
2969 | } |
2970 | |
2971 | redir->rd_type = style; |
2972 | redir->fd = (fd == -1) ? redir_table[style].default_fd : fd; |
2973 | |
2974 | debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip); |
2975 | |
2976 | /* Check for a '2>&1' type redirect */ |
2977 | redir->dup = redirect_dup_num(input); |
2978 | if (redir->dup == -2) |
2979 | return 1; /* syntax error */ |
2980 | if (redir->dup != -1) { |
2981 | /* Erik had a check here that the file descriptor in question |
2982 | * is legit; I postpone that to "run time" |
2983 | * A "-" representation of "close me" shows up as a -3 here */ |
2984 | debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup); |
2985 | } else { |
2986 | /* We do _not_ try to open the file that src points to, |
2987 | * since we need to return and let src be expanded first. |
2988 | * Set ctx->pending_redirect, so we know what to do at the |
2989 | * end of the next parsed word. */ |
2990 | ctx->pending_redirect = redir; |
2991 | } |
2992 | return 0; |
2993 | } |
2994 | |
2995 | static struct pipe *new_pipe(void) |
2996 | { |
2997 | struct pipe *pi; |
2998 | pi = xzalloc(sizeof(struct pipe)); |
2999 | /*pi->followup = 0; - deliberately invalid value */ |
3000 | /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */ |
3001 | return pi; |
3002 | } |
3003 | |
3004 | static void initialize_context(struct parse_context *ctx) |
3005 | { |
3006 | memset(ctx, 0, sizeof(*ctx)); |
3007 | ctx->pipe = ctx->list_head = new_pipe(); |
3008 | /* Create the memory for command, roughly: |
3009 | * ctx->pipe->cmds = new struct command; |
3010 | * ctx->command = &ctx->pipe->cmds[0]; |
3011 | */ |
3012 | done_command(ctx); |
3013 | } |
3014 | |
3015 | /* If a reserved word is found and processed, parse context is modified |
3016 | * and 1 is returned. |
3017 | * Handles if, then, elif, else, fi, for, while, until, do, done. |
3018 | * case, function, and select are obnoxious, save those for later. |
3019 | */ |
3020 | #if HAS_KEYWORDS |
3021 | struct reserved_combo { |
3022 | char literal[6]; |
3023 | unsigned char res; |
3024 | unsigned char assignment_flag; |
3025 | int flag; |
3026 | }; |
3027 | enum { |
3028 | FLAG_END = (1 << RES_NONE ), |
3029 | #if ENABLE_HUSH_IF |
3030 | FLAG_IF = (1 << RES_IF ), |
3031 | FLAG_THEN = (1 << RES_THEN ), |
3032 | FLAG_ELIF = (1 << RES_ELIF ), |
3033 | FLAG_ELSE = (1 << RES_ELSE ), |
3034 | FLAG_FI = (1 << RES_FI ), |
3035 | #endif |
3036 | #if ENABLE_HUSH_LOOPS |
3037 | FLAG_FOR = (1 << RES_FOR ), |
3038 | FLAG_WHILE = (1 << RES_WHILE), |
3039 | FLAG_UNTIL = (1 << RES_UNTIL), |
3040 | FLAG_DO = (1 << RES_DO ), |
3041 | FLAG_DONE = (1 << RES_DONE ), |
3042 | FLAG_IN = (1 << RES_IN ), |
3043 | #endif |
3044 | #if ENABLE_HUSH_CASE |
3045 | FLAG_MATCH = (1 << RES_MATCH), |
3046 | FLAG_ESAC = (1 << RES_ESAC ), |
3047 | #endif |
3048 | FLAG_START = (1 << RES_XXXX ), |
3049 | }; |
3050 | |
3051 | static const struct reserved_combo* match_reserved_word(o_string *word) |
3052 | { |
3053 | /* Mostly a list of accepted follow-up reserved words. |
3054 | * FLAG_END means we are done with the sequence, and are ready |
3055 | * to turn the compound list into a command. |
3056 | * FLAG_START means the word must start a new compound list. |
3057 | */ |
3058 | static const struct reserved_combo reserved_list[] = { |
3059 | #if ENABLE_HUSH_IF |
3060 | { "!", RES_NONE, NOT_ASSIGNMENT , 0 }, |
3061 | { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START }, |
3062 | { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI }, |
3063 | { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN }, |
3064 | { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI }, |
3065 | { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END }, |
3066 | #endif |
3067 | #if ENABLE_HUSH_LOOPS |
3068 | { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START }, |
3069 | { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START }, |
3070 | { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START }, |
3071 | { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO }, |
3072 | { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE }, |
3073 | { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END }, |
3074 | #endif |
3075 | #if ENABLE_HUSH_CASE |
3076 | { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START }, |
3077 | { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END }, |
3078 | #endif |
3079 | }; |
3080 | const struct reserved_combo *r; |
3081 | |
3082 | for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) { |
3083 | if (strcmp(word->data, r->literal) == 0) |
3084 | return r; |
3085 | } |
3086 | return NULL; |
3087 | } |
3088 | static int reserved_word(o_string *word, struct parse_context *ctx) |
3089 | { |
3090 | #if ENABLE_HUSH_CASE |
3091 | static const struct reserved_combo reserved_match = { |
3092 | "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC |
3093 | }; |
3094 | #endif |
3095 | const struct reserved_combo *r; |
3096 | |
3097 | r = match_reserved_word(word); |
3098 | if (!r) |
3099 | return 0; |
3100 | |
3101 | debug_printf("found reserved word %s, res %d\n", r->literal, r->res); |
3102 | #if ENABLE_HUSH_CASE |
3103 | if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE) |
3104 | /* "case word IN ..." - IN part starts first match part */ |
3105 | r = &reserved_match; |
3106 | else |
3107 | #endif |
3108 | if (r->flag == 0) { /* '!' */ |
3109 | if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */ |
3110 | syntax(NULL); |
3111 | IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;) |
3112 | } |
3113 | ctx->ctx_inverted = 1; |
3114 | return 1; |
3115 | } |
3116 | if (r->flag & FLAG_START) { |
3117 | struct parse_context *new; |
3118 | debug_printf("push stack\n"); |
3119 | new = xmalloc(sizeof(*new)); |
3120 | *new = *ctx; /* physical copy */ |
3121 | initialize_context(ctx); |
3122 | ctx->stack = new; |
3123 | } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) { |
3124 | syntax(NULL); |
3125 | ctx->ctx_res_w = RES_SNTX; |
3126 | return 1; |
3127 | } |
3128 | ctx->ctx_res_w = r->res; |
3129 | ctx->old_flag = r->flag; |
3130 | if (ctx->old_flag & FLAG_END) { |
3131 | struct parse_context *old; |
3132 | debug_printf("pop stack\n"); |
3133 | done_pipe(ctx, PIPE_SEQ); |
3134 | old = ctx->stack; |
3135 | old->command->group = ctx->list_head; |
3136 | old->command->grp_type = GRP_NORMAL; |
3137 | *ctx = *old; /* physical copy */ |
3138 | free(old); |
3139 | } |
3140 | word->o_assignment = r->assignment_flag; |
3141 | return 1; |
3142 | } |
3143 | #endif |
3144 | |
3145 | //TODO: many, many callers don't check error from done_word() |
3146 | |
3147 | /* Word is complete, look at it and update parsing context. |
3148 | * Normal return is 0. Syntax errors return 1. */ |
3149 | static int done_word(o_string *word, struct parse_context *ctx) |
3150 | { |
3151 | struct command *command = ctx->command; |
3152 | |
3153 | debug_printf_parse("done_word entered: '%s' %p\n", word->data, command); |
3154 | if (word->length == 0 && word->nonnull == 0) { |
3155 | debug_printf_parse("done_word return 0: true null, ignored\n"); |
3156 | return 0; |
3157 | } |
3158 | /* If this word wasn't an assignment, next ones definitely |
3159 | * can't be assignments. Even if they look like ones. */ |
3160 | if (word->o_assignment != DEFINITELY_ASSIGNMENT |
3161 | && word->o_assignment != WORD_IS_KEYWORD |
3162 | ) { |
3163 | word->o_assignment = NOT_ASSIGNMENT; |
3164 | } else { |
3165 | if (word->o_assignment == DEFINITELY_ASSIGNMENT) |
3166 | command->assignment_cnt++; |
3167 | word->o_assignment = MAYBE_ASSIGNMENT; |
3168 | } |
3169 | |
3170 | if (ctx->pending_redirect) { |
3171 | /* We do not glob in e.g. >*.tmp case. bash seems to glob here |
3172 | * only if run as "bash", not "sh" */ |
3173 | ctx->pending_redirect->rd_filename = xstrdup(word->data); |
3174 | word->o_assignment = NOT_ASSIGNMENT; |
3175 | debug_printf("word stored in rd_filename: '%s'\n", word->data); |
3176 | } else { |
3177 | /* "{ echo foo; } echo bar" - bad */ |
3178 | /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */ |
3179 | if (command->group) { |
3180 | syntax(NULL); |
3181 | debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n"); |
3182 | return 1; |
3183 | } |
3184 | #if HAS_KEYWORDS |
3185 | #if ENABLE_HUSH_CASE |
3186 | if (ctx->ctx_dsemicolon |
3187 | && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */ |
3188 | ) { |
3189 | /* already done when ctx_dsemicolon was set to 1: */ |
3190 | /* ctx->ctx_res_w = RES_MATCH; */ |
3191 | ctx->ctx_dsemicolon = 0; |
3192 | } else |
3193 | #endif |
3194 | |
3195 | if (!command->argv /* if it's the first word... */ |
3196 | #if ENABLE_HUSH_LOOPS |
3197 | && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */ |
3198 | && ctx->ctx_res_w != RES_IN |
3199 | #endif |
3200 | ) { |
3201 | debug_printf_parse(": checking '%s' for reserved-ness\n", word->data); |
3202 | if (reserved_word(word, ctx)) { |
3203 | o_reset(word); |
3204 | debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX)); |
3205 | return (ctx->ctx_res_w == RES_SNTX); |
3206 | } |
3207 | } |
3208 | #endif |
3209 | if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */ |
3210 | /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */ |
3211 | && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL) |
3212 | /* (otherwise it's known to be not empty and is already safe) */ |
3213 | ) { |
3214 | /* exclude "$@" - it can expand to no word despite "" */ |
3215 | char *p = word->data; |
3216 | while (p[0] == SPECIAL_VAR_SYMBOL |
3217 | && (p[1] & 0x7f) == '@' |
3218 | && p[2] == SPECIAL_VAR_SYMBOL |
3219 | ) { |
3220 | p += 3; |
3221 | } |
3222 | if (p == word->data || p[0] != '\0') { |
3223 | /* saw no "$@", or not only "$@" but some |
3224 | * real text is there too */ |
3225 | /* insert "empty variable" reference, this makes |
3226 | * e.g. "", $empty"" etc to not disappear */ |
3227 | o_addchr(word, SPECIAL_VAR_SYMBOL); |
3228 | o_addchr(word, SPECIAL_VAR_SYMBOL); |
3229 | } |
3230 | } |
3231 | command->argv = add_string_to_strings(command->argv, xstrdup(word->data)); |
3232 | debug_print_strings("word appended to argv", command->argv); |
3233 | } |
3234 | |
3235 | o_reset(word); |
3236 | ctx->pending_redirect = NULL; |
3237 | |
3238 | #if ENABLE_HUSH_LOOPS |
3239 | /* Force FOR to have just one word (variable name) */ |
3240 | /* NB: basically, this makes hush see "for v in ..." syntax as if |
3241 | * as it is "for v; in ...". FOR and IN become two pipe structs |
3242 | * in parse tree. */ |
3243 | if (ctx->ctx_res_w == RES_FOR) { |
3244 | //TODO: check that command->argv[0] is a valid variable name! |
3245 | done_pipe(ctx, PIPE_SEQ); |
3246 | } |
3247 | #endif |
3248 | #if ENABLE_HUSH_CASE |
3249 | /* Force CASE to have just one word */ |
3250 | if (ctx->ctx_res_w == RES_CASE) { |
3251 | done_pipe(ctx, PIPE_SEQ); |
3252 | } |
3253 | #endif |
3254 | debug_printf_parse("done_word return 0\n"); |
3255 | return 0; |
3256 | } |
3257 | |
3258 | /* Command (member of a pipe) is complete. The only possible error here |
3259 | * is out of memory, in which case xmalloc exits. */ |
3260 | static int done_command(struct parse_context *ctx) |
3261 | { |
3262 | /* The command is really already in the pipe structure, so |
3263 | * advance the pipe counter and make a new, null command. */ |
3264 | struct pipe *pi = ctx->pipe; |
3265 | struct command *command = ctx->command; |
3266 | |
3267 | if (command) { |
3268 | if (command->group == NULL |
3269 | && command->argv == NULL |
3270 | && command->redirects == NULL |
3271 | ) { |
3272 | debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds); |
3273 | return pi->num_cmds; |
3274 | } |
3275 | pi->num_cmds++; |
3276 | debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds); |
3277 | } else { |
3278 | debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds); |
3279 | } |
3280 | |
3281 | /* Only real trickiness here is that the uncommitted |
3282 | * command structure is not counted in pi->num_cmds. */ |
3283 | pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1)); |
3284 | command = &pi->cmds[pi->num_cmds]; |
3285 | memset(command, 0, sizeof(*command)); |
3286 | |
3287 | ctx->command = command; |
3288 | /* but ctx->pipe and ctx->list_head remain unchanged */ |
3289 | |
3290 | return pi->num_cmds; /* used only for 0/nonzero check */ |
3291 | } |
3292 | |
3293 | static void done_pipe(struct parse_context *ctx, pipe_style type) |
3294 | { |
3295 | int not_null; |
3296 | |
3297 | debug_printf_parse("done_pipe entered, followup %d\n", type); |
3298 | /* Close previous command */ |
3299 | not_null = done_command(ctx); |
3300 | ctx->pipe->followup = type; |
3301 | IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;) |
3302 | IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;) |
3303 | IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;) |
3304 | |
3305 | /* Without this check, even just <enter> on command line generates |
3306 | * tree of three NOPs (!). Which is harmless but annoying. |
3307 | * IOW: it is safe to do it unconditionally. |
3308 | * RES_NONE case is for "for a in; do ..." (empty IN set) |
3309 | * to work, possibly other cases too. */ |
3310 | if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) { |
3311 | struct pipe *new_p; |
3312 | debug_printf_parse("done_pipe: adding new pipe: " |
3313 | "not_null:%d ctx->ctx_res_w:%d\n", |
3314 | not_null, ctx->ctx_res_w); |
3315 | new_p = new_pipe(); |
3316 | ctx->pipe->next = new_p; |
3317 | ctx->pipe = new_p; |
3318 | ctx->command = NULL; /* needed! */ |
3319 | /* RES_THEN, RES_DO etc are "sticky" - |
3320 | * they remain set for commands inside if/while. |
3321 | * This is used to control execution. |
3322 | * RES_FOR and RES_IN are NOT sticky (needed to support |
3323 | * cases where variable or value happens to match a keyword): |
3324 | */ |
3325 | #if ENABLE_HUSH_LOOPS |
3326 | if (ctx->ctx_res_w == RES_FOR |
3327 | || ctx->ctx_res_w == RES_IN) |
3328 | ctx->ctx_res_w = RES_NONE; |
3329 | #endif |
3330 | #if ENABLE_HUSH_CASE |
3331 | if (ctx->ctx_res_w == RES_MATCH) |
3332 | ctx->ctx_res_w = RES_CASEI; |
3333 | #endif |
3334 | /* Create the memory for command, roughly: |
3335 | * ctx->pipe->cmds = new struct command; |
3336 | * ctx->command = &ctx->pipe->cmds[0]; |
3337 | */ |
3338 | done_command(ctx); |
3339 | } |
3340 | debug_printf_parse("done_pipe return\n"); |
3341 | } |
3342 | |
3343 | /* Peek ahead in the in_str to find out if we have a "&n" construct, |
3344 | * as in "2>&1", that represents duplicating a file descriptor. |
3345 | * Return either -2 (syntax error), -1 (no &), or the number found. |
3346 | */ |
3347 | static int redirect_dup_num(struct in_str *input) |
3348 | { |
3349 | int ch, d = 0, ok = 0; |
3350 | ch = i_peek(input); |
3351 | if (ch != '&') return -1; |
3352 | |
3353 | i_getch(input); /* get the & */ |
3354 | ch = i_peek(input); |
3355 | if (ch == '-') { |
3356 | i_getch(input); |
3357 | return -3; /* "-" represents "close me" */ |
3358 | } |
3359 | while (isdigit(ch)) { |
3360 | d = d*10 + (ch-'0'); |
3361 | ok = 1; |
3362 | i_getch(input); |
3363 | ch = i_peek(input); |
3364 | } |
3365 | if (ok) return d; |
3366 | |
3367 | bb_error_msg("ambiguous redirect"); |
3368 | return -2; |
3369 | } |
3370 | |
3371 | /* If a redirect is immediately preceded by a number, that number is |
3372 | * supposed to tell which file descriptor to redirect. This routine |
3373 | * looks for such preceding numbers. In an ideal world this routine |
3374 | * needs to handle all the following classes of redirects... |
3375 | * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo |
3376 | * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo |
3377 | * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo |
3378 | * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo |
3379 | * A -1 output from this program means no valid number was found, so the |
3380 | * caller should use the appropriate default for this redirection. |
3381 | */ |
3382 | static int redirect_opt_num(o_string *o) |
3383 | { |
3384 | int num; |
3385 | |
3386 | if (o->length == 0) |
3387 | return -1; |
3388 | for (num = 0; num < o->length; num++) { |
3389 | if (!isdigit(o->data[num])) { |
3390 | return -1; |
3391 | } |
3392 | } |
3393 | num = atoi(o->data); |
3394 | o_reset(o); |
3395 | return num; |
3396 | } |
3397 | |
3398 | #if ENABLE_HUSH_TICK |
3399 | static FILE *generate_stream_from_list(struct pipe *head) |
3400 | { |
3401 | FILE *pf; |
3402 | int pid, channel[2]; |
3403 | |
3404 | xpipe(channel); |
3405 | /* *** NOMMU WARNING *** */ |
3406 | /* By using vfork here, we suspend parent till child exits or execs. |
3407 | * If child will not do it before it fills the pipe, it can block forever |
3408 | * in write(STDOUT_FILENO), and parent (shell) will be also stuck. |
3409 | * Try this script: |
3410 | * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE |
3411 | * huge=`cat TESTFILE` # will block here forever |
3412 | * echo OK |
3413 | */ |
3414 | pid = BB_MMU ? fork() : vfork(); |
3415 | if (pid < 0) |
3416 | bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork"); |
3417 | if (pid == 0) { /* child */ |
3418 | if (ENABLE_HUSH_JOB) |
3419 | die_sleep = 0; /* let nofork's xfuncs die */ |
3420 | close(channel[0]); /* NB: close _first_, then move fd! */ |
3421 | xmove_fd(channel[1], 1); |
3422 | /* Prevent it from trying to handle ctrl-z etc */ |
3423 | #if ENABLE_HUSH_JOB |
3424 | G.run_list_level = 1; |
3425 | #endif |
3426 | /* Process substitution is not considered to be usual |
3427 | * 'command execution'. |
3428 | * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */ |
3429 | /* Not needed, we are relying on it being disabled |
3430 | * everywhere outside actual command execution. */ |
3431 | /*set_jobctrl_sighandler(SIG_IGN);*/ |
3432 | set_misc_sighandler(SIG_DFL); |
3433 | /* Freeing 'head' here would break NOMMU. */ |
3434 | _exit(run_list(head)); |
3435 | } |
3436 | close(channel[1]); |
3437 | pf = fdopen(channel[0], "r"); |
3438 | return pf; |
3439 | /* 'head' is freed by the caller */ |
3440 | } |
3441 | |
3442 | /* Return code is exit status of the process that is run. */ |
3443 | static int process_command_subs(o_string *dest, |
3444 | struct in_str *input, |
3445 | const char *subst_end) |
3446 | { |
3447 | int retcode, ch, eol_cnt; |
3448 | o_string result = NULL_O_STRING; |
3449 | struct parse_context inner; |
3450 | FILE *p; |
3451 | struct in_str pipe_str; |
3452 | |
3453 | initialize_context(&inner); |
3454 | |
3455 | /* Recursion to generate command */ |
3456 | retcode = parse_stream(&result, &inner, input, subst_end); |
3457 | if (retcode != 0) |
3458 | return retcode; /* syntax error or EOF */ |
3459 | done_word(&result, &inner); |
3460 | done_pipe(&inner, PIPE_SEQ); |
3461 | o_free(&result); |
3462 | |
3463 | p = generate_stream_from_list(inner.list_head); |
3464 | if (p == NULL) |
3465 | return 1; |
3466 | close_on_exec_on(fileno(p)); |
3467 | setup_file_in_str(&pipe_str, p); |
3468 | |
3469 | /* Now send results of command back into original context */ |
3470 | eol_cnt = 0; |
3471 | while ((ch = i_getch(&pipe_str)) != EOF) { |
3472 | if (ch == '\n') { |
3473 | eol_cnt++; |
3474 | continue; |
3475 | } |
3476 | while (eol_cnt) { |
3477 | o_addchr(dest, '\n'); |
3478 | eol_cnt--; |
3479 | } |
3480 | o_addQchr(dest, ch); |
3481 | } |
3482 | |
3483 | debug_printf("done reading from pipe, pclose()ing\n"); |
3484 | /* This is the step that wait()s for the child. Should be pretty |
3485 | * safe, since we just read an EOF from its stdout. We could try |
3486 | * to do better, by using wait(), and keeping track of background jobs |
3487 | * at the same time. That would be a lot of work, and contrary |
3488 | * to the KISS philosophy of this program. */ |
3489 | retcode = fclose(p); |
3490 | free_pipe_list(inner.list_head, /* indent: */ 0); |
3491 | debug_printf("closed FILE from child, retcode=%d\n", retcode); |
3492 | return retcode; |
3493 | } |
3494 | #endif |
3495 | |
3496 | static int parse_group(o_string *dest, struct parse_context *ctx, |
3497 | struct in_str *input, int ch) |
3498 | { |
3499 | /* dest contains characters seen prior to ( or {. |
3500 | * Typically it's empty, but for functions defs, |
3501 | * it contains function name (without '()'). */ |
3502 | int rcode; |
3503 | const char *endch = NULL; |
3504 | struct parse_context sub; |
3505 | struct command *command = ctx->command; |
3506 | |
3507 | debug_printf_parse("parse_group entered\n"); |
3508 | #if ENABLE_HUSH_FUNCTIONS |
3509 | if (ch == 'F') { /* function definition? */ |
3510 | bb_error_msg("aha '%s' is a function, parsing it...", dest->data); |
3511 | //command->fname = dest->data; |
3512 | command->grp_type = GRP_FUNCTION; |
3513 | //TODO: review every o_reset() location... do they handle all o_string fields correctly? |
3514 | memset(dest, 0, sizeof(*dest)); |
3515 | } |
3516 | #endif |
3517 | if (command->argv /* word [word](... */ |
3518 | || dest->length /* word(... */ |
3519 | || dest->nonnull /* ""(... */ |
3520 | ) { |
3521 | syntax(NULL); |
3522 | debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n"); |
3523 | return 1; |
3524 | } |
3525 | initialize_context(&sub); |
3526 | endch = "}"; |
3527 | if (ch == '(') { |
3528 | endch = ")"; |
3529 | command->grp_type = GRP_SUBSHELL; |
3530 | } |
3531 | rcode = parse_stream(dest, &sub, input, endch); |
3532 | if (rcode == 0) { |
3533 | done_word(dest, &sub); /* finish off the final word in the subcontext */ |
3534 | done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */ |
3535 | command->group = sub.list_head; |
3536 | } |
3537 | debug_printf_parse("parse_group return %d\n", rcode); |
3538 | return rcode; |
3539 | /* command remains "open", available for possible redirects */ |
3540 | } |
3541 | |
3542 | /* Basically useful version until someone wants to get fancier, |
3543 | * see the bash man page under "Parameter Expansion" */ |
3544 | static const char *lookup_param(const char *src) |
3545 | { |
3546 | struct variable *var = get_local_var(src); |
3547 | if (var) |
3548 | return strchr(var->varstr, '=') + 1; |
3549 | return NULL; |
3550 | } |
3551 | |
3552 | #if ENABLE_HUSH_TICK |
3553 | /* Subroutines for copying $(...) and `...` things */ |
3554 | static void add_till_backquote(o_string *dest, struct in_str *input); |
3555 | /* '...' */ |
3556 | static void add_till_single_quote(o_string *dest, struct in_str *input) |
3557 | { |
3558 | while (1) { |
3559 | int ch = i_getch(input); |
3560 | if (ch == EOF) |
3561 | break; |
3562 | if (ch == '\'') |
3563 | break; |
3564 | o_addchr(dest, ch); |
3565 | } |
3566 | } |
3567 | /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */ |
3568 | static void add_till_double_quote(o_string *dest, struct in_str *input) |
3569 | { |
3570 | while (1) { |
3571 | int ch = i_getch(input); |
3572 | if (ch == '"') |
3573 | break; |
3574 | if (ch == '\\') { /* \x. Copy both chars. */ |
3575 | o_addchr(dest, ch); |
3576 | ch = i_getch(input); |
3577 | } |
3578 | if (ch == EOF) |
3579 | break; |
3580 | o_addchr(dest, ch); |
3581 | if (ch == '`') { |
3582 | add_till_backquote(dest, input); |
3583 | o_addchr(dest, ch); |
3584 | continue; |
3585 | } |
3586 | //if (ch == '$') ... |
3587 | } |
3588 | } |
3589 | /* Process `cmd` - copy contents until "`" is seen. Complicated by |
3590 | * \` quoting. |
3591 | * "Within the backquoted style of command substitution, backslash |
3592 | * shall retain its literal meaning, except when followed by: '$', '`', or '\'. |
3593 | * The search for the matching backquote shall be satisfied by the first |
3594 | * backquote found without a preceding backslash; during this search, |
3595 | * if a non-escaped backquote is encountered within a shell comment, |
3596 | * a here-document, an embedded command substitution of the $(command) |
3597 | * form, or a quoted string, undefined results occur. A single-quoted |
3598 | * or double-quoted string that begins, but does not end, within the |
3599 | * "`...`" sequence produces undefined results." |
3600 | * Example Output |
3601 | * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST |
3602 | */ |
3603 | static void add_till_backquote(o_string *dest, struct in_str *input) |
3604 | { |
3605 | while (1) { |
3606 | int ch = i_getch(input); |
3607 | if (ch == '`') |
3608 | break; |
3609 | if (ch == '\\') { /* \x. Copy both chars unless it is \` */ |
3610 | int ch2 = i_getch(input); |
3611 | if (ch2 != '`' && ch2 != '$' && ch2 != '\\') |
3612 | o_addchr(dest, ch); |
3613 | ch = ch2; |
3614 | } |
3615 | if (ch == EOF) |
3616 | break; |
3617 | o_addchr(dest, ch); |
3618 | } |
3619 | } |
3620 | /* Process $(cmd) - copy contents until ")" is seen. Complicated by |
3621 | * quoting and nested ()s. |
3622 | * "With the $(command) style of command substitution, all characters |
3623 | * following the open parenthesis to the matching closing parenthesis |
3624 | * constitute the command. Any valid shell script can be used for command, |
3625 | * except a script consisting solely of redirections which produces |
3626 | * unspecified results." |
3627 | * Example Output |
3628 | * echo $(echo '(TEST)' BEST) (TEST) BEST |
3629 | * echo $(echo 'TEST)' BEST) TEST) BEST |
3630 | * echo $(echo \(\(TEST\) BEST) ((TEST) BEST |
3631 | */ |
3632 | static void add_till_closing_curly_brace(o_string *dest, struct in_str *input) |
3633 | { |
3634 | int count = 0; |
3635 | while (1) { |
3636 | int ch = i_getch(input); |
3637 | if (ch == EOF) |
3638 | break; |
3639 | if (ch == '(') |
3640 | count++; |
3641 | if (ch == ')') |
3642 | if (--count < 0) |
3643 | break; |
3644 | o_addchr(dest, ch); |
3645 | if (ch == '\'') { |
3646 | add_till_single_quote(dest, input); |
3647 | o_addchr(dest, ch); |
3648 | continue; |
3649 | } |
3650 | if (ch == '"') { |
3651 | add_till_double_quote(dest, input); |
3652 | o_addchr(dest, ch); |
3653 | continue; |
3654 | } |
3655 | if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */ |
3656 | ch = i_getch(input); |
3657 | if (ch == EOF) |
3658 | break; |
3659 | o_addchr(dest, ch); |
3660 | continue; |
3661 | } |
3662 | } |
3663 | } |
3664 | #endif /* ENABLE_HUSH_TICK */ |
3665 | |
3666 | /* Return code: 0 for OK, 1 for syntax error */ |
3667 | static int handle_dollar(o_string *dest, struct in_str *input) |
3668 | { |
3669 | int ch = i_peek(input); /* first character after the $ */ |
3670 | unsigned char quote_mask = dest->o_quote ? 0x80 : 0; |
3671 | |
3672 | debug_printf_parse("handle_dollar entered: ch='%c'\n", ch); |
3673 | if (isalpha(ch)) { |
3674 | i_getch(input); |
3675 | make_var: |
3676 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3677 | while (1) { |
3678 | debug_printf_parse(": '%c'\n", ch); |
3679 | o_addchr(dest, ch | quote_mask); |
3680 | quote_mask = 0; |
3681 | ch = i_peek(input); |
3682 | if (!isalnum(ch) && ch != '_') |
3683 | break; |
3684 | i_getch(input); |
3685 | } |
3686 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3687 | } else if (isdigit(ch)) { |
3688 | make_one_char_var: |
3689 | i_getch(input); |
3690 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3691 | debug_printf_parse(": '%c'\n", ch); |
3692 | o_addchr(dest, ch | quote_mask); |
3693 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3694 | } else switch (ch) { |
3695 | case '$': /* pid */ |
3696 | case '!': /* last bg pid */ |
3697 | case '?': /* last exit code */ |
3698 | case '#': /* number of args */ |
3699 | case '*': /* args */ |
3700 | case '@': /* args */ |
3701 | goto make_one_char_var; |
3702 | case '{': |
3703 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3704 | i_getch(input); |
3705 | /* XXX maybe someone will try to escape the '}' */ |
3706 | while (1) { |
3707 | ch = i_getch(input); |
3708 | if (ch == '}') |
3709 | break; |
3710 | if (!isalnum(ch) && ch != '_') { |
3711 | syntax("unterminated ${name}"); |
3712 | debug_printf_parse("handle_dollar return 1: unterminated ${name}\n"); |
3713 | return 1; |
3714 | } |
3715 | debug_printf_parse(": '%c'\n", ch); |
3716 | o_addchr(dest, ch | quote_mask); |
3717 | quote_mask = 0; |
3718 | } |
3719 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3720 | break; |
3721 | #if ENABLE_HUSH_TICK |
3722 | case '(': { |
3723 | //int pos = dest->length; |
3724 | i_getch(input); |
3725 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3726 | o_addchr(dest, quote_mask | '`'); |
3727 | add_till_closing_curly_brace(dest, input); |
3728 | //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos); |
3729 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3730 | break; |
3731 | } |
3732 | #endif |
3733 | case '_': |
3734 | i_getch(input); |
3735 | ch = i_peek(input); |
3736 | if (isalnum(ch)) { /* it's $_name or $_123 */ |
3737 | ch = '_'; |
3738 | goto make_var; |
3739 | } |
3740 | /* else: it's $_ */ |
3741 | case '-': |
3742 | /* still unhandled, but should be eventually */ |
3743 | bb_error_msg("unhandled syntax: $%c", ch); |
3744 | return 1; |
3745 | break; |
3746 | default: |
3747 | o_addQchr(dest, '$'); |
3748 | } |
3749 | debug_printf_parse("handle_dollar return 0\n"); |
3750 | return 0; |
3751 | } |
3752 | |
3753 | /* Scan input, call done_word() whenever full IFS delimited word was seen. |
3754 | * Call done_pipe if '\n' was seen (and end_trigger != NULL). |
3755 | * Return code is 0 if end_trigger char is met, |
3756 | * -1 on EOF (but if end_trigger == NULL then return 0), |
3757 | * 1 for syntax error */ |
3758 | static int parse_stream(o_string *dest, struct parse_context *ctx, |
3759 | struct in_str *input, const char *end_trigger) |
3760 | { |
3761 | int ch, m; |
3762 | int redir_fd; |
3763 | redir_type redir_style; |
3764 | int shadow_quote = dest->o_quote; |
3765 | int next; |
3766 | |
3767 | /* Only double-quote state is handled in the state variable dest->o_quote. |
3768 | * A single-quote triggers a bypass of the main loop until its mate is |
3769 | * found. When recursing, quote state is passed in via dest->o_quote. */ |
3770 | |
3771 | debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment); |
3772 | |
3773 | while (1) { |
3774 | m = CHAR_IFS; |
3775 | next = '\0'; |
3776 | ch = i_getch(input); |
3777 | if (ch != EOF) { |
3778 | m = G.charmap[ch]; |
3779 | if (ch != '\n') { |
3780 | next = i_peek(input); |
3781 | } |
3782 | } |
3783 | debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n", |
3784 | ch, ch, m, dest->o_quote); |
3785 | if (m == CHAR_ORDINARY |
3786 | || (m != CHAR_SPECIAL && shadow_quote) |
3787 | ) { |
3788 | if (ch == EOF) { |
3789 | syntax("unterminated \""); |
3790 | debug_printf_parse("parse_stream return 1: unterminated \"\n"); |
3791 | return 1; |
3792 | } |
3793 | o_addQchr(dest, ch); |
3794 | if ((dest->o_assignment == MAYBE_ASSIGNMENT |
3795 | || dest->o_assignment == WORD_IS_KEYWORD) |
3796 | && ch == '=' |
3797 | && is_assignment(dest->data) |
3798 | ) { |
3799 | dest->o_assignment = DEFINITELY_ASSIGNMENT; |
3800 | } |
3801 | continue; |
3802 | } |
3803 | if (m == CHAR_IFS) { |
3804 | if (done_word(dest, ctx)) { |
3805 | debug_printf_parse("parse_stream return 1: done_word!=0\n"); |
3806 | return 1; |
3807 | } |
3808 | if (ch == EOF) |
3809 | break; |
3810 | /* If we aren't performing a substitution, treat |
3811 | * a newline as a command separator. |
3812 | * [why we don't handle it exactly like ';'? --vda] */ |
3813 | if (end_trigger && ch == '\n') { |
3814 | #if ENABLE_HUSH_CASE |
3815 | /* "case ... in <newline> word) ..." - |
3816 | * newlines are ignored (but ';' wouldn't be) */ |
3817 | if (dest->length == 0 // && argv[0] == NULL |
3818 | && ctx->ctx_res_w == RES_MATCH |
3819 | ) { |
3820 | continue; |
3821 | } |
3822 | #endif |
3823 | done_pipe(ctx, PIPE_SEQ); |
3824 | dest->o_assignment = MAYBE_ASSIGNMENT; |
3825 | } |
3826 | } |
3827 | if (end_trigger) { |
3828 | if (!shadow_quote && strchr(end_trigger, ch)) { |
3829 | /* Special case: (...word) makes last word terminate, |
3830 | * as if ';' is seen */ |
3831 | if (ch == ')') { |
3832 | done_word(dest, ctx); |
3833 | //err chk? |
3834 | done_pipe(ctx, PIPE_SEQ); |
3835 | dest->o_assignment = MAYBE_ASSIGNMENT; |
3836 | } |
3837 | if (!HAS_KEYWORDS |
3838 | IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0)) |
3839 | ) { |
3840 | debug_printf_parse("parse_stream return 0: end_trigger char found\n"); |
3841 | return 0; |
3842 | } |
3843 | } |
3844 | } |
3845 | if (m == CHAR_IFS) |
3846 | continue; |
3847 | |
3848 | if (dest->o_assignment == MAYBE_ASSIGNMENT) { |
3849 | /* ch is a special char and thus this word |
3850 | * cannot be an assignment: */ |
3851 | dest->o_assignment = NOT_ASSIGNMENT; |
3852 | } |
3853 | |
3854 | switch (ch) { |
3855 | case '#': |
3856 | if (dest->length == 0 && !shadow_quote) { |
3857 | while (1) { |
3858 | ch = i_peek(input); |
3859 | if (ch == EOF || ch == '\n') |
3860 | break; |
3861 | i_getch(input); |
3862 | } |
3863 | } else { |
3864 | o_addQchr(dest, ch); |
3865 | } |
3866 | break; |
3867 | case '\\': |
3868 | if (next == EOF) { |
3869 | syntax("\\<eof>"); |
3870 | debug_printf_parse("parse_stream return 1: \\<eof>\n"); |
3871 | return 1; |
3872 | } |
3873 | /* bash: |
3874 | * "The backslash retains its special meaning [in "..."] |
3875 | * only when followed by one of the following characters: |
3876 | * $, `, ", \, or <newline>. A double quote may be quoted |
3877 | * within double quotes by preceding it with a backslash. |
3878 | * If enabled, history expansion will be performed unless |
3879 | * an ! appearing in double quotes is escaped using |
3880 | * a backslash. The backslash preceding the ! is not removed." |
3881 | */ |
3882 | if (shadow_quote) { //NOT SURE dest->o_quote) { |
3883 | if (strchr("$`\"\\", next) != NULL) { |
3884 | o_addqchr(dest, i_getch(input)); |
3885 | } else { |
3886 | o_addqchr(dest, '\\'); |
3887 | } |
3888 | } else { |
3889 | o_addchr(dest, '\\'); |
3890 | o_addchr(dest, i_getch(input)); |
3891 | } |
3892 | break; |
3893 | case '$': |
3894 | if (handle_dollar(dest, input) != 0) { |
3895 | debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n"); |
3896 | return 1; |
3897 | } |
3898 | break; |
3899 | case '\'': |
3900 | dest->nonnull = 1; |
3901 | while (1) { |
3902 | ch = i_getch(input); |
3903 | if (ch == EOF) { |
3904 | syntax("unterminated '"); |
3905 | debug_printf_parse("parse_stream return 1: unterminated '\n"); |
3906 | return 1; |
3907 | } |
3908 | if (ch == '\'') |
3909 | break; |
3910 | if (dest->o_assignment == NOT_ASSIGNMENT) |
3911 | o_addqchr(dest, ch); |
3912 | else |
3913 | o_addchr(dest, ch); |
3914 | } |
3915 | break; |
3916 | case '"': |
3917 | dest->nonnull = 1; |
3918 | shadow_quote ^= 1; /* invert */ |
3919 | if (dest->o_assignment == NOT_ASSIGNMENT) |
3920 | dest->o_quote ^= 1; |
3921 | break; |
3922 | #if ENABLE_HUSH_TICK |
3923 | case '`': { |
3924 | //int pos = dest->length; |
3925 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3926 | o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`'); |
3927 | add_till_backquote(dest, input); |
3928 | o_addchr(dest, SPECIAL_VAR_SYMBOL); |
3929 | //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos); |
3930 | break; |
3931 | } |
3932 | #endif |
3933 | case '>': |
3934 | redir_fd = redirect_opt_num(dest); |
3935 | done_word(dest, ctx); |
3936 | redir_style = REDIRECT_OVERWRITE; |
3937 | if (next == '>') { |
3938 | redir_style = REDIRECT_APPEND; |
3939 | i_getch(input); |
3940 | } |
3941 | #if 0 |
3942 | else if (next == '(') { |
3943 | syntax(">(process) not supported"); |
3944 | debug_printf_parse("parse_stream return 1: >(process) not supported\n"); |
3945 | return 1; |
3946 | } |
3947 | #endif |
3948 | setup_redirect(ctx, redir_fd, redir_style, input); |
3949 | break; |
3950 | case '<': |
3951 | redir_fd = redirect_opt_num(dest); |
3952 | done_word(dest, ctx); |
3953 | redir_style = REDIRECT_INPUT; |
3954 | if (next == '<') { |
3955 | redir_style = REDIRECT_HEREIS; |
3956 | i_getch(input); |
3957 | } else if (next == '>') { |
3958 | redir_style = REDIRECT_IO; |
3959 | i_getch(input); |
3960 | } |
3961 | #if 0 |
3962 | else if (next == '(') { |
3963 | syntax("<(process) not supported"); |
3964 | debug_printf_parse("parse_stream return 1: <(process) not supported\n"); |
3965 | return 1; |
3966 | } |
3967 | #endif |
3968 | setup_redirect(ctx, redir_fd, redir_style, input); |
3969 | break; |
3970 | case ';': |
3971 | #if ENABLE_HUSH_CASE |
3972 | case_semi: |
3973 | #endif |
3974 | done_word(dest, ctx); |
3975 | done_pipe(ctx, PIPE_SEQ); |
3976 | #if ENABLE_HUSH_CASE |
3977 | /* Eat multiple semicolons, detect |
3978 | * whether it means something special */ |
3979 | while (1) { |
3980 | ch = i_peek(input); |
3981 | if (ch != ';') |
3982 | break; |
3983 | i_getch(input); |
3984 | if (ctx->ctx_res_w == RES_CASEI) { |
3985 | ctx->ctx_dsemicolon = 1; |
3986 | ctx->ctx_res_w = RES_MATCH; |
3987 | break; |
3988 | } |
3989 | } |
3990 | #endif |
3991 | new_cmd: |
3992 | /* We just finished a cmd. New one may start |
3993 | * with an assignment */ |
3994 | dest->o_assignment = MAYBE_ASSIGNMENT; |
3995 | break; |
3996 | case '&': |
3997 | done_word(dest, ctx); |
3998 | if (next == '&') { |
3999 | i_getch(input); |
4000 | done_pipe(ctx, PIPE_AND); |
4001 | } else { |
4002 | done_pipe(ctx, PIPE_BG); |
4003 | } |
4004 | goto new_cmd; |
4005 | case '|': |
4006 | done_word(dest, ctx); |
4007 | #if ENABLE_HUSH_CASE |
4008 | if (ctx->ctx_res_w == RES_MATCH) |
4009 | break; /* we are in case's "word | word)" */ |
4010 | #endif |
4011 | if (next == '|') { /* || */ |
4012 | i_getch(input); |
4013 | done_pipe(ctx, PIPE_OR); |
4014 | } else { |
4015 | /* we could pick up a file descriptor choice here |
4016 | * with redirect_opt_num(), but bash doesn't do it. |
4017 | * "echo foo 2| cat" yields "foo 2". */ |
4018 | done_command(ctx); |
4019 | } |
4020 | goto new_cmd; |
4021 | case '(': |
4022 | #if ENABLE_HUSH_CASE |
4023 | /* "case... in [(]word)..." - skip '(' */ |
4024 | if (ctx->ctx_res_w == RES_MATCH |
4025 | && ctx->command->argv == NULL /* not (word|(... */ |
4026 | && dest->length == 0 /* not word(... */ |
4027 | && dest->nonnull == 0 /* not ""(... */ |
4028 | ) { |
4029 | continue; |
4030 | } |
4031 | #endif |
4032 | #if ENABLE_HUSH_FUNCTIONS |
4033 | if (dest->length != 0 /* not just () but word() */ |
4034 | && dest->nonnull == 0 /* not a"b"c() */ |
4035 | && ctx->command->argv == NULL /* it's the first word */ |
4036 | //TODO: "func ( ) {...}" - note spaces - is valid format too in bash |
4037 | && i_peek(input) == ')' |
4038 | && !match_reserved_word(dest) |
4039 | ) { |
4040 | bb_error_msg("seems like a function definition"); |
4041 | i_getch(input); |
4042 | do { |
4043 | //TODO: do it properly. |
4044 | ch = i_getch(input); |
4045 | } while (ch == ' ' || ch == '\n'); |
4046 | if (ch != '{') { |
4047 | syntax("was expecting {"); |
4048 | debug_printf_parse("parse_stream return 1\n"); |
4049 | return 1; |
4050 | } |
4051 | ch = 'F'; /* magic value */ |
4052 | } |
4053 | #endif |
4054 | case '{': |
4055 | if (parse_group(dest, ctx, input, ch) != 0) { |
4056 | debug_printf_parse("parse_stream return 1: parse_group returned non-0\n"); |
4057 | return 1; |
4058 | } |
4059 | goto new_cmd; |
4060 | case ')': |
4061 | #if ENABLE_HUSH_CASE |
4062 | if (ctx->ctx_res_w == RES_MATCH) |
4063 | goto case_semi; |
4064 | #endif |
4065 | case '}': |
4066 | /* proper use of this character is caught by end_trigger: |
4067 | * if we see {, we call parse_group(..., end_trigger='}') |
4068 | * and it will match } earlier (not here). */ |
4069 | syntax("unexpected } or )"); |
4070 | debug_printf_parse("parse_stream return 1: unexpected '}'\n"); |
4071 | return 1; |
4072 | default: |
4073 | if (HUSH_DEBUG) |
4074 | bb_error_msg_and_die("BUG: unexpected %c\n", ch); |
4075 | } |
4076 | } /* while (1) */ |
4077 | debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL)); |
4078 | if (end_trigger) |
4079 | return -1; |
4080 | return 0; |
4081 | } |
4082 | |
4083 | static void set_in_charmap(const char *set, int code) |
4084 | { |
4085 | while (*set) |
4086 | G.charmap[(unsigned char)*set++] = code; |
4087 | } |
4088 | |
4089 | static void update_charmap(void) |
4090 | { |
4091 | G.ifs = getenv("IFS"); |
4092 | if (G.ifs == NULL) |
4093 | G.ifs = " \t\n"; |
4094 | /* Precompute a list of 'flow through' behavior so it can be treated |
4095 | * quickly up front. Computation is necessary because of IFS. |
4096 | * Special case handling of IFS == " \t\n" is not implemented. |
4097 | * The charmap[] array only really needs two bits each, |
4098 | * and on most machines that would be faster (reduced L1 cache use). |
4099 | */ |
4100 | memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap)); |
4101 | #if ENABLE_HUSH_TICK |
4102 | set_in_charmap("\\$\"`", CHAR_SPECIAL); |
4103 | #else |
4104 | set_in_charmap("\\$\"", CHAR_SPECIAL); |
4105 | #endif |
4106 | set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED); |
4107 | set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */ |
4108 | } |
4109 | |
4110 | /* Most recursion does not come through here, the exception is |
4111 | * from builtin_source() and builtin_eval() */ |
4112 | static int parse_and_run_stream(struct in_str *inp, int parse_flag) |
4113 | { |
4114 | struct parse_context ctx; |
4115 | o_string temp = NULL_O_STRING; |
4116 | int rcode; |
4117 | |
4118 | do { |
4119 | initialize_context(&ctx); |
4120 | update_charmap(); |
4121 | #if ENABLE_HUSH_INTERACTIVE |
4122 | inp->promptmode = 0; /* PS1 */ |
4123 | #endif |
4124 | /* We will stop & execute after each ';' or '\n'. |
4125 | * Example: "sleep 9999; echo TEST" + ctrl-C: |
4126 | * TEST should be printed */ |
4127 | temp.o_assignment = MAYBE_ASSIGNMENT; |
4128 | rcode = parse_stream(&temp, &ctx, inp, ";\n"); |
4129 | #if HAS_KEYWORDS |
4130 | if (rcode != 1 && ctx.old_flag != 0) { |
4131 | syntax(NULL); |
4132 | } |
4133 | #endif |
4134 | if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) { |
4135 | done_word(&temp, &ctx); |
4136 | done_pipe(&ctx, PIPE_SEQ); |
4137 | debug_print_tree(ctx.list_head, 0); |
4138 | debug_printf_exec("parse_stream_outer: run_and_free_list\n"); |
4139 | run_and_free_list(ctx.list_head); |
4140 | } else { |
4141 | /* We arrive here also if rcode == 1 (error in parse_stream) */ |
4142 | #if HAS_KEYWORDS |
4143 | if (ctx.old_flag != 0) { |
4144 | free(ctx.stack); |
4145 | o_reset(&temp); |
4146 | } |
4147 | #endif |
4148 | /*temp.nonnull = 0; - o_free does it below */ |
4149 | /*temp.o_quote = 0; - o_free does it below */ |
4150 | free_pipe_list(ctx.list_head, /* indent: */ 0); |
4151 | /* Discard all unprocessed line input, force prompt on */ |
4152 | inp->p = NULL; |
4153 | #if ENABLE_HUSH_INTERACTIVE |
4154 | inp->promptme = 1; |
4155 | #endif |
4156 | } |
4157 | o_free(&temp); |
4158 | /* loop on syntax errors, return on EOF: */ |
4159 | } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP)); |
4160 | return 0; |
4161 | } |
4162 | |
4163 | static int parse_and_run_string(const char *s, int parse_flag) |
4164 | { |
4165 | struct in_str input; |
4166 | setup_string_in_str(&input, s); |
4167 | return parse_and_run_stream(&input, parse_flag); |
4168 | } |
4169 | |
4170 | static int parse_and_run_file(FILE *f) |
4171 | { |
4172 | int rcode; |
4173 | struct in_str input; |
4174 | setup_file_in_str(&input, f); |
4175 | rcode = parse_and_run_stream(&input, 0 /* parse_flag */); |
4176 | return rcode; |
4177 | } |
4178 | |
4179 | #if ENABLE_HUSH_JOB |
4180 | /* Make sure we have a controlling tty. If we get started under a job |
4181 | * aware app (like bash for example), make sure we are now in charge so |
4182 | * we don't fight over who gets the foreground */ |
4183 | static void setup_job_control(void) |
4184 | { |
4185 | pid_t shell_pgrp; |
4186 | |
4187 | shell_pgrp = getpgrp(); |
4188 | close_on_exec_on(G.interactive_fd); |
4189 | |
4190 | /* If we were ran as 'hush &', |
4191 | * sleep until we are in the foreground. */ |
4192 | while (tcgetpgrp(G.interactive_fd) != shell_pgrp) { |
4193 | /* Send TTIN to ourself (should stop us) */ |
4194 | kill(- shell_pgrp, SIGTTIN); |
4195 | shell_pgrp = getpgrp(); |
4196 | } |
4197 | |
4198 | /* Ignore job-control and misc signals. */ |
4199 | set_jobctrl_sighandler(SIG_IGN); |
4200 | set_misc_sighandler(SIG_IGN); |
4201 | //huh? signal(SIGCHLD, SIG_IGN); |
4202 | |
4203 | /* We _must_ restore tty pgrp on fatal signals */ |
4204 | set_fatal_sighandler(sigexit); |
4205 | |
4206 | /* Put ourselves in our own process group. */ |
4207 | bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */ |
4208 | /* Grab control of the terminal. */ |
4209 | tcsetpgrp(G.interactive_fd, getpid()); |
4210 | } |
4211 | #endif |
4212 | |
4213 | |
4214 | int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; |
4215 | int hush_main(int argc, char **argv) |
4216 | { |
4217 | static const struct variable const_shell_ver = { |
4218 | .next = NULL, |
4219 | .varstr = (char*)hush_version_str, |
4220 | .max_len = 1, /* 0 can provoke free(name) */ |
4221 | .flg_export = 1, |
4222 | .flg_read_only = 1, |
4223 | }; |
4224 | |
4225 | int opt; |
4226 | FILE *input; |
4227 | char **e; |
4228 | struct variable *cur_var; |
4229 | |
4230 | INIT_G(); |
4231 | |
4232 | G.root_pid = getpid(); |
4233 | |
4234 | /* Deal with HUSH_VERSION */ |
4235 | G.shell_ver = const_shell_ver; /* copying struct here */ |
4236 | G.top_var = &G.shell_ver; |
4237 | debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION"); |
4238 | unsetenv("HUSH_VERSION"); /* in case it exists in initial env */ |
4239 | /* Initialize our shell local variables with the values |
4240 | * currently living in the environment */ |
4241 | cur_var = G.top_var; |
4242 | e = environ; |
4243 | if (e) while (*e) { |
4244 | char *value = strchr(*e, '='); |
4245 | if (value) { /* paranoia */ |
4246 | cur_var->next = xzalloc(sizeof(*cur_var)); |
4247 | cur_var = cur_var->next; |
4248 | cur_var->varstr = *e; |
4249 | cur_var->max_len = strlen(*e); |
4250 | cur_var->flg_export = 1; |
4251 | } |
4252 | e++; |
4253 | } |
4254 | debug_printf_env("putenv '%s'\n", hush_version_str); |
4255 | putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */ |
4256 | |
4257 | #if ENABLE_FEATURE_EDITING |
4258 | G.line_input_state = new_line_input_t(FOR_SHELL); |
4259 | #endif |
4260 | /* XXX what should these be while sourcing /etc/profile? */ |
4261 | G.global_argc = argc; |
4262 | G.global_argv = argv; |
4263 | /* Initialize some more globals to non-zero values */ |
4264 | set_cwd(); |
4265 | #if ENABLE_HUSH_INTERACTIVE |
4266 | #if ENABLE_FEATURE_EDITING |
4267 | cmdedit_set_initial_prompt(); |
4268 | #endif |
4269 | G.PS2 = "> "; |
4270 | #endif |
4271 | |
4272 | if (EXIT_SUCCESS) /* otherwise is already done */ |
4273 | G.last_return_code = EXIT_SUCCESS; |
4274 | |
4275 | if (argv[0] && argv[0][0] == '-') { |
4276 | debug_printf("sourcing /etc/profile\n"); |
4277 | input = fopen_for_read("/etc/profile"); |
4278 | if (input != NULL) { |
4279 | close_on_exec_on(fileno(input)); |
4280 | parse_and_run_file(input); |
4281 | fclose(input); |
4282 | } |
4283 | } |
4284 | input = stdin; |
4285 | |
4286 | while ((opt = getopt(argc, argv, "c:xif")) > 0) { |
4287 | switch (opt) { |
4288 | case 'c': |
4289 | G.global_argv = argv + optind; |
4290 | if (!argv[optind]) { |
4291 | /* -c 'script' (no params): prevent empty $0 */ |
4292 | *--G.global_argv = argv[0]; |
4293 | optind--; |
4294 | } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */ |
4295 | G.global_argc = argc - optind; |
4296 | opt = parse_and_run_string(optarg, 0 /* parse_flag */); |
4297 | goto final_return; |
4298 | case 'i': |
4299 | /* Well, we cannot just declare interactiveness, |
4300 | * we have to have some stuff (ctty, etc) */ |
4301 | /* G.interactive_fd++; */ |
4302 | break; |
4303 | case 'f': |
4304 | G.fake_mode = 1; |
4305 | break; |
4306 | default: |
4307 | #ifndef BB_VER |
4308 | fprintf(stderr, "Usage: sh [FILE]...\n" |
4309 | " or: sh -c command [args]...\n\n"); |
4310 | exit(EXIT_FAILURE); |
4311 | #else |
4312 | bb_show_usage(); |
4313 | #endif |
4314 | } |
4315 | } |
4316 | #if ENABLE_HUSH_JOB |
4317 | /* A shell is interactive if the '-i' flag was given, or if all of |
4318 | * the following conditions are met: |
4319 | * no -c command |
4320 | * no arguments remaining or the -s flag given |
4321 | * standard input is a terminal |
4322 | * standard output is a terminal |
4323 | * Refer to Posix.2, the description of the 'sh' utility. */ |
4324 | if (argv[optind] == NULL && input == stdin |
4325 | && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) |
4326 | ) { |
4327 | G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO); |
4328 | debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp); |
4329 | if (G.saved_tty_pgrp >= 0) { |
4330 | /* try to dup to high fd#, >= 255 */ |
4331 | G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255); |
4332 | if (G.interactive_fd < 0) { |
4333 | /* try to dup to any fd */ |
4334 | G.interactive_fd = dup(STDIN_FILENO); |
4335 | if (G.interactive_fd < 0) |
4336 | /* give up */ |
4337 | G.interactive_fd = 0; |
4338 | } |
4339 | // TODO: track & disallow any attempts of user |
4340 | // to (inadvertently) close/redirect it |
4341 | } |
4342 | } |
4343 | debug_printf("G.interactive_fd=%d\n", G.interactive_fd); |
4344 | if (G.interactive_fd) { |
4345 | fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC); |
4346 | /* Looks like they want an interactive shell */ |
4347 | setup_job_control(); |
4348 | /* -1 is special - makes xfuncs longjmp, not exit |
4349 | * (we reset die_sleep = 0 whereever we [v]fork) */ |
4350 | die_sleep = -1; |
4351 | if (setjmp(die_jmp)) { |
4352 | /* xfunc has failed! die die die */ |
4353 | hush_exit(xfunc_error_retval); |
4354 | } |
4355 | #if !ENABLE_FEATURE_SH_EXTRA_QUIET |
4356 | printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner); |
4357 | printf("Enter 'help' for a list of built-in commands.\n\n"); |
4358 | #endif |
4359 | } |
4360 | #elif ENABLE_HUSH_INTERACTIVE |
4361 | /* no job control compiled, only prompt/line editing */ |
4362 | if (argv[optind] == NULL && input == stdin |
4363 | && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) |
4364 | ) { |
4365 | G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255); |
4366 | if (G.interactive_fd < 0) { |
4367 | /* try to dup to any fd */ |
4368 | G.interactive_fd = dup(STDIN_FILENO); |
4369 | if (G.interactive_fd < 0) |
4370 | /* give up */ |
4371 | G.interactive_fd = 0; |
4372 | } |
4373 | if (G.interactive_fd) { |
4374 | fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC); |
4375 | set_misc_sighandler(SIG_IGN); |
4376 | } |
4377 | } |
4378 | #endif |
4379 | |
4380 | if (argv[optind] == NULL) { |
4381 | opt = parse_and_run_file(stdin); |
4382 | } else { |
4383 | debug_printf("\nrunning script '%s'\n", argv[optind]); |
4384 | G.global_argv = argv + optind; |
4385 | G.global_argc = argc - optind; |
4386 | input = xfopen_for_read(argv[optind]); |
4387 | fcntl(fileno(input), F_SETFD, FD_CLOEXEC); |
4388 | opt = parse_and_run_file(input); |
4389 | } |
4390 | |
4391 | final_return: |
4392 | |
4393 | #if ENABLE_FEATURE_CLEAN_UP |
4394 | fclose(input); |
4395 | if (G.cwd != bb_msg_unknown) |
4396 | free((char*)G.cwd); |
4397 | cur_var = G.top_var->next; |
4398 | while (cur_var) { |
4399 | struct variable *tmp = cur_var; |
4400 | if (!cur_var->max_len) |
4401 | free(cur_var->varstr); |
4402 | cur_var = cur_var->next; |
4403 | free(tmp); |
4404 | } |
4405 | #endif |
4406 | hush_exit(opt ? opt : G.last_return_code); |
4407 | } |
4408 | |
4409 | |
4410 | #if ENABLE_LASH |
4411 | int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; |
4412 | int lash_main(int argc, char **argv) |
4413 | { |
4414 | //bb_error_msg("lash is deprecated, please use hush instead"); |
4415 | return hush_main(argc, argv); |
4416 | } |
4417 | #endif |
4418 | |
4419 | |
4420 | /* |
4421 | * Built-ins |
4422 | */ |
4423 | static int builtin_true(char **argv UNUSED_PARAM) |
4424 | { |
4425 | return 0; |
4426 | } |
4427 | |
4428 | static int builtin_test(char **argv) |
4429 | { |
4430 | int argc = 0; |
4431 | while (*argv) { |
4432 | argc++; |
4433 | argv++; |
4434 | } |
4435 | return test_main(argc, argv - argc); |
4436 | } |
4437 | |
4438 | static int builtin_echo(char **argv) |
4439 | { |
4440 | int argc = 0; |
4441 | while (*argv) { |
4442 | argc++; |
4443 | argv++; |
4444 | } |
4445 | return echo_main(argc, argv - argc); |
4446 | } |
4447 | |
4448 | static int builtin_eval(char **argv) |
4449 | { |
4450 | int rcode = EXIT_SUCCESS; |
4451 | |
4452 | if (argv[1]) { |
4453 | char *str = expand_strvec_to_string(argv + 1); |
4454 | parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP); |
4455 | free(str); |
4456 | rcode = G.last_return_code; |
4457 | } |
4458 | return rcode; |
4459 | } |
4460 | |
4461 | static int builtin_cd(char **argv) |
4462 | { |
4463 | const char *newdir; |
4464 | if (argv[1] == NULL) { |
4465 | // bash does nothing (exitcode 0) if HOME is ""; if it's unset, |
4466 | // bash says "bash: cd: HOME not set" and does nothing (exitcode 1) |
4467 | newdir = getenv("HOME") ? : "/"; |
4468 | } else |
4469 | newdir = argv[1]; |
4470 | if (chdir(newdir)) { |
4471 | printf("cd: %s: %s\n", newdir, strerror(errno)); |
4472 | return EXIT_FAILURE; |
4473 | } |
4474 | set_cwd(); |
4475 | return EXIT_SUCCESS; |
4476 | } |
4477 | |
4478 | static int builtin_exec(char **argv) |
4479 | { |
4480 | if (argv[1] == NULL) |
4481 | return EXIT_SUCCESS; /* bash does this */ |
4482 | { |
4483 | #if !BB_MMU |
4484 | nommu_save_t dummy; |
4485 | #endif |
4486 | // FIXME: if exec fails, bash does NOT exit! We do... |
4487 | pseudo_exec_argv(&dummy, argv + 1, 0, NULL); |
4488 | /* never returns */ |
4489 | } |
4490 | } |
4491 | |
4492 | static int builtin_exit(char **argv) |
4493 | { |
4494 | // TODO: bash does it ONLY on top-level sh exit (+interacive only?) |
4495 | //puts("exit"); /* bash does it */ |
4496 | // TODO: warn if we have background jobs: "There are stopped jobs" |
4497 | // On second consecutive 'exit', exit anyway. |
4498 | if (argv[1] == NULL) |
4499 | hush_exit(G.last_return_code); |
4500 | /* mimic bash: exit 123abc == exit 255 + error msg */ |
4501 | xfunc_error_retval = 255; |
4502 | /* bash: exit -2 == exit 254, no error msg */ |
4503 | hush_exit(xatoi(argv[1]) & 0xff); |
4504 | } |
4505 | |
4506 | static int builtin_export(char **argv) |
4507 | { |
4508 | const char *value; |
4509 | char *name = argv[1]; |
4510 | |
4511 | if (name == NULL) { |
4512 | // TODO: |
4513 | // ash emits: export VAR='VAL' |
4514 | // bash: declare -x VAR="VAL" |
4515 | // (both also escape as needed (quotes, $, etc)) |
4516 | char **e = environ; |
4517 | if (e) |
4518 | while (*e) |
4519 | puts(*e++); |
4520 | return EXIT_SUCCESS; |
4521 | } |
4522 | |
4523 | value = strchr(name, '='); |
4524 | if (!value) { |
4525 | /* They are exporting something without a =VALUE */ |
4526 | struct variable *var; |
4527 | |
4528 | var = get_local_var(name); |
4529 | if (var) { |
4530 | var->flg_export = 1; |
4531 | debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr); |
4532 | putenv(var->varstr); |
4533 | } |
4534 | /* bash does not return an error when trying to export |
4535 | * an undefined variable. Do likewise. */ |
4536 | return EXIT_SUCCESS; |
4537 | } |
4538 | |
4539 | set_local_var(xstrdup(name), 1); |
4540 | return EXIT_SUCCESS; |
4541 | } |
4542 | |
4543 | #if ENABLE_HUSH_JOB |
4544 | /* built-in 'fg' and 'bg' handler */ |
4545 | static int builtin_fg_bg(char **argv) |
4546 | { |
4547 | int i, jobnum; |
4548 | struct pipe *pi; |
4549 | |
4550 | if (!G.interactive_fd) |
4551 | return EXIT_FAILURE; |
4552 | /* If they gave us no args, assume they want the last backgrounded task */ |
4553 | if (!argv[1]) { |
4554 | for (pi = G.job_list; pi; pi = pi->next) { |
4555 | if (pi->jobid == G.last_jobid) { |
4556 | goto found; |
4557 | } |
4558 | } |
4559 | bb_error_msg("%s: no current job", argv[0]); |
4560 | return EXIT_FAILURE; |
4561 | } |
4562 | if (sscanf(argv[1], "%%%d", &jobnum) != 1) { |
4563 | bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]); |
4564 | return EXIT_FAILURE; |
4565 | } |
4566 | for (pi = G.job_list; pi; pi = pi->next) { |
4567 | if (pi->jobid == jobnum) { |
4568 | goto found; |
4569 | } |
4570 | } |
4571 | bb_error_msg("%s: %d: no such job", argv[0], jobnum); |
4572 | return EXIT_FAILURE; |
4573 | found: |
4574 | // TODO: bash prints a string representation |
4575 | // of job being foregrounded (like "sleep 1 | cat") |
4576 | if (*argv[0] == 'f') { |
4577 | /* Put the job into the foreground. */ |
4578 | tcsetpgrp(G.interactive_fd, pi->pgrp); |
4579 | } |
4580 | |
4581 | /* Restart the processes in the job */ |
4582 | debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp); |
4583 | for (i = 0; i < pi->num_cmds; i++) { |
4584 | debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid); |
4585 | pi->cmds[i].is_stopped = 0; |
4586 | } |
4587 | pi->stopped_cmds = 0; |
4588 | |
4589 | i = kill(- pi->pgrp, SIGCONT); |
4590 | if (i < 0) { |
4591 | if (errno == ESRCH) { |
4592 | delete_finished_bg_job(pi); |
4593 | return EXIT_SUCCESS; |
4594 | } else { |
4595 | bb_perror_msg("kill (SIGCONT)"); |
4596 | } |
4597 | } |
4598 | |
4599 | if (*argv[0] == 'f') { |
4600 | remove_bg_job(pi); |
4601 | return checkjobs_and_fg_shell(pi); |
4602 | } |
4603 | return EXIT_SUCCESS; |
4604 | } |
4605 | #endif |
4606 | |
4607 | #if ENABLE_HUSH_HELP |
4608 | static int builtin_help(char **argv UNUSED_PARAM) |
4609 | { |
4610 | const struct built_in_command *x; |
4611 | |
4612 | printf("\nBuilt-in commands:\n"); |
4613 | printf("-------------------\n"); |
4614 | for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) { |
4615 | printf("%s\t%s\n", x->cmd, x->descr); |
4616 | } |
4617 | printf("\n\n"); |
4618 | return EXIT_SUCCESS; |
4619 | } |
4620 | #endif |
4621 | |
4622 | #if ENABLE_HUSH_JOB |
4623 | static int builtin_jobs(char **argv UNUSED_PARAM) |
4624 | { |
4625 | struct pipe *job; |
4626 | const char *status_string; |
4627 | |
4628 | for (job = G.job_list; job; job = job->next) { |
4629 | if (job->alive_cmds == job->stopped_cmds) |
4630 | status_string = "Stopped"; |
4631 | else |
4632 | status_string = "Running"; |
4633 | |
4634 | printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext); |
4635 | } |
4636 | return EXIT_SUCCESS; |
4637 | } |
4638 | #endif |
4639 | |
4640 | static int builtin_pwd(char **argv UNUSED_PARAM) |
4641 | { |
4642 | puts(set_cwd()); |
4643 | return EXIT_SUCCESS; |
4644 | } |
4645 | |
4646 | static int builtin_read(char **argv) |
4647 | { |
4648 | char *string; |
4649 | const char *name = argv[1] ? argv[1] : "REPLY"; |
4650 | |
4651 | string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL); |
4652 | return set_local_var(string, 0); |
4653 | } |
4654 | |
4655 | /* built-in 'set' handler |
4656 | * SUSv3 says: |
4657 | * set [-abCefmnuvx] [-h] [-o option] [argument...] |
4658 | * set [+abCefmnuvx] [+h] [+o option] [argument...] |
4659 | * set -- [argument...] |
4660 | * set -o |
4661 | * set +o |
4662 | * Implementations shall support the options in both their hyphen and |
4663 | * plus-sign forms. These options can also be specified as options to sh. |
4664 | * Examples: |
4665 | * Write out all variables and their values: set |
4666 | * Set $1, $2, and $3 and set "$#" to 3: set c a b |
4667 | * Turn on the -x and -v options: set -xv |
4668 | * Unset all positional parameters: set -- |
4669 | * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x" |
4670 | * Set the positional parameters to the expansion of x, even if x expands |
4671 | * with a leading '-' or '+': set -- $x |
4672 | * |
4673 | * So far, we only support "set -- [argument...]" by ignoring all options |
4674 | * (also, "-o option" will be mishandled by taking "option" as parameter #1). |
4675 | */ |
4676 | static int builtin_set(char **argv) |
4677 | { |
4678 | struct variable *e; |
4679 | char **pp; |
4680 | char *arg = *++argv; |
4681 | |
4682 | if (arg == NULL) { |
4683 | for (e = G.top_var; e; e = e->next) |
4684 | puts(e->varstr); |
4685 | } else { |
4686 | /* NB: G.global_argv[0] ($0) is never freed/changed */ |
4687 | |
4688 | if (G.global_args_malloced) { |
4689 | pp = G.global_argv; |
4690 | while (*++pp) |
4691 | free(*pp); |
4692 | G.global_argv[1] = NULL; |
4693 | } else { |
4694 | G.global_args_malloced = 1; |
4695 | pp = xzalloc(sizeof(pp[0]) * 2); |
4696 | pp[0] = G.global_argv[0]; /* retain $0 */ |
4697 | G.global_argv = pp; |
4698 | } |
4699 | do { |
4700 | if (arg[0] == '+') |
4701 | continue; |
4702 | if (arg[0] != '-') |
4703 | break; |
4704 | if (arg[1] == '-' && arg[2] == '\0') { |
4705 | argv++; |
4706 | break; |
4707 | } |
4708 | } while ((arg = *++argv) != NULL); |
4709 | /* Now argv[0] is 1st argument */ |
4710 | |
4711 | /* This realloc's G.global_argv */ |
4712 | G.global_argv = pp = add_strings_to_strings(G.global_argv, argv, /*dup:*/ 1); |
4713 | G.global_argc = 1; |
4714 | while (*++pp) |
4715 | G.global_argc++; |
4716 | } |
4717 | |
4718 | return EXIT_SUCCESS; |
4719 | } |
4720 | |
4721 | static int builtin_shift(char **argv) |
4722 | { |
4723 | int n = 1; |
4724 | if (argv[1]) { |
4725 | n = atoi(argv[1]); |
4726 | } |
4727 | if (n >= 0 && n < G.global_argc) { |
4728 | if (G.global_args_malloced) { |
4729 | int m = 1; |
4730 | while (m <= n) |
4731 | free(G.global_argv[m++]); |
4732 | } |
4733 | G.global_argc -= n; |
4734 | memmove(&G.global_argv[1], &G.global_argv[n+1], |
4735 | G.global_argc * sizeof(G.global_argv[0])); |
4736 | return EXIT_SUCCESS; |
4737 | } |
4738 | return EXIT_FAILURE; |
4739 | } |
4740 | |
4741 | static int builtin_source(char **argv) |
4742 | { |
4743 | FILE *input; |
4744 | int status; |
4745 | |
4746 | if (argv[1] == NULL) |
4747 | return EXIT_FAILURE; |
4748 | |
4749 | /* XXX search through $PATH is missing */ |
4750 | input = fopen_for_read(argv[1]); |
4751 | if (!input) { |
4752 | bb_error_msg("can't open '%s'", argv[1]); |
4753 | return EXIT_FAILURE; |
4754 | } |
4755 | close_on_exec_on(fileno(input)); |
4756 | |
4757 | /* Now run the file */ |
4758 | /* XXX argv and argc are broken; need to save old G.global_argv |
4759 | * (pointer only is OK!) on this stack frame, |
4760 | * set G.global_argv=argv+1, recurse, and restore. */ |
4761 | status = parse_and_run_file(input); |
4762 | fclose(input); |
4763 | return status; |
4764 | } |
4765 | |
4766 | static int builtin_umask(char **argv) |
4767 | { |
4768 | mode_t new_umask; |
4769 | const char *arg = argv[1]; |
4770 | char *end; |
4771 | if (arg) { |
4772 | new_umask = strtoul(arg, &end, 8); |
4773 | if (*end != '\0' || end == arg) { |
4774 | return EXIT_FAILURE; |
4775 | } |
4776 | } else { |
4777 | new_umask = umask(0); |
4778 | printf("%.3o\n", (unsigned) new_umask); |
4779 | } |
4780 | umask(new_umask); |
4781 | return EXIT_SUCCESS; |
4782 | } |
4783 | |
4784 | static int builtin_unset(char **argv) |
4785 | { |
4786 | /* bash always returns true */ |
4787 | unset_local_var(argv[1]); |
4788 | return EXIT_SUCCESS; |
4789 | } |
4790 | |
4791 | #if ENABLE_HUSH_LOOPS |
4792 | static int builtin_break(char **argv) |
4793 | { |
4794 | if (G.depth_of_loop == 0) { |
4795 | bb_error_msg("%s: only meaningful in a loop", argv[0]); |
4796 | return EXIT_SUCCESS; /* bash compat */ |
4797 | } |
4798 | G.flag_break_continue++; /* BC_BREAK = 1 */ |
4799 | G.depth_break_continue = 1; |
4800 | if (argv[1]) { |
4801 | G.depth_break_continue = bb_strtou(argv[1], NULL, 10); |
4802 | if (errno || !G.depth_break_continue || argv[2]) { |
4803 | bb_error_msg("%s: bad arguments", argv[0]); |
4804 | G.flag_break_continue = BC_BREAK; |
4805 | G.depth_break_continue = UINT_MAX; |
4806 | } |
4807 | } |
4808 | if (G.depth_of_loop < G.depth_break_continue) |
4809 | G.depth_break_continue = G.depth_of_loop; |
4810 | return EXIT_SUCCESS; |
4811 | } |
4812 | |
4813 | static int builtin_continue(char **argv) |
4814 | { |
4815 | G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */ |
4816 | return builtin_break(argv); |
4817 | } |
4818 | #endif |