blob: 5b432247599fc521cc184d7ca0b81c8109ee4f8e [file] [log] [blame]
wdenkfe8c2802002-11-03 00:38:21 +00001/*
2 * sh.c -- a prototype Bourne shell grammar parser
3 * Intended to follow the original Thompson and Ritchie
4 * "small and simple is beautiful" philosophy, which
5 * incidentally is a good match to today's BusyBox.
6 *
7 * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
8 *
9 * Credits:
10 * The parser routines proper are all original material, first
11 * written Dec 2000 and Jan 2001 by Larry Doolittle.
12 * The execution engine, the builtins, and much of the underlying
13 * support has been adapted from busybox-0.49pre's lash,
14 * which is Copyright (C) 2000 by Lineo, Inc., and
15 * written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>.
16 * That, in turn, is based in part on ladsh.c, by Michael K. Johnson and
17 * Erik W. Troan, which they placed in the public domain. I don't know
18 * how much of the Johnson/Troan code has survived the repeated rewrites.
19 * Other credits:
wdenkfe8c2802002-11-03 00:38:21 +000020 * b_addchr() derived from similar w_addchar function in glibc-2.2
21 * setup_redirect(), redirect_opt_num(), and big chunks of main()
22 * and many builtins derived from contributions by Erik Andersen
23 * miscellaneous bugfixes from Matt Kraai
24 *
25 * There are two big (and related) architecture differences between
26 * this parser and the lash parser. One is that this version is
27 * actually designed from the ground up to understand nearly all
28 * of the Bourne grammar. The second, consequential change is that
29 * the parser and input reader have been turned inside out. Now,
30 * the parser is in control, and asks for input as needed. The old
31 * way had the input reader in control, and it asked for parsing to
32 * take place as needed. The new way makes it much easier to properly
33 * handle the recursion implicit in the various substitutions, especially
34 * across continuation lines.
35 *
36 * Bash grammar not implemented: (how many of these were in original sh?)
37 * $@ (those sure look like weird quoting rules)
38 * $_
39 * ! negation operator for pipes
40 * &> and >& redirection of stdout+stderr
41 * Brace Expansion
42 * Tilde Expansion
43 * fancy forms of Parameter Expansion
44 * aliases
45 * Arithmetic Expansion
46 * <(list) and >(list) Process Substitution
47 * reserved words: case, esac, select, function
48 * Here Documents ( << word )
49 * Functions
50 * Major bugs:
51 * job handling woefully incomplete and buggy
52 * reserved word execution woefully incomplete and buggy
53 * to-do:
54 * port selected bugfixes from post-0.49 busybox lash - done?
55 * finish implementing reserved words: for, while, until, do, done
56 * change { and } from special chars to reserved words
57 * builtins: break, continue, eval, return, set, trap, ulimit
58 * test magic exec
59 * handle children going into background
60 * clean up recognition of null pipes
61 * check setting of global_argc and global_argv
62 * control-C handling, probably with longjmp
63 * follow IFS rules more precisely, including update semantics
64 * figure out what to do with backslash-newline
65 * explain why we use signal instead of sigaction
66 * propagate syntax errors, die on resource errors?
67 * continuation lines, both explicit and implicit - done?
68 * memory leak finding and plugging - done?
69 * more testing, especially quoting rules and redirection
70 * document how quoting rules not precisely followed for variable assignments
71 * maybe change map[] to use 2-bit entries
72 * (eventually) remove all the printf's
73 *
Wolfgang Denkd79de1d2013-07-08 09:37:19 +020074 * SPDX-License-Identifier: GPL-2.0+
wdenkfe8c2802002-11-03 00:38:21 +000075 */
Wolfgang Denkd79de1d2013-07-08 09:37:19 +020076
wdenkfe8c2802002-11-03 00:38:21 +000077#define __U_BOOT__
78#ifdef __U_BOOT__
79#include <malloc.h> /* malloc, free, realloc*/
80#include <linux/ctype.h> /* isalpha, isdigit */
81#include <common.h> /* readline */
82#include <hush.h>
83#include <command.h> /* find_cmd */
Tom Rini584c0ea2012-06-19 15:54:35 -070084#ifndef CONFIG_SYS_PROMPT_HUSH_PS2
85#define CONFIG_SYS_PROMPT_HUSH_PS2 "> "
86#endif
wdenkfe8c2802002-11-03 00:38:21 +000087#endif
wdenkfe8c2802002-11-03 00:38:21 +000088#ifndef __U_BOOT__
89#include <ctype.h> /* isalpha, isdigit */
90#include <unistd.h> /* getpid */
91#include <stdlib.h> /* getenv, atoi */
92#include <string.h> /* strchr */
93#include <stdio.h> /* popen etc. */
94#include <glob.h> /* glob, of course */
95#include <stdarg.h> /* va_list */
96#include <errno.h>
97#include <fcntl.h>
98#include <getopt.h> /* should be pretty obvious */
99
100#include <sys/stat.h> /* ulimit */
101#include <sys/types.h>
102#include <sys/wait.h>
103#include <signal.h>
104
105/* #include <dmalloc.h> */
wdenkfe8c2802002-11-03 00:38:21 +0000106
wdenke7f34c62003-01-11 09:48:40 +0000107#if 1
wdenkfe8c2802002-11-03 00:38:21 +0000108#include "busybox.h"
109#include "cmdedit.h"
110#else
111#define applet_name "hush"
112#include "standalone.h"
113#define hush_main main
wdenke7f34c62003-01-11 09:48:40 +0000114#undef CONFIG_FEATURE_SH_FANCY_PROMPT
115#define BB_BANNER
wdenkfe8c2802002-11-03 00:38:21 +0000116#endif
117#endif
118#define SPECIAL_VAR_SYMBOL 03
Joe Hershberger38de0b62012-08-17 10:26:30 +0000119#define SUBSTED_VAR_SYMBOL 04
wdenkfe8c2802002-11-03 00:38:21 +0000120#ifndef __U_BOOT__
121#define FLAG_EXIT_FROM_LOOP 1
122#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
123#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
124
125#endif
126
127#ifdef __U_BOOT__
Wolfgang Denk6405a152006-03-31 18:32:53 +0200128DECLARE_GLOBAL_DATA_PTR;
129
wdenkfe8c2802002-11-03 00:38:21 +0000130#define EXIT_SUCCESS 0
131#define EOF -1
132#define syntax() syntax_err()
133#define xstrdup strdup
134#define error_msg printf
135#else
136typedef enum {
137 REDIRECT_INPUT = 1,
138 REDIRECT_OVERWRITE = 2,
139 REDIRECT_APPEND = 3,
140 REDIRECT_HEREIS = 4,
141 REDIRECT_IO = 5
142} redir_type;
143
144/* The descrip member of this structure is only used to make debugging
145 * output pretty */
146struct {int mode; int default_fd; char *descrip;} redir_table[] = {
147 { 0, 0, "()" },
148 { O_RDONLY, 0, "<" },
149 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
150 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
151 { O_RDONLY, -1, "<<" },
152 { O_RDWR, 1, "<>" }
153};
154#endif
155
156typedef enum {
157 PIPE_SEQ = 1,
158 PIPE_AND = 2,
159 PIPE_OR = 3,
160 PIPE_BG = 4,
161} pipe_style;
162
163/* might eventually control execution */
164typedef enum {
165 RES_NONE = 0,
166 RES_IF = 1,
167 RES_THEN = 2,
168 RES_ELIF = 3,
169 RES_ELSE = 4,
170 RES_FI = 5,
171 RES_FOR = 6,
172 RES_WHILE = 7,
173 RES_UNTIL = 8,
174 RES_DO = 9,
175 RES_DONE = 10,
176 RES_XXXX = 11,
177 RES_IN = 12,
178 RES_SNTX = 13
179} reserved_style;
180#define FLAG_END (1<<RES_NONE)
181#define FLAG_IF (1<<RES_IF)
182#define FLAG_THEN (1<<RES_THEN)
183#define FLAG_ELIF (1<<RES_ELIF)
184#define FLAG_ELSE (1<<RES_ELSE)
185#define FLAG_FI (1<<RES_FI)
186#define FLAG_FOR (1<<RES_FOR)
187#define FLAG_WHILE (1<<RES_WHILE)
188#define FLAG_UNTIL (1<<RES_UNTIL)
189#define FLAG_DO (1<<RES_DO)
190#define FLAG_DONE (1<<RES_DONE)
191#define FLAG_IN (1<<RES_IN)
192#define FLAG_START (1<<RES_XXXX)
193
194/* This holds pointers to the various results of parsing */
195struct p_context {
196 struct child_prog *child;
197 struct pipe *list_head;
198 struct pipe *pipe;
199#ifndef __U_BOOT__
200 struct redir_struct *pending_redirect;
201#endif
202 reserved_style w;
203 int old_flag; /* for figuring out valid reserved words */
204 struct p_context *stack;
205 int type; /* define type of parser : ";$" common or special symbol */
206 /* How about quoting status? */
207};
208
209#ifndef __U_BOOT__
210struct redir_struct {
211 redir_type type; /* type of redirection */
212 int fd; /* file descriptor being redirected */
213 int dup; /* -1, or file descriptor being duplicated */
214 struct redir_struct *next; /* pointer to the next redirect in the list */
215 glob_t word; /* *word.gl_pathv is the filename */
216};
217#endif
218
219struct child_prog {
220#ifndef __U_BOOT__
221 pid_t pid; /* 0 if exited */
222#endif
223 char **argv; /* program name and arguments */
Stephen Warren60c38c92014-03-01 22:16:10 -0700224 /* was quoted when parsed; copy of struct o_string.nonnull field */
225 int *argv_nonnull;
wdenkfe8c2802002-11-03 00:38:21 +0000226#ifdef __U_BOOT__
227 int argc; /* number of program arguments */
228#endif
229 struct pipe *group; /* if non-NULL, first in group or subshell */
230#ifndef __U_BOOT__
231 int subshell; /* flag, non-zero if group must be forked */
232 struct redir_struct *redirects; /* I/O redirections */
233 glob_t glob_result; /* result of parameter globbing */
234 int is_stopped; /* is the program currently running? */
235 struct pipe *family; /* pointer back to the child's parent pipe */
236#endif
237 int sp; /* number of SPECIAL_VAR_SYMBOL */
238 int type;
239};
240
241struct pipe {
242#ifndef __U_BOOT__
243 int jobid; /* job number */
244#endif
245 int num_progs; /* total number of programs in job */
246#ifndef __U_BOOT__
247 int running_progs; /* number of programs running */
248 char *text; /* name of job */
249 char *cmdbuf; /* buffer various argv's point into */
250 pid_t pgrp; /* process group ID for the job */
251#endif
252 struct child_prog *progs; /* array of commands in pipe */
253 struct pipe *next; /* to track background commands */
254#ifndef __U_BOOT__
255 int stopped_progs; /* number of programs alive, but stopped */
256 int job_context; /* bitmask defining current context */
257#endif
258 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
259 reserved_style r_mode; /* supports if, for, while, until */
260};
261
262#ifndef __U_BOOT__
263struct close_me {
264 int fd;
265 struct close_me *next;
266};
267#endif
268
269struct variables {
270 char *name;
271 char *value;
272 int flg_export;
273 int flg_read_only;
274 struct variables *next;
275};
276
277/* globals, connect us to the outside world
278 * the first three support $?, $#, and $1 */
279#ifndef __U_BOOT__
280char **global_argv;
281unsigned int global_argc;
282#endif
Kim Phillipsb052b602012-10-29 13:34:32 +0000283static unsigned int last_return_code;
wdenkfe8c2802002-11-03 00:38:21 +0000284#ifndef __U_BOOT__
285extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
286#endif
287
288/* "globals" within this file */
Wolfgang Denk7fb52662005-10-13 16:45:02 +0200289static uchar *ifs;
wdenkfe8c2802002-11-03 00:38:21 +0000290static char map[256];
291#ifndef __U_BOOT__
292static int fake_mode;
293static int interactive;
294static struct close_me *close_me_head;
295static const char *cwd;
296static struct pipe *job_list;
297static unsigned int last_bg_pid;
298static unsigned int last_jobid;
299static unsigned int shell_terminal;
300static char *PS1;
301static char *PS2;
302struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
303struct variables *top_vars = &shell_ver;
304#else
305static int flag_repeat = 0;
306static int do_repeat = 0;
wdenkbd1575f2003-10-14 19:43:55 +0000307static struct variables *top_vars = NULL ;
wdenkfe8c2802002-11-03 00:38:21 +0000308#endif /*__U_BOOT__ */
309
310#define B_CHUNK (100)
311#define B_NOSPAC 1
312
313typedef struct {
314 char *data;
315 int length;
316 int maxlen;
317 int quote;
318 int nonnull;
319} o_string;
320#define NULL_O_STRING {NULL,0,0,0,0}
321/* used for initialization:
322 o_string foo = NULL_O_STRING; */
323
324/* I can almost use ordinary FILE *. Is open_memstream() universally
325 * available? Where is it documented? */
326struct in_str {
327 const char *p;
328#ifndef __U_BOOT__
329 char peek_buf[2];
330#endif
331 int __promptme;
332 int promptmode;
333#ifndef __U_BOOT__
334 FILE *file;
335#endif
336 int (*get) (struct in_str *);
337 int (*peek) (struct in_str *);
338};
339#define b_getch(input) ((input)->get(input))
340#define b_peek(input) ((input)->peek(input))
341
342#ifndef __U_BOOT__
343#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
344
345struct built_in_command {
346 char *cmd; /* name */
347 char *descr; /* description */
348 int (*function) (struct child_prog *); /* function ptr */
349};
350#endif
351
Stefan Roesec23634d2008-08-19 14:57:55 +0200352/* define DEBUG_SHELL for debugging output (obviously ;-)) */
353#if 0
354#define DEBUG_SHELL
355#endif
356
wdenkfe8c2802002-11-03 00:38:21 +0000357/* This should be in utility.c */
358#ifdef DEBUG_SHELL
359#ifndef __U_BOOT__
360static void debug_printf(const char *format, ...)
361{
362 va_list args;
363 va_start(args, format);
364 vfprintf(stderr, format, args);
365 va_end(args);
366}
367#else
Stefan Roesec23634d2008-08-19 14:57:55 +0200368#define debug_printf(fmt,args...) printf (fmt ,##args)
wdenkfe8c2802002-11-03 00:38:21 +0000369#endif
370#else
371static inline void debug_printf(const char *format, ...) { }
372#endif
373#define final_printf debug_printf
374
375#ifdef __U_BOOT__
376static void syntax_err(void) {
377 printf("syntax error\n");
378}
379#else
380static void __syntax(char *file, int line) {
381 error_msg("syntax error %s:%d", file, line);
382}
383#define syntax() __syntax(__FILE__, __LINE__)
384#endif
385
386#ifdef __U_BOOT__
387static void *xmalloc(size_t size);
388static void *xrealloc(void *ptr, size_t size);
389#else
390/* Index of subroutines: */
391/* function prototypes for builtins */
392static int builtin_cd(struct child_prog *child);
393static int builtin_env(struct child_prog *child);
394static int builtin_eval(struct child_prog *child);
395static int builtin_exec(struct child_prog *child);
396static int builtin_exit(struct child_prog *child);
397static int builtin_export(struct child_prog *child);
398static int builtin_fg_bg(struct child_prog *child);
399static int builtin_help(struct child_prog *child);
400static int builtin_jobs(struct child_prog *child);
401static int builtin_pwd(struct child_prog *child);
402static int builtin_read(struct child_prog *child);
403static int builtin_set(struct child_prog *child);
404static int builtin_shift(struct child_prog *child);
405static int builtin_source(struct child_prog *child);
406static int builtin_umask(struct child_prog *child);
407static int builtin_unset(struct child_prog *child);
408static int builtin_not_written(struct child_prog *child);
409#endif
410/* o_string manipulation: */
411static int b_check_space(o_string *o, int len);
412static int b_addchr(o_string *o, int ch);
413static void b_reset(o_string *o);
414static int b_addqchr(o_string *o, int ch, int quote);
wdenk6203e402004-04-18 10:13:26 +0000415#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +0000416static int b_adduint(o_string *o, unsigned int i);
wdenk6203e402004-04-18 10:13:26 +0000417#endif
wdenkfe8c2802002-11-03 00:38:21 +0000418/* in_str manipulations: */
419static int static_get(struct in_str *i);
420static int static_peek(struct in_str *i);
421static int file_get(struct in_str *i);
422static int file_peek(struct in_str *i);
423#ifndef __U_BOOT__
424static void setup_file_in_str(struct in_str *i, FILE *f);
425#else
426static void setup_file_in_str(struct in_str *i);
427#endif
428static void setup_string_in_str(struct in_str *i, const char *s);
429#ifndef __U_BOOT__
430/* close_me manipulations: */
431static void mark_open(int fd);
432static void mark_closed(int fd);
wdenke7f34c62003-01-11 09:48:40 +0000433static void close_all(void);
wdenkfe8c2802002-11-03 00:38:21 +0000434#endif
435/* "run" the final data structures: */
436static char *indenter(int i);
437static int free_pipe_list(struct pipe *head, int indent);
438static int free_pipe(struct pipe *pi, int indent);
439/* really run the final data structures: */
440#ifndef __U_BOOT__
441static int setup_redirects(struct child_prog *prog, int squirrel[]);
442#endif
443static int run_list_real(struct pipe *pi);
444#ifndef __U_BOOT__
445static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
446#endif
447static int run_pipe_real(struct pipe *pi);
448/* extended glob support: */
449#ifndef __U_BOOT__
450static int globhack(const char *src, int flags, glob_t *pglob);
451static int glob_needed(const char *s);
452static int xglob(o_string *dest, int flags, glob_t *pglob);
453#endif
454/* variable assignment: */
455static int is_assignment(const char *s);
456/* data structure manipulation: */
457#ifndef __U_BOOT__
458static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
459#endif
460static void initialize_context(struct p_context *ctx);
461static int done_word(o_string *dest, struct p_context *ctx);
462static int done_command(struct p_context *ctx);
463static int done_pipe(struct p_context *ctx, pipe_style type);
464/* primary string parsing: */
465#ifndef __U_BOOT__
466static int redirect_dup_num(struct in_str *input);
467static int redirect_opt_num(o_string *o);
468static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
469static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
470#endif
471static char *lookup_param(char *src);
Stephen Warren60c38c92014-03-01 22:16:10 -0700472static char *make_string(char **inp, int *nonnull);
wdenkfe8c2802002-11-03 00:38:21 +0000473static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
474#ifndef __U_BOOT__
475static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
476#endif
477static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
478/* setup: */
479static int parse_stream_outer(struct in_str *inp, int flag);
480#ifndef __U_BOOT__
481static int parse_string_outer(const char *s, int flag);
482static int parse_file_outer(FILE *f);
483#endif
484#ifndef __U_BOOT__
485/* job management: */
486static int checkjobs(struct pipe* fg_pipe);
487static void insert_bg_job(struct pipe *pi);
488static void remove_bg_job(struct pipe *pi);
489#endif
490/* local variable support */
491static char **make_list_in(char **inp, char *name);
492static char *insert_var_value(char *inp);
Joe Hershberger38de0b62012-08-17 10:26:30 +0000493static char *insert_var_value_sub(char *inp, int tag_subst);
wdenkfe8c2802002-11-03 00:38:21 +0000494
495#ifndef __U_BOOT__
496/* Table of built-in functions. They can be forked or not, depending on
497 * context: within pipes, they fork. As simple commands, they do not.
498 * When used in non-forking context, they can change global variables
499 * in the parent shell process. If forked, of course they can not.
500 * For example, 'unset foo | whatever' will parse and run, but foo will
501 * still be set at the end. */
502static struct built_in_command bltins[] = {
503 {"bg", "Resume a job in the background", builtin_fg_bg},
504 {"break", "Exit for, while or until loop", builtin_not_written},
505 {"cd", "Change working directory", builtin_cd},
506 {"continue", "Continue for, while or until loop", builtin_not_written},
507 {"env", "Print all environment variables", builtin_env},
508 {"eval", "Construct and run shell command", builtin_eval},
509 {"exec", "Exec command, replacing this shell with the exec'd process",
510 builtin_exec},
511 {"exit", "Exit from shell()", builtin_exit},
512 {"export", "Set environment variable", builtin_export},
513 {"fg", "Bring job into the foreground", builtin_fg_bg},
514 {"jobs", "Lists the active jobs", builtin_jobs},
515 {"pwd", "Print current directory", builtin_pwd},
516 {"read", "Input environment variable", builtin_read},
517 {"return", "Return from a function", builtin_not_written},
518 {"set", "Set/unset shell local variables", builtin_set},
519 {"shift", "Shift positional parameters", builtin_shift},
520 {"trap", "Trap signals", builtin_not_written},
521 {"ulimit","Controls resource limits", builtin_not_written},
522 {"umask","Sets file creation mask", builtin_umask},
523 {"unset", "Unset environment variable", builtin_unset},
524 {".", "Source-in and run commands in a file", builtin_source},
525 {"help", "List shell built-in commands", builtin_help},
526 {NULL, NULL, NULL}
527};
528
529static const char *set_cwd(void)
530{
531 if(cwd==unknown)
532 cwd = NULL; /* xgetcwd(arg) called free(arg) */
533 cwd = xgetcwd((char *)cwd);
534 if (!cwd)
535 cwd = unknown;
536 return cwd;
537}
538
539/* built-in 'eval' handler */
540static int builtin_eval(struct child_prog *child)
541{
542 char *str = NULL;
543 int rcode = EXIT_SUCCESS;
544
545 if (child->argv[1]) {
546 str = make_string(child->argv + 1);
547 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
548 FLAG_PARSE_SEMICOLON);
549 free(str);
550 rcode = last_return_code;
551 }
552 return rcode;
553}
554
555/* built-in 'cd <path>' handler */
556static int builtin_cd(struct child_prog *child)
557{
558 char *newdir;
559 if (child->argv[1] == NULL)
560 newdir = getenv("HOME");
561 else
562 newdir = child->argv[1];
563 if (chdir(newdir)) {
564 printf("cd: %s: %s\n", newdir, strerror(errno));
565 return EXIT_FAILURE;
566 }
567 set_cwd();
568 return EXIT_SUCCESS;
569}
570
571/* built-in 'env' handler */
572static int builtin_env(struct child_prog *dummy)
573{
574 char **e = environ;
575 if (e == NULL) return EXIT_FAILURE;
576 for (; *e; e++) {
577 puts(*e);
578 }
579 return EXIT_SUCCESS;
580}
581
582/* built-in 'exec' handler */
583static int builtin_exec(struct child_prog *child)
584{
585 if (child->argv[1] == NULL)
586 return EXIT_SUCCESS; /* Really? */
587 child->argv++;
588 pseudo_exec(child);
589 /* never returns */
590}
591
592/* built-in 'exit' handler */
593static int builtin_exit(struct child_prog *child)
594{
595 if (child->argv[1] == NULL)
596 exit(last_return_code);
597 exit (atoi(child->argv[1]));
598}
599
600/* built-in 'export VAR=value' handler */
601static int builtin_export(struct child_prog *child)
602{
603 int res = 0;
604 char *name = child->argv[1];
605
606 if (name == NULL) {
607 return (builtin_env(child));
608 }
609
610 name = strdup(name);
611
612 if(name) {
613 char *value = strchr(name, '=');
614
615 if (!value) {
616 char *tmp;
617 /* They are exporting something without an =VALUE */
618
619 value = get_local_var(name);
620 if (value) {
621 size_t ln = strlen(name);
622
623 tmp = realloc(name, ln+strlen(value)+2);
624 if(tmp==NULL)
625 res = -1;
626 else {
627 sprintf(tmp+ln, "=%s", value);
628 name = tmp;
629 }
630 } else {
631 /* bash does not return an error when trying to export
632 * an undefined variable. Do likewise. */
633 res = 1;
634 }
635 }
636 }
637 if (res<0)
638 perror_msg("export");
639 else if(res==0)
640 res = set_local_var(name, 1);
641 else
642 res = 0;
643 free(name);
644 return res;
645}
646
647/* built-in 'fg' and 'bg' handler */
648static int builtin_fg_bg(struct child_prog *child)
649{
650 int i, jobnum;
651 struct pipe *pi=NULL;
652
653 if (!interactive)
654 return EXIT_FAILURE;
655 /* If they gave us no args, assume they want the last backgrounded task */
656 if (!child->argv[1]) {
657 for (pi = job_list; pi; pi = pi->next) {
658 if (pi->jobid == last_jobid) {
659 break;
660 }
661 }
662 if (!pi) {
663 error_msg("%s: no current job", child->argv[0]);
664 return EXIT_FAILURE;
665 }
666 } else {
667 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
668 error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
669 return EXIT_FAILURE;
670 }
671 for (pi = job_list; pi; pi = pi->next) {
672 if (pi->jobid == jobnum) {
673 break;
674 }
675 }
676 if (!pi) {
677 error_msg("%s: %d: no such job", child->argv[0], jobnum);
678 return EXIT_FAILURE;
679 }
680 }
681
682 if (*child->argv[0] == 'f') {
683 /* Put the job into the foreground. */
684 tcsetpgrp(shell_terminal, pi->pgrp);
685 }
686
687 /* Restart the processes in the job */
688 for (i = 0; i < pi->num_progs; i++)
689 pi->progs[i].is_stopped = 0;
690
691 if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) {
692 if (i == ESRCH) {
693 remove_bg_job(pi);
694 } else {
695 perror_msg("kill (SIGCONT)");
696 }
697 }
698
699 pi->stopped_progs = 0;
700 return EXIT_SUCCESS;
701}
702
703/* built-in 'help' handler */
704static int builtin_help(struct child_prog *dummy)
705{
706 struct built_in_command *x;
707
708 printf("\nBuilt-in commands:\n");
709 printf("-------------------\n");
710 for (x = bltins; x->cmd; x++) {
711 if (x->descr==NULL)
712 continue;
713 printf("%s\t%s\n", x->cmd, x->descr);
714 }
715 printf("\n\n");
716 return EXIT_SUCCESS;
717}
718
719/* built-in 'jobs' handler */
720static int builtin_jobs(struct child_prog *child)
721{
722 struct pipe *job;
723 char *status_string;
724
725 for (job = job_list; job; job = job->next) {
726 if (job->running_progs == job->stopped_progs)
727 status_string = "Stopped";
728 else
729 status_string = "Running";
730
731 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
732 }
733 return EXIT_SUCCESS;
734}
735
736
737/* built-in 'pwd' handler */
738static int builtin_pwd(struct child_prog *dummy)
739{
740 puts(set_cwd());
741 return EXIT_SUCCESS;
742}
743
744/* built-in 'read VAR' handler */
745static int builtin_read(struct child_prog *child)
746{
747 int res;
748
749 if (child->argv[1]) {
750 char string[BUFSIZ];
751 char *var = 0;
752
753 string[0] = 0; /* In case stdin has only EOF */
754 /* read string */
755 fgets(string, sizeof(string), stdin);
756 chomp(string);
757 var = malloc(strlen(child->argv[1])+strlen(string)+2);
758 if(var) {
759 sprintf(var, "%s=%s", child->argv[1], string);
760 res = set_local_var(var, 0);
761 } else
762 res = -1;
763 if (res)
764 fprintf(stderr, "read: %m\n");
765 free(var); /* So not move up to avoid breaking errno */
766 return res;
767 } else {
768 do res=getchar(); while(res!='\n' && res!=EOF);
769 return 0;
770 }
771}
772
773/* built-in 'set VAR=value' handler */
774static int builtin_set(struct child_prog *child)
775{
776 char *temp = child->argv[1];
777 struct variables *e;
778
779 if (temp == NULL)
780 for(e = top_vars; e; e=e->next)
781 printf("%s=%s\n", e->name, e->value);
782 else
783 set_local_var(temp, 0);
784
785 return EXIT_SUCCESS;
786}
787
788
789/* Built-in 'shift' handler */
790static int builtin_shift(struct child_prog *child)
791{
792 int n=1;
793 if (child->argv[1]) {
794 n=atoi(child->argv[1]);
795 }
796 if (n>=0 && n<global_argc) {
797 /* XXX This probably breaks $0 */
798 global_argc -= n;
799 global_argv += n;
800 return EXIT_SUCCESS;
801 } else {
802 return EXIT_FAILURE;
803 }
804}
805
806/* Built-in '.' handler (read-in and execute commands from file) */
807static int builtin_source(struct child_prog *child)
808{
809 FILE *input;
810 int status;
811
812 if (child->argv[1] == NULL)
813 return EXIT_FAILURE;
814
815 /* XXX search through $PATH is missing */
816 input = fopen(child->argv[1], "r");
817 if (!input) {
818 error_msg("Couldn't open file '%s'", child->argv[1]);
819 return EXIT_FAILURE;
820 }
821
822 /* Now run the file */
823 /* XXX argv and argc are broken; need to save old global_argv
824 * (pointer only is OK!) on this stack frame,
825 * set global_argv=child->argv+1, recurse, and restore. */
826 mark_open(fileno(input));
827 status = parse_file_outer(input);
828 mark_closed(fileno(input));
829 fclose(input);
830 return (status);
831}
832
833static int builtin_umask(struct child_prog *child)
834{
835 mode_t new_umask;
836 const char *arg = child->argv[1];
837 char *end;
838 if (arg) {
839 new_umask=strtoul(arg, &end, 8);
840 if (*end!='\0' || end == arg) {
841 return EXIT_FAILURE;
842 }
843 } else {
844 printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
845 }
846 umask(new_umask);
847 return EXIT_SUCCESS;
848}
849
850/* built-in 'unset VAR' handler */
851static int builtin_unset(struct child_prog *child)
852{
853 /* bash returned already true */
854 unset_local_var(child->argv[1]);
855 return EXIT_SUCCESS;
856}
857
858static int builtin_not_written(struct child_prog *child)
859{
860 printf("builtin_%s not written\n",child->argv[0]);
861 return EXIT_FAILURE;
862}
863#endif
864
865static int b_check_space(o_string *o, int len)
866{
867 /* It would be easy to drop a more restrictive policy
868 * in here, such as setting a maximum string length */
869 if (o->length + len > o->maxlen) {
870 char *old_data = o->data;
871 /* assert (data == NULL || o->maxlen != 0); */
872 o->maxlen += max(2*len, B_CHUNK);
873 o->data = realloc(o->data, 1 + o->maxlen);
874 if (o->data == NULL) {
875 free(old_data);
876 }
877 }
878 return o->data == NULL;
879}
880
881static int b_addchr(o_string *o, int ch)
882{
883 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
884 if (b_check_space(o, 1)) return B_NOSPAC;
885 o->data[o->length] = ch;
886 o->length++;
887 o->data[o->length] = '\0';
888 return 0;
889}
890
891static void b_reset(o_string *o)
892{
893 o->length = 0;
894 o->nonnull = 0;
895 if (o->data != NULL) *o->data = '\0';
896}
897
898static void b_free(o_string *o)
899{
900 b_reset(o);
wdenke7f34c62003-01-11 09:48:40 +0000901 free(o->data);
wdenkfe8c2802002-11-03 00:38:21 +0000902 o->data = NULL;
903 o->maxlen = 0;
904}
905
906/* My analysis of quoting semantics tells me that state information
907 * is associated with a destination, not a source.
908 */
909static int b_addqchr(o_string *o, int ch, int quote)
910{
911 if (quote && strchr("*?[\\",ch)) {
912 int rc;
913 rc = b_addchr(o, '\\');
914 if (rc) return rc;
915 }
916 return b_addchr(o, ch);
917}
918
wdenk6203e402004-04-18 10:13:26 +0000919#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +0000920static int b_adduint(o_string *o, unsigned int i)
921{
922 int r;
923 char *p = simple_itoa(i);
924 /* no escape checking necessary */
925 do r=b_addchr(o, *p++); while (r==0 && *p);
926 return r;
927}
wdenk6203e402004-04-18 10:13:26 +0000928#endif
wdenkfe8c2802002-11-03 00:38:21 +0000929
930static int static_get(struct in_str *i)
931{
Wolfgang Denkdc770c72008-07-14 15:19:07 +0200932 int ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +0000933 if (ch=='\0') return EOF;
934 return ch;
935}
936
937static int static_peek(struct in_str *i)
938{
939 return *i->p;
940}
941
942#ifndef __U_BOOT__
943static inline void cmdedit_set_initial_prompt(void)
944{
wdenke7f34c62003-01-11 09:48:40 +0000945#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
wdenkfe8c2802002-11-03 00:38:21 +0000946 PS1 = NULL;
947#else
948 PS1 = getenv("PS1");
949 if(PS1==0)
950 PS1 = "\\w \\$ ";
951#endif
952}
953
954static inline void setup_prompt_string(int promptmode, char **prompt_str)
955{
956 debug_printf("setup_prompt_string %d ",promptmode);
wdenke7f34c62003-01-11 09:48:40 +0000957#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
wdenkfe8c2802002-11-03 00:38:21 +0000958 /* Set up the prompt */
959 if (promptmode == 1) {
wdenke7f34c62003-01-11 09:48:40 +0000960 free(PS1);
wdenkfe8c2802002-11-03 00:38:21 +0000961 PS1=xmalloc(strlen(cwd)+4);
962 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
963 *prompt_str = PS1;
964 } else {
965 *prompt_str = PS2;
966 }
967#else
968 *prompt_str = (promptmode==1)? PS1 : PS2;
969#endif
970 debug_printf("result %s\n",*prompt_str);
971}
972#endif
973
974static void get_user_input(struct in_str *i)
975{
976#ifndef __U_BOOT__
977 char *prompt_str;
978 static char the_command[BUFSIZ];
979
980 setup_prompt_string(i->promptmode, &prompt_str);
wdenke7f34c62003-01-11 09:48:40 +0000981#ifdef CONFIG_FEATURE_COMMAND_EDITING
wdenkfe8c2802002-11-03 00:38:21 +0000982 /*
983 ** enable command line editing only while a command line
984 ** is actually being read; otherwise, we'll end up bequeathing
985 ** atexit() handlers and other unwanted stuff to our
986 ** child processes (rob@sysgo.de)
987 */
988 cmdedit_read_input(prompt_str, the_command);
989#else
990 fputs(prompt_str, stdout);
991 fflush(stdout);
992 the_command[0]=fgetc(i->file);
993 the_command[1]='\0';
994#endif
995 fflush(stdout);
996 i->p = the_command;
997#else
wdenkfe8c2802002-11-03 00:38:21 +0000998 int n;
Kristian Otnes2a262cd2014-04-25 15:35:43 +0200999 static char the_command[CONFIG_SYS_CBSIZE + 1];
wdenkfe8c2802002-11-03 00:38:21 +00001000
Wolfgang Denk2b7976a2005-08-12 23:34:51 +02001001#ifdef CONFIG_BOOT_RETRY_TIME
Mike Frysinger6d1f6982010-10-20 03:41:17 -04001002# ifndef CONFIG_RESET_TO_RETRY
Wolfgang Denk2b7976a2005-08-12 23:34:51 +02001003# error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
1004# endif
1005 reset_cmd_timeout();
1006#endif
wdenkfe8c2802002-11-03 00:38:21 +00001007 i->__promptme = 1;
1008 if (i->promptmode == 1) {
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02001009 n = readline(CONFIG_SYS_PROMPT);
wdenkfe8c2802002-11-03 00:38:21 +00001010 } else {
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02001011 n = readline(CONFIG_SYS_PROMPT_HUSH_PS2);
wdenkfe8c2802002-11-03 00:38:21 +00001012 }
Wolfgang Denk2b7976a2005-08-12 23:34:51 +02001013#ifdef CONFIG_BOOT_RETRY_TIME
1014 if (n == -2) {
1015 puts("\nTimeout waiting for command\n");
1016# ifdef CONFIG_RESET_TO_RETRY
1017 do_reset(NULL, 0, 0, NULL);
1018# else
1019# error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
1020# endif
1021 }
1022#endif
wdenkfe8c2802002-11-03 00:38:21 +00001023 if (n == -1 ) {
1024 flag_repeat = 0;
1025 i->__promptme = 0;
1026 }
1027 n = strlen(console_buffer);
1028 console_buffer[n] = '\n';
1029 console_buffer[n+1]= '\0';
1030 if (had_ctrlc()) flag_repeat = 0;
1031 clear_ctrlc();
1032 do_repeat = 0;
1033 if (i->promptmode == 1) {
1034 if (console_buffer[0] == '\n'&& flag_repeat == 0) {
1035 strcpy(the_command,console_buffer);
1036 }
1037 else {
1038 if (console_buffer[0] != '\n') {
1039 strcpy(the_command,console_buffer);
1040 flag_repeat = 1;
1041 }
1042 else {
1043 do_repeat = 1;
1044 }
1045 }
1046 i->p = the_command;
1047 }
1048 else {
wdenk57b2d802003-06-27 21:31:46 +00001049 if (console_buffer[0] != '\n') {
1050 if (strlen(the_command) + strlen(console_buffer)
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02001051 < CONFIG_SYS_CBSIZE) {
wdenk57b2d802003-06-27 21:31:46 +00001052 n = strlen(the_command);
1053 the_command[n-1] = ' ';
1054 strcpy(&the_command[n],console_buffer);
wdenkfe8c2802002-11-03 00:38:21 +00001055 }
1056 else {
1057 the_command[0] = '\n';
1058 the_command[1] = '\0';
1059 flag_repeat = 0;
1060 }
1061 }
1062 if (i->__promptme == 0) {
1063 the_command[0] = '\n';
1064 the_command[1] = '\0';
1065 }
1066 i->p = console_buffer;
1067 }
1068#endif
1069}
1070
1071/* This is the magic location that prints prompts
1072 * and gets data back from the user */
1073static int file_get(struct in_str *i)
1074{
1075 int ch;
1076
1077 ch = 0;
1078 /* If there is data waiting, eat it up */
1079 if (i->p && *i->p) {
Wolfgang Denkdc770c72008-07-14 15:19:07 +02001080 ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +00001081 } else {
1082 /* need to double check i->file because we might be doing something
1083 * more complicated by now, like sourcing or substituting. */
1084#ifndef __U_BOOT__
1085 if (i->__promptme && interactive && i->file == stdin) {
1086 while(! i->p || (interactive && strlen(i->p)==0) ) {
1087#else
1088 while(! i->p || strlen(i->p)==0 ) {
1089#endif
1090 get_user_input(i);
1091 }
1092 i->promptmode=2;
1093#ifndef __U_BOOT__
1094 i->__promptme = 0;
1095#endif
1096 if (i->p && *i->p) {
Wolfgang Denkdc770c72008-07-14 15:19:07 +02001097 ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +00001098 }
1099#ifndef __U_BOOT__
1100 } else {
1101 ch = fgetc(i->file);
1102 }
1103
1104#endif
1105 debug_printf("b_getch: got a %d\n", ch);
1106 }
1107#ifndef __U_BOOT__
1108 if (ch == '\n') i->__promptme=1;
1109#endif
1110 return ch;
1111}
1112
1113/* All the callers guarantee this routine will never be
1114 * used right after a newline, so prompting is not needed.
1115 */
1116static int file_peek(struct in_str *i)
1117{
1118#ifndef __U_BOOT__
1119 if (i->p && *i->p) {
1120#endif
1121 return *i->p;
1122#ifndef __U_BOOT__
1123 } else {
1124 i->peek_buf[0] = fgetc(i->file);
1125 i->peek_buf[1] = '\0';
1126 i->p = i->peek_buf;
1127 debug_printf("b_peek: got a %d\n", *i->p);
1128 return *i->p;
1129 }
1130#endif
1131}
1132
1133#ifndef __U_BOOT__
1134static void setup_file_in_str(struct in_str *i, FILE *f)
1135#else
1136static void setup_file_in_str(struct in_str *i)
1137#endif
1138{
1139 i->peek = file_peek;
1140 i->get = file_get;
1141 i->__promptme=1;
1142 i->promptmode=1;
1143#ifndef __U_BOOT__
1144 i->file = f;
1145#endif
1146 i->p = NULL;
1147}
1148
1149static void setup_string_in_str(struct in_str *i, const char *s)
1150{
1151 i->peek = static_peek;
1152 i->get = static_get;
1153 i->__promptme=1;
1154 i->promptmode=1;
1155 i->p = s;
1156}
1157
1158#ifndef __U_BOOT__
1159static void mark_open(int fd)
1160{
1161 struct close_me *new = xmalloc(sizeof(struct close_me));
1162 new->fd = fd;
1163 new->next = close_me_head;
1164 close_me_head = new;
1165}
1166
1167static void mark_closed(int fd)
1168{
1169 struct close_me *tmp;
1170 if (close_me_head == NULL || close_me_head->fd != fd)
1171 error_msg_and_die("corrupt close_me");
1172 tmp = close_me_head;
1173 close_me_head = close_me_head->next;
1174 free(tmp);
1175}
1176
wdenke7f34c62003-01-11 09:48:40 +00001177static void close_all(void)
wdenkfe8c2802002-11-03 00:38:21 +00001178{
1179 struct close_me *c;
1180 for (c=close_me_head; c; c=c->next) {
1181 close(c->fd);
1182 }
1183 close_me_head = NULL;
1184}
1185
1186/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1187 * and stderr if they are redirected. */
1188static int setup_redirects(struct child_prog *prog, int squirrel[])
1189{
1190 int openfd, mode;
1191 struct redir_struct *redir;
1192
1193 for (redir=prog->redirects; redir; redir=redir->next) {
1194 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1195 /* something went wrong in the parse. Pretend it didn't happen */
1196 continue;
1197 }
1198 if (redir->dup == -1) {
1199 mode=redir_table[redir->type].mode;
1200 openfd = open(redir->word.gl_pathv[0], mode, 0666);
1201 if (openfd < 0) {
1202 /* this could get lost if stderr has been redirected, but
1203 bash and ash both lose it as well (though zsh doesn't!) */
1204 perror_msg("error opening %s", redir->word.gl_pathv[0]);
1205 return 1;
1206 }
1207 } else {
1208 openfd = redir->dup;
1209 }
1210
1211 if (openfd != redir->fd) {
1212 if (squirrel && redir->fd < 3) {
1213 squirrel[redir->fd] = dup(redir->fd);
1214 }
1215 if (openfd == -3) {
1216 close(openfd);
1217 } else {
1218 dup2(openfd, redir->fd);
1219 if (redir->dup == -1)
1220 close (openfd);
1221 }
1222 }
1223 }
1224 return 0;
1225}
1226
1227static void restore_redirects(int squirrel[])
1228{
1229 int i, fd;
1230 for (i=0; i<3; i++) {
1231 fd = squirrel[i];
1232 if (fd != -1) {
1233 /* No error checking. I sure wouldn't know what
1234 * to do with an error if I found one! */
1235 dup2(fd, i);
1236 close(fd);
1237 }
1238 }
1239}
1240
1241/* never returns */
1242/* XXX no exit() here. If you don't exec, use _exit instead.
1243 * The at_exit handlers apparently confuse the calling process,
1244 * in particular stdin handling. Not sure why? */
1245static void pseudo_exec(struct child_prog *child)
1246{
1247 int i, rcode;
1248 char *p;
1249 struct built_in_command *x;
1250 if (child->argv) {
1251 for (i=0; is_assignment(child->argv[i]); i++) {
1252 debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]);
1253 p = insert_var_value(child->argv[i]);
1254 putenv(strdup(p));
1255 if (p != child->argv[i]) free(p);
1256 }
1257 child->argv+=i; /* XXX this hack isn't so horrible, since we are about
wdenk57b2d802003-06-27 21:31:46 +00001258 to exit, and therefore don't need to keep data
1259 structures consistent for free() use. */
wdenkfe8c2802002-11-03 00:38:21 +00001260 /* If a variable is assigned in a forest, and nobody listens,
1261 * was it ever really set?
1262 */
1263 if (child->argv[0] == NULL) {
1264 _exit(EXIT_SUCCESS);
1265 }
1266
1267 /*
1268 * Check if the command matches any of the builtins.
1269 * Depending on context, this might be redundant. But it's
1270 * easier to waste a few CPU cycles than it is to figure out
1271 * if this is one of those cases.
1272 */
1273 for (x = bltins; x->cmd; x++) {
1274 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1275 debug_printf("builtin exec %s\n", child->argv[0]);
1276 rcode = x->function(child);
1277 fflush(stdout);
1278 _exit(rcode);
1279 }
1280 }
1281
1282 /* Check if the command matches any busybox internal commands
1283 * ("applets") here.
1284 * FIXME: This feature is not 100% safe, since
1285 * BusyBox is not fully reentrant, so we have no guarantee the things
1286 * from the .bss are still zeroed, or that things from .data are still
1287 * at their defaults. We could exec ourself from /proc/self/exe, but I
1288 * really dislike relying on /proc for things. We could exec ourself
1289 * from global_argv[0], but if we are in a chroot, we may not be able
1290 * to find ourself... */
wdenke7f34c62003-01-11 09:48:40 +00001291#ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
wdenkfe8c2802002-11-03 00:38:21 +00001292 {
1293 int argc_l;
1294 char** argv_l=child->argv;
1295 char *name = child->argv[0];
1296
wdenke7f34c62003-01-11 09:48:40 +00001297#ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
wdenkfe8c2802002-11-03 00:38:21 +00001298 /* Following discussions from November 2000 on the busybox mailing
1299 * list, the default configuration, (without
1300 * get_last_path_component()) lets the user force use of an
1301 * external command by specifying the full (with slashes) filename.
wdenke7f34c62003-01-11 09:48:40 +00001302 * If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets
wdenkfe8c2802002-11-03 00:38:21 +00001303 * _aways_ override external commands, so if you want to run
1304 * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
1305 * filesystem and is _not_ busybox. Some systems may want this,
1306 * most do not. */
1307 name = get_last_path_component(name);
1308#endif
1309 /* Count argc for use in a second... */
1310 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
1311 optind = 1;
1312 debug_printf("running applet %s\n", name);
1313 run_applet_by_name(name, argc_l, child->argv);
1314 }
1315#endif
1316 debug_printf("exec of %s\n",child->argv[0]);
1317 execvp(child->argv[0],child->argv);
1318 perror_msg("couldn't exec: %s",child->argv[0]);
1319 _exit(1);
1320 } else if (child->group) {
1321 debug_printf("runtime nesting to group\n");
1322 interactive=0; /* crucial!!!! */
1323 rcode = run_list_real(child->group);
1324 /* OK to leak memory by not calling free_pipe_list,
1325 * since this process is about to exit */
1326 _exit(rcode);
1327 } else {
1328 /* Can happen. See what bash does with ">foo" by itself. */
1329 debug_printf("trying to pseudo_exec null command\n");
1330 _exit(EXIT_SUCCESS);
1331 }
1332}
1333
1334static void insert_bg_job(struct pipe *pi)
1335{
1336 struct pipe *thejob;
1337
1338 /* Linear search for the ID of the job to use */
1339 pi->jobid = 1;
1340 for (thejob = job_list; thejob; thejob = thejob->next)
1341 if (thejob->jobid >= pi->jobid)
1342 pi->jobid = thejob->jobid + 1;
1343
1344 /* add thejob to the list of running jobs */
1345 if (!job_list) {
1346 thejob = job_list = xmalloc(sizeof(*thejob));
1347 } else {
1348 for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */;
1349 thejob->next = xmalloc(sizeof(*thejob));
1350 thejob = thejob->next;
1351 }
1352
1353 /* physically copy the struct job */
1354 memcpy(thejob, pi, sizeof(struct pipe));
1355 thejob->next = NULL;
1356 thejob->running_progs = thejob->num_progs;
1357 thejob->stopped_progs = 0;
1358 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1359
1360 /*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */
1361 {
1362 char *bar=thejob->text;
1363 char **foo=pi->progs[0].argv;
1364 while(foo && *foo) {
1365 bar += sprintf(bar, "%s ", *foo++);
1366 }
1367 }
1368
1369 /* we don't wait for background thejobs to return -- append it
1370 to the list of backgrounded thejobs and leave it alone */
1371 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1372 last_bg_pid = thejob->progs[0].pid;
1373 last_jobid = thejob->jobid;
1374}
1375
1376/* remove a backgrounded job */
1377static void remove_bg_job(struct pipe *pi)
1378{
1379 struct pipe *prev_pipe;
1380
1381 if (pi == job_list) {
1382 job_list = pi->next;
1383 } else {
1384 prev_pipe = job_list;
1385 while (prev_pipe->next != pi)
1386 prev_pipe = prev_pipe->next;
1387 prev_pipe->next = pi->next;
1388 }
1389 if (job_list)
1390 last_jobid = job_list->jobid;
1391 else
1392 last_jobid = 0;
1393
1394 pi->stopped_progs = 0;
1395 free_pipe(pi, 0);
1396 free(pi);
1397}
1398
1399/* Checks to see if any processes have exited -- if they
1400 have, figure out why and see if a job has completed */
1401static int checkjobs(struct pipe* fg_pipe)
1402{
1403 int attributes;
1404 int status;
1405 int prognum = 0;
1406 struct pipe *pi;
1407 pid_t childpid;
1408
1409 attributes = WUNTRACED;
1410 if (fg_pipe==NULL) {
1411 attributes |= WNOHANG;
1412 }
1413
1414 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1415 if (fg_pipe) {
1416 int i, rcode = 0;
1417 for (i=0; i < fg_pipe->num_progs; i++) {
1418 if (fg_pipe->progs[i].pid == childpid) {
1419 if (i==fg_pipe->num_progs-1)
1420 rcode=WEXITSTATUS(status);
1421 (fg_pipe->num_progs)--;
1422 return(rcode);
1423 }
1424 }
1425 }
1426
1427 for (pi = job_list; pi; pi = pi->next) {
1428 prognum = 0;
1429 while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) {
1430 prognum++;
1431 }
1432 if (prognum < pi->num_progs)
1433 break;
1434 }
1435
1436 if(pi==NULL) {
1437 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1438 continue;
1439 }
1440
1441 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1442 /* child exited */
1443 pi->running_progs--;
1444 pi->progs[prognum].pid = 0;
1445
1446 if (!pi->running_progs) {
1447 printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
1448 remove_bg_job(pi);
1449 }
1450 } else {
1451 /* child stopped */
1452 pi->stopped_progs++;
1453 pi->progs[prognum].is_stopped = 1;
1454
1455#if 0
1456 /* Printing this stuff is a pain, since it tends to
1457 * overwrite the prompt an inconveinient moments. So
1458 * don't do that. */
1459 if (pi->stopped_progs == pi->num_progs) {
1460 printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text);
1461 }
1462#endif
1463 }
1464 }
1465
1466 if (childpid == -1 && errno != ECHILD)
1467 perror_msg("waitpid");
1468
1469 /* move the shell to the foreground */
1470 /*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */
1471 /* perror_msg("tcsetpgrp-2"); */
1472 return -1;
1473}
1474
1475/* Figure out our controlling tty, checking in order stderr,
1476 * stdin, and stdout. If check_pgrp is set, also check that
1477 * we belong to the foreground process group associated with
1478 * that tty. The value of shell_terminal is needed in order to call
1479 * tcsetpgrp(shell_terminal, ...); */
1480void controlling_tty(int check_pgrp)
1481{
1482 pid_t curpgrp;
1483
1484 if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0
1485 && (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0
1486 && (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0)
1487 goto shell_terminal_error;
1488
1489 if (check_pgrp && curpgrp != getpgid(0))
1490 goto shell_terminal_error;
1491
1492 return;
1493
1494shell_terminal_error:
1495 shell_terminal = -1;
1496 return;
1497}
1498#endif
1499
1500/* run_pipe_real() starts all the jobs, but doesn't wait for anything
1501 * to finish. See checkjobs().
1502 *
1503 * return code is normally -1, when the caller has to wait for children
1504 * to finish to determine the exit status of the pipe. If the pipe
1505 * is a simple builtin command, however, the action is done by the
1506 * time run_pipe_real returns, and the exit code is provided as the
1507 * return value.
1508 *
1509 * The input of the pipe is always stdin, the output is always
1510 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1511 * because it tries to avoid running the command substitution in
1512 * subshell, when that is in fact necessary. The subshell process
1513 * now has its stdout directed to the input of the appropriate pipe,
1514 * so this routine is noticeably simpler.
1515 */
1516static int run_pipe_real(struct pipe *pi)
1517{
1518 int i;
1519#ifndef __U_BOOT__
1520 int nextin, nextout;
1521 int pipefds[2]; /* pipefds[0] is for reading */
1522 struct child_prog *child;
1523 struct built_in_command *x;
1524 char *p;
wdenke7f34c62003-01-11 09:48:40 +00001525# if __GNUC__
1526 /* Avoid longjmp clobbering */
1527 (void) &i;
1528 (void) &nextin;
1529 (void) &nextout;
1530 (void) &child;
1531# endif
wdenkfe8c2802002-11-03 00:38:21 +00001532#else
1533 int nextin;
1534 int flag = do_repeat ? CMD_FLAG_REPEAT : 0;
1535 struct child_prog *child;
wdenkfe8c2802002-11-03 00:38:21 +00001536 char *p;
wdenke7f34c62003-01-11 09:48:40 +00001537# if __GNUC__
1538 /* Avoid longjmp clobbering */
1539 (void) &i;
1540 (void) &nextin;
1541 (void) &child;
1542# endif
1543#endif /* __U_BOOT__ */
wdenkfe8c2802002-11-03 00:38:21 +00001544
1545 nextin = 0;
1546#ifndef __U_BOOT__
1547 pi->pgrp = -1;
1548#endif
1549
1550 /* Check if this is a simple builtin (not part of a pipe).
1551 * Builtins within pipes have to fork anyway, and are handled in
1552 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1553 */
1554 if (pi->num_progs == 1) child = & (pi->progs[0]);
1555#ifndef __U_BOOT__
1556 if (pi->num_progs == 1 && child->group && child->subshell == 0) {
1557 int squirrel[] = {-1, -1, -1};
1558 int rcode;
1559 debug_printf("non-subshell grouping\n");
1560 setup_redirects(child, squirrel);
1561 /* XXX could we merge code with following builtin case,
1562 * by creating a pseudo builtin that calls run_list_real? */
1563 rcode = run_list_real(child->group);
1564 restore_redirects(squirrel);
1565#else
1566 if (pi->num_progs == 1 && child->group) {
1567 int rcode;
1568 debug_printf("non-subshell grouping\n");
1569 rcode = run_list_real(child->group);
1570#endif
1571 return rcode;
1572 } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1573 for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
1574 if (i!=0 && child->argv[i]==NULL) {
1575 /* assignments, but no command: set the local environment */
1576 for (i=0; child->argv[i]!=NULL; i++) {
1577
1578 /* Ok, this case is tricky. We have to decide if this is a
1579 * local variable, or an already exported variable. If it is
1580 * already exported, we have to export the new value. If it is
1581 * not exported, we need only set this as a local variable.
1582 * This junk is all to decide whether or not to export this
1583 * variable. */
1584 int export_me=0;
1585 char *name, *value;
1586 name = xstrdup(child->argv[i]);
1587 debug_printf("Local environment set: %s\n", name);
1588 value = strchr(name, '=');
1589 if (value)
1590 *value=0;
1591#ifndef __U_BOOT__
1592 if ( get_local_var(name)) {
1593 export_me=1;
1594 }
1595#endif
1596 free(name);
1597 p = insert_var_value(child->argv[i]);
1598 set_local_var(p, export_me);
1599 if (p != child->argv[i]) free(p);
1600 }
1601 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1602 }
1603 for (i = 0; is_assignment(child->argv[i]); i++) {
1604 p = insert_var_value(child->argv[i]);
1605#ifndef __U_BOOT__
1606 putenv(strdup(p));
1607#else
1608 set_local_var(p, 0);
1609#endif
1610 if (p != child->argv[i]) {
1611 child->sp--;
1612 free(p);
1613 }
1614 }
1615 if (child->sp) {
1616 char * str = NULL;
1617
Stephen Warren60c38c92014-03-01 22:16:10 -07001618 str = make_string(child->argv + i,
1619 child->argv_nonnull + i);
wdenkfe8c2802002-11-03 00:38:21 +00001620 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1621 free(str);
1622 return last_return_code;
1623 }
1624#ifndef __U_BOOT__
1625 for (x = bltins; x->cmd; x++) {
1626 if (strcmp(child->argv[i], x->cmd) == 0 ) {
1627 int squirrel[] = {-1, -1, -1};
1628 int rcode;
1629 if (x->function == builtin_exec && child->argv[i+1]==NULL) {
1630 debug_printf("magic exec\n");
1631 setup_redirects(child,NULL);
1632 return EXIT_SUCCESS;
1633 }
1634 debug_printf("builtin inline %s\n", child->argv[0]);
1635 /* XXX setup_redirects acts on file descriptors, not FILEs.
1636 * This is perfect for work that comes after exec().
1637 * Is it really safe for inline use? Experimentally,
1638 * things seem to work with glibc. */
1639 setup_redirects(child, squirrel);
Simon Glasse79731e2011-12-06 19:47:53 +00001640
1641 child->argv += i; /* XXX horrible hack */
1642 rcode = x->function(child);
1643 /* XXX restore hack so free() can work right */
1644 child->argv -= i;
1645 restore_redirects(squirrel);
1646 }
1647 return rcode;
1648 }
wdenkfe8c2802002-11-03 00:38:21 +00001649#else
Simon Glass1727b942012-02-14 19:59:25 +00001650 /* check ";", because ,example , argv consist from
1651 * "help;flinfo" must not execute
1652 */
1653 if (strchr(child->argv[i], ';')) {
1654 printf("Unknown command '%s' - try 'help' or use "
1655 "'run' command\n", child->argv[i]);
1656 return -1;
wdenkfe8c2802002-11-03 00:38:21 +00001657 }
Simon Glass1727b942012-02-14 19:59:25 +00001658 /* Process the command */
1659 return cmd_process(flag, child->argc, child->argv,
Richard Genoud94ff0672012-12-03 06:28:28 +00001660 &flag_repeat, NULL);
Simon Glass1727b942012-02-14 19:59:25 +00001661#endif
wdenkfe8c2802002-11-03 00:38:21 +00001662 }
Simon Glass1727b942012-02-14 19:59:25 +00001663#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00001664
1665 for (i = 0; i < pi->num_progs; i++) {
1666 child = & (pi->progs[i]);
1667
1668 /* pipes are inserted between pairs of commands */
1669 if ((i + 1) < pi->num_progs) {
1670 if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1671 nextout = pipefds[1];
1672 } else {
1673 nextout=1;
1674 pipefds[0] = -1;
1675 }
1676
1677 /* XXX test for failed fork()? */
1678 if (!(child->pid = fork())) {
1679 /* Set the handling for job control signals back to the default. */
1680 signal(SIGINT, SIG_DFL);
1681 signal(SIGQUIT, SIG_DFL);
1682 signal(SIGTERM, SIG_DFL);
1683 signal(SIGTSTP, SIG_DFL);
1684 signal(SIGTTIN, SIG_DFL);
1685 signal(SIGTTOU, SIG_DFL);
1686 signal(SIGCHLD, SIG_DFL);
1687
1688 close_all();
1689
1690 if (nextin != 0) {
1691 dup2(nextin, 0);
1692 close(nextin);
1693 }
1694 if (nextout != 1) {
1695 dup2(nextout, 1);
1696 close(nextout);
1697 }
1698 if (pipefds[0]!=-1) {
1699 close(pipefds[0]); /* opposite end of our output pipe */
1700 }
1701
1702 /* Like bash, explicit redirects override pipes,
1703 * and the pipe fd is available for dup'ing. */
1704 setup_redirects(child,NULL);
1705
1706 if (interactive && pi->followup!=PIPE_BG) {
1707 /* If we (the child) win the race, put ourselves in the process
1708 * group whose leader is the first process in this pipe. */
1709 if (pi->pgrp < 0) {
1710 pi->pgrp = getpid();
1711 }
1712 if (setpgid(0, pi->pgrp) == 0) {
1713 tcsetpgrp(2, pi->pgrp);
1714 }
1715 }
1716
1717 pseudo_exec(child);
1718 }
1719
1720
1721 /* put our child in the process group whose leader is the
1722 first process in this pipe */
1723 if (pi->pgrp < 0) {
1724 pi->pgrp = child->pid;
1725 }
1726 /* Don't check for errors. The child may be dead already,
1727 * in which case setpgid returns error code EACCES. */
1728 setpgid(child->pid, pi->pgrp);
1729
1730 if (nextin != 0)
1731 close(nextin);
1732 if (nextout != 1)
1733 close(nextout);
1734
1735 /* If there isn't another process, nextin is garbage
1736 but it doesn't matter */
1737 nextin = pipefds[0];
1738 }
1739#endif
1740 return -1;
1741}
1742
1743static int run_list_real(struct pipe *pi)
1744{
1745 char *save_name = NULL;
1746 char **list = NULL;
1747 char **save_list = NULL;
1748 struct pipe *rpipe;
1749 int flag_rep = 0;
1750#ifndef __U_BOOT__
1751 int save_num_progs;
1752#endif
1753 int rcode=0, flag_skip=1;
1754 int flag_restore = 0;
1755 int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
1756 reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
1757 /* check syntax for "for" */
1758 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1759 if ((rpipe->r_mode == RES_IN ||
1760 rpipe->r_mode == RES_FOR) &&
1761 (rpipe->next == NULL)) {
1762 syntax();
1763#ifdef __U_BOOT__
1764 flag_repeat = 0;
1765#endif
1766 return 1;
1767 }
1768 if ((rpipe->r_mode == RES_IN &&
1769 (rpipe->next->r_mode == RES_IN &&
1770 rpipe->next->progs->argv != NULL))||
1771 (rpipe->r_mode == RES_FOR &&
1772 rpipe->next->r_mode != RES_IN)) {
1773 syntax();
1774#ifdef __U_BOOT__
1775 flag_repeat = 0;
1776#endif
1777 return 1;
1778 }
1779 }
1780 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1781 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL ||
1782 pi->r_mode == RES_FOR) {
1783#ifdef __U_BOOT__
1784 /* check Ctrl-C */
1785 ctrlc();
1786 if ((had_ctrlc())) {
1787 return 1;
1788 }
1789#endif
1790 flag_restore = 0;
1791 if (!rpipe) {
1792 flag_rep = 0;
1793 rpipe = pi;
1794 }
1795 }
1796 rmode = pi->r_mode;
1797 debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n", rmode, if_code, next_if_code, skip_more_in_this_rmode);
1798 if (rmode == skip_more_in_this_rmode && flag_skip) {
1799 if (pi->followup == PIPE_SEQ) flag_skip=0;
1800 continue;
1801 }
1802 flag_skip = 1;
1803 skip_more_in_this_rmode = RES_XXXX;
1804 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1805 if (rmode == RES_THEN && if_code) continue;
1806 if (rmode == RES_ELSE && !if_code) continue;
wdenk33591052004-04-12 14:31:43 +00001807 if (rmode == RES_ELIF && !if_code) break;
wdenkfe8c2802002-11-03 00:38:21 +00001808 if (rmode == RES_FOR && pi->num_progs) {
1809 if (!list) {
1810 /* if no variable values after "in" we skip "for" */
1811 if (!pi->next->progs->argv) continue;
1812 /* create list of variable values */
1813 list = make_list_in(pi->next->progs->argv,
1814 pi->progs->argv[0]);
1815 save_list = list;
1816 save_name = pi->progs->argv[0];
1817 pi->progs->argv[0] = NULL;
1818 flag_rep = 1;
1819 }
1820 if (!(*list)) {
1821 free(pi->progs->argv[0]);
1822 free(save_list);
1823 list = NULL;
1824 flag_rep = 0;
1825 pi->progs->argv[0] = save_name;
1826#ifndef __U_BOOT__
1827 pi->progs->glob_result.gl_pathv[0] =
1828 pi->progs->argv[0];
1829#endif
1830 continue;
1831 } else {
1832 /* insert new value from list for variable */
1833 if (pi->progs->argv[0])
1834 free(pi->progs->argv[0]);
1835 pi->progs->argv[0] = *list++;
1836#ifndef __U_BOOT__
1837 pi->progs->glob_result.gl_pathv[0] =
1838 pi->progs->argv[0];
1839#endif
1840 }
1841 }
1842 if (rmode == RES_IN) continue;
1843 if (rmode == RES_DO) {
1844 if (!flag_rep) continue;
1845 }
1846 if ((rmode == RES_DONE)) {
1847 if (flag_rep) {
1848 flag_restore = 1;
1849 } else {
1850 rpipe = NULL;
1851 }
1852 }
1853 if (pi->num_progs == 0) continue;
1854#ifndef __U_BOOT__
1855 save_num_progs = pi->num_progs; /* save number of programs */
1856#endif
1857 rcode = run_pipe_real(pi);
1858 debug_printf("run_pipe_real returned %d\n",rcode);
1859#ifndef __U_BOOT__
1860 if (rcode!=-1) {
1861 /* We only ran a builtin: rcode was set by the return value
1862 * of run_pipe_real(), and we don't need to wait for anything. */
1863 } else if (pi->followup==PIPE_BG) {
1864 /* XXX check bash's behavior with nontrivial pipes */
1865 /* XXX compute jobid */
1866 /* XXX what does bash do with attempts to background builtins? */
1867 insert_bg_job(pi);
1868 rcode = EXIT_SUCCESS;
1869 } else {
1870 if (interactive) {
1871 /* move the new process group into the foreground */
1872 if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY)
1873 perror_msg("tcsetpgrp-3");
1874 rcode = checkjobs(pi);
1875 /* move the shell to the foreground */
1876 if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY)
1877 perror_msg("tcsetpgrp-4");
1878 } else {
1879 rcode = checkjobs(pi);
1880 }
1881 debug_printf("checkjobs returned %d\n",rcode);
1882 }
1883 last_return_code=rcode;
1884#else
wdenk6203e402004-04-18 10:13:26 +00001885 if (rcode < -1) {
1886 last_return_code = -rcode - 2;
1887 return -2; /* exit */
1888 }
wdenkfe8c2802002-11-03 00:38:21 +00001889 last_return_code=(rcode == 0) ? 0 : 1;
1890#endif
1891#ifndef __U_BOOT__
1892 pi->num_progs = save_num_progs; /* restore number of programs */
1893#endif
1894 if ( rmode == RES_IF || rmode == RES_ELIF )
1895 next_if_code=rcode; /* can be overwritten a number of times */
1896 if (rmode == RES_WHILE)
1897 flag_rep = !last_return_code;
1898 if (rmode == RES_UNTIL)
1899 flag_rep = last_return_code;
1900 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1901 (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1902 skip_more_in_this_rmode=rmode;
1903#ifndef __U_BOOT__
1904 checkjobs(NULL);
1905#endif
1906 }
1907 return rcode;
1908}
1909
1910/* broken, of course, but OK for testing */
1911static char *indenter(int i)
1912{
1913 static char blanks[]=" ";
1914 return &blanks[sizeof(blanks)-i-1];
1915}
1916
1917/* return code is the exit status of the pipe */
1918static int free_pipe(struct pipe *pi, int indent)
1919{
1920 char **p;
1921 struct child_prog *child;
1922#ifndef __U_BOOT__
1923 struct redir_struct *r, *rnext;
1924#endif
1925 int a, i, ret_code=0;
1926 char *ind = indenter(indent);
1927
1928#ifndef __U_BOOT__
1929 if (pi->stopped_progs > 0)
1930 return ret_code;
1931 final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1932#endif
1933 for (i=0; i<pi->num_progs; i++) {
1934 child = &pi->progs[i];
1935 final_printf("%s command %d:\n",ind,i);
1936 if (child->argv) {
1937 for (a=0,p=child->argv; *p; a++,p++) {
1938 final_printf("%s argv[%d] = %s\n",ind,a,*p);
1939 }
1940#ifndef __U_BOOT__
1941 globfree(&child->glob_result);
1942#else
Peter Tysercc215a12009-08-05 16:18:44 -05001943 for (a = 0; a < child->argc; a++) {
wdenk57b2d802003-06-27 21:31:46 +00001944 free(child->argv[a]);
1945 }
Stephen Warren60c38c92014-03-01 22:16:10 -07001946 free(child->argv);
1947 free(child->argv_nonnull);
wdenk57b2d802003-06-27 21:31:46 +00001948 child->argc = 0;
wdenkfe8c2802002-11-03 00:38:21 +00001949#endif
1950 child->argv=NULL;
1951 } else if (child->group) {
1952#ifndef __U_BOOT__
1953 final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
1954#endif
1955 ret_code = free_pipe_list(child->group,indent+3);
1956 final_printf("%s end group\n",ind);
1957 } else {
1958 final_printf("%s (nil)\n",ind);
1959 }
1960#ifndef __U_BOOT__
1961 for (r=child->redirects; r; r=rnext) {
1962 final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1963 if (r->dup == -1) {
1964 /* guard against the case >$FOO, where foo is unset or blank */
1965 if (r->word.gl_pathv) {
1966 final_printf(" %s\n", *r->word.gl_pathv);
1967 globfree(&r->word);
1968 }
1969 } else {
1970 final_printf("&%d\n", r->dup);
1971 }
1972 rnext=r->next;
1973 free(r);
1974 }
1975 child->redirects=NULL;
1976#endif
1977 }
1978 free(pi->progs); /* children are an array, they get freed all at once */
1979 pi->progs=NULL;
1980 return ret_code;
1981}
1982
1983static int free_pipe_list(struct pipe *head, int indent)
1984{
1985 int rcode=0; /* if list has no members */
1986 struct pipe *pi, *next;
1987 char *ind = indenter(indent);
1988 for (pi=head; pi; pi=next) {
1989 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1990 rcode = free_pipe(pi, indent);
1991 final_printf("%s pipe followup code %d\n", ind, pi->followup);
1992 next=pi->next;
1993 pi->next=NULL;
1994 free(pi);
1995 }
1996 return rcode;
1997}
1998
1999/* Select which version we will use */
2000static int run_list(struct pipe *pi)
2001{
2002 int rcode=0;
2003#ifndef __U_BOOT__
2004 if (fake_mode==0) {
2005#endif
2006 rcode = run_list_real(pi);
2007#ifndef __U_BOOT__
2008 }
2009#endif
2010 /* free_pipe_list has the side effect of clearing memory
2011 * In the long run that function can be merged with run_list_real,
2012 * but doing that now would hobble the debugging effort. */
2013 free_pipe_list(pi,0);
2014 return rcode;
2015}
2016
2017/* The API for glob is arguably broken. This routine pushes a non-matching
2018 * string into the output structure, removing non-backslashed backslashes.
2019 * If someone can prove me wrong, by performing this function within the
2020 * original glob(3) api, feel free to rewrite this routine into oblivion.
2021 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2022 * XXX broken if the last character is '\\', check that before calling.
2023 */
2024#ifndef __U_BOOT__
2025static int globhack(const char *src, int flags, glob_t *pglob)
2026{
2027 int cnt=0, pathc;
2028 const char *s;
2029 char *dest;
2030 for (cnt=1, s=src; s && *s; s++) {
2031 if (*s == '\\') s++;
2032 cnt++;
2033 }
2034 dest = malloc(cnt);
2035 if (!dest) return GLOB_NOSPACE;
2036 if (!(flags & GLOB_APPEND)) {
2037 pglob->gl_pathv=NULL;
2038 pglob->gl_pathc=0;
2039 pglob->gl_offs=0;
2040 pglob->gl_offs=0;
2041 }
2042 pathc = ++pglob->gl_pathc;
2043 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
2044 if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
2045 pglob->gl_pathv[pathc-1]=dest;
2046 pglob->gl_pathv[pathc]=NULL;
2047 for (s=src; s && *s; s++, dest++) {
2048 if (*s == '\\') s++;
2049 *dest = *s;
2050 }
2051 *dest='\0';
2052 return 0;
2053}
2054
2055/* XXX broken if the last character is '\\', check that before calling */
2056static int glob_needed(const char *s)
2057{
2058 for (; *s; s++) {
2059 if (*s == '\\') s++;
2060 if (strchr("*[?",*s)) return 1;
2061 }
2062 return 0;
2063}
2064
2065#if 0
2066static void globprint(glob_t *pglob)
2067{
2068 int i;
2069 debug_printf("glob_t at %p:\n", pglob);
2070 debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
2071 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
2072 for (i=0; i<pglob->gl_pathc; i++)
2073 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
2074 pglob->gl_pathv[i], pglob->gl_pathv[i]);
2075}
2076#endif
2077
2078static int xglob(o_string *dest, int flags, glob_t *pglob)
2079{
2080 int gr;
2081
wdenk57b2d802003-06-27 21:31:46 +00002082 /* short-circuit for null word */
wdenkfe8c2802002-11-03 00:38:21 +00002083 /* we can code this better when the debug_printf's are gone */
wdenk57b2d802003-06-27 21:31:46 +00002084 if (dest->length == 0) {
2085 if (dest->nonnull) {
2086 /* bash man page calls this an "explicit" null */
2087 gr = globhack(dest->data, flags, pglob);
2088 debug_printf("globhack returned %d\n",gr);
2089 } else {
wdenkfe8c2802002-11-03 00:38:21 +00002090 return 0;
2091 }
wdenk57b2d802003-06-27 21:31:46 +00002092 } else if (glob_needed(dest->data)) {
wdenkfe8c2802002-11-03 00:38:21 +00002093 gr = glob(dest->data, flags, NULL, pglob);
2094 debug_printf("glob returned %d\n",gr);
2095 if (gr == GLOB_NOMATCH) {
2096 /* quote removal, or more accurately, backslash removal */
2097 gr = globhack(dest->data, flags, pglob);
2098 debug_printf("globhack returned %d\n",gr);
2099 }
2100 } else {
2101 gr = globhack(dest->data, flags, pglob);
2102 debug_printf("globhack returned %d\n",gr);
2103 }
2104 if (gr == GLOB_NOSPACE)
2105 error_msg_and_die("out of memory during glob");
2106 if (gr != 0) { /* GLOB_ABORTED ? */
2107 error_msg("glob(3) error %d",gr);
2108 }
2109 /* globprint(glob_target); */
2110 return gr;
2111}
2112#endif
2113
wdenk6203e402004-04-18 10:13:26 +00002114#ifdef __U_BOOT__
2115static char *get_dollar_var(char ch);
2116#endif
2117
wdenkfe8c2802002-11-03 00:38:21 +00002118/* This is used to get/check local shell variables */
Holger Brunck50950222011-04-08 02:47:42 +00002119char *get_local_var(const char *s)
wdenkfe8c2802002-11-03 00:38:21 +00002120{
2121 struct variables *cur;
2122
2123 if (!s)
2124 return NULL;
wdenk6203e402004-04-18 10:13:26 +00002125
2126#ifdef __U_BOOT__
2127 if (*s == '$')
2128 return get_dollar_var(s[1]);
2129#endif
2130
wdenkfe8c2802002-11-03 00:38:21 +00002131 for (cur = top_vars; cur; cur=cur->next)
2132 if(strcmp(cur->name, s)==0)
2133 return cur->value;
2134 return NULL;
2135}
2136
2137/* This is used to set local shell variables
2138 flg_export==0 if only local (not exporting) variable
2139 flg_export==1 if "new" exporting environ
2140 flg_export>1 if current startup environ (not call putenv()) */
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002141int set_local_var(const char *s, int flg_export)
wdenkfe8c2802002-11-03 00:38:21 +00002142{
2143 char *name, *value;
2144 int result=0;
2145 struct variables *cur;
2146
wdenk6203e402004-04-18 10:13:26 +00002147#ifdef __U_BOOT__
2148 /* might be possible! */
2149 if (!isalpha(*s))
2150 return -1;
2151#endif
2152
wdenkfe8c2802002-11-03 00:38:21 +00002153 name=strdup(s);
2154
2155#ifdef __U_BOOT__
2156 if (getenv(name) != NULL) {
2157 printf ("ERROR: "
wdenk2ebee312004-02-23 19:30:57 +00002158 "There is a global environment variable with the same name.\n");
wdenk6203e402004-04-18 10:13:26 +00002159 free(name);
wdenkfe8c2802002-11-03 00:38:21 +00002160 return -1;
2161 }
2162#endif
2163 /* Assume when we enter this function that we are already in
2164 * NAME=VALUE format. So the first order of business is to
2165 * split 's' on the '=' into 'name' and 'value' */
2166 value = strchr(name, '=');
Kim Phillipsb052b602012-10-29 13:34:32 +00002167 if (value == NULL && ++value == NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002168 free(name);
2169 return -1;
2170 }
2171 *value++ = 0;
2172
2173 for(cur = top_vars; cur; cur = cur->next) {
2174 if(strcmp(cur->name, name)==0)
2175 break;
2176 }
2177
2178 if(cur) {
2179 if(strcmp(cur->value, value)==0) {
2180 if(flg_export>0 && cur->flg_export==0)
2181 cur->flg_export=flg_export;
2182 else
2183 result++;
2184 } else {
2185 if(cur->flg_read_only) {
2186 error_msg("%s: readonly variable", name);
2187 result = -1;
2188 } else {
2189 if(flg_export>0 || cur->flg_export>1)
2190 cur->flg_export=1;
2191 free(cur->value);
2192
2193 cur->value = strdup(value);
2194 }
2195 }
2196 } else {
2197 cur = malloc(sizeof(struct variables));
2198 if(!cur) {
2199 result = -1;
2200 } else {
2201 cur->name = strdup(name);
Kim Phillipsb052b602012-10-29 13:34:32 +00002202 if (cur->name == NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002203 free(cur);
2204 result = -1;
2205 } else {
2206 struct variables *bottom = top_vars;
2207 cur->value = strdup(value);
Kim Phillipsb052b602012-10-29 13:34:32 +00002208 cur->next = NULL;
wdenkfe8c2802002-11-03 00:38:21 +00002209 cur->flg_export = flg_export;
2210 cur->flg_read_only = 0;
2211 while(bottom->next) bottom=bottom->next;
2212 bottom->next = cur;
2213 }
2214 }
2215 }
2216
2217#ifndef __U_BOOT__
2218 if(result==0 && cur->flg_export==1) {
2219 *(value-1) = '=';
2220 result = putenv(name);
2221 } else {
2222#endif
2223 free(name);
2224#ifndef __U_BOOT__
2225 if(result>0) /* equivalent to previous set */
2226 result = 0;
2227 }
2228#endif
2229 return result;
2230}
2231
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002232void unset_local_var(const char *name)
wdenkfe8c2802002-11-03 00:38:21 +00002233{
2234 struct variables *cur;
2235
2236 if (name) {
2237 for (cur = top_vars; cur; cur=cur->next) {
2238 if(strcmp(cur->name, name)==0)
2239 break;
2240 }
Kim Phillipsb052b602012-10-29 13:34:32 +00002241 if (cur != NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002242 struct variables *next = top_vars;
2243 if(cur->flg_read_only) {
2244 error_msg("%s: readonly variable", name);
2245 return;
2246 } else {
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002247#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00002248 if(cur->flg_export)
2249 unsetenv(cur->name);
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002250#endif
wdenkfe8c2802002-11-03 00:38:21 +00002251 free(cur->name);
2252 free(cur->value);
2253 while (next->next != cur)
2254 next = next->next;
2255 next->next = cur->next;
2256 }
2257 free(cur);
2258 }
2259 }
2260}
wdenkfe8c2802002-11-03 00:38:21 +00002261
2262static int is_assignment(const char *s)
2263{
wdenk6203e402004-04-18 10:13:26 +00002264 if (s == NULL)
2265 return 0;
2266
2267 if (!isalpha(*s)) return 0;
wdenkfe8c2802002-11-03 00:38:21 +00002268 ++s;
2269 while(isalnum(*s) || *s=='_') ++s;
2270 return *s=='=';
2271}
2272
2273#ifndef __U_BOOT__
2274/* the src parameter allows us to peek forward to a possible &n syntax
2275 * for file descriptor duplication, e.g., "2>&1".
2276 * Return code is 0 normally, 1 if a syntax error is detected in src.
2277 * Resource errors (in xmalloc) cause the process to exit */
2278static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2279 struct in_str *input)
2280{
2281 struct child_prog *child=ctx->child;
2282 struct redir_struct *redir = child->redirects;
2283 struct redir_struct *last_redir=NULL;
2284
2285 /* Create a new redir_struct and drop it onto the end of the linked list */
2286 while(redir) {
2287 last_redir=redir;
2288 redir=redir->next;
2289 }
2290 redir = xmalloc(sizeof(struct redir_struct));
2291 redir->next=NULL;
2292 redir->word.gl_pathv=NULL;
2293 if (last_redir) {
2294 last_redir->next=redir;
2295 } else {
2296 child->redirects=redir;
2297 }
2298
2299 redir->type=style;
2300 redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
2301
2302 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2303
2304 /* Check for a '2>&1' type redirect */
2305 redir->dup = redirect_dup_num(input);
2306 if (redir->dup == -2) return 1; /* syntax error */
2307 if (redir->dup != -1) {
2308 /* Erik had a check here that the file descriptor in question
2309 * is legit; I postpone that to "run time"
2310 * A "-" representation of "close me" shows up as a -3 here */
2311 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2312 } else {
2313 /* We do _not_ try to open the file that src points to,
2314 * since we need to return and let src be expanded first.
2315 * Set ctx->pending_redirect, so we know what to do at the
2316 * end of the next parsed word.
2317 */
2318 ctx->pending_redirect = redir;
2319 }
2320 return 0;
2321}
2322#endif
2323
Kim Phillipsb052b602012-10-29 13:34:32 +00002324static struct pipe *new_pipe(void)
2325{
wdenkfe8c2802002-11-03 00:38:21 +00002326 struct pipe *pi;
2327 pi = xmalloc(sizeof(struct pipe));
2328 pi->num_progs = 0;
2329 pi->progs = NULL;
2330 pi->next = NULL;
2331 pi->followup = 0; /* invalid */
Wolfgang Denk00b67fd2005-09-28 01:49:47 +02002332 pi->r_mode = RES_NONE;
wdenkfe8c2802002-11-03 00:38:21 +00002333 return pi;
2334}
2335
2336static void initialize_context(struct p_context *ctx)
2337{
2338 ctx->pipe=NULL;
2339#ifndef __U_BOOT__
2340 ctx->pending_redirect=NULL;
2341#endif
2342 ctx->child=NULL;
2343 ctx->list_head=new_pipe();
2344 ctx->pipe=ctx->list_head;
2345 ctx->w=RES_NONE;
2346 ctx->stack=NULL;
2347#ifdef __U_BOOT__
2348 ctx->old_flag=0;
2349#endif
2350 done_command(ctx); /* creates the memory for working child */
2351}
2352
2353/* normal return is 0
2354 * if a reserved word is found, and processed, return 1
2355 * should handle if, then, elif, else, fi, for, while, until, do, done.
2356 * case, function, and select are obnoxious, save those for later.
2357 */
wdenkb02744a2003-04-05 00:53:31 +00002358struct reserved_combo {
2359 char *literal;
2360 int code;
2361 long flag;
2362};
2363/* Mostly a list of accepted follow-up reserved words.
2364 * FLAG_END means we are done with the sequence, and are ready
2365 * to turn the compound list into a command.
2366 * FLAG_START means the word must start a new compound list.
2367 */
2368static struct reserved_combo reserved_list[] = {
2369 { "if", RES_IF, FLAG_THEN | FLAG_START },
2370 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2371 { "elif", RES_ELIF, FLAG_THEN },
2372 { "else", RES_ELSE, FLAG_FI },
2373 { "fi", RES_FI, FLAG_END },
2374 { "for", RES_FOR, FLAG_IN | FLAG_START },
2375 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2376 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2377 { "in", RES_IN, FLAG_DO },
2378 { "do", RES_DO, FLAG_DONE },
2379 { "done", RES_DONE, FLAG_END }
2380};
2381#define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo))
2382
Kim Phillipsb052b602012-10-29 13:34:32 +00002383static int reserved_word(o_string *dest, struct p_context *ctx)
wdenkfe8c2802002-11-03 00:38:21 +00002384{
wdenkfe8c2802002-11-03 00:38:21 +00002385 struct reserved_combo *r;
2386 for (r=reserved_list;
wdenkfe8c2802002-11-03 00:38:21 +00002387 r<reserved_list+NRES; r++) {
2388 if (strcmp(dest->data, r->literal) == 0) {
2389 debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
2390 if (r->flag & FLAG_START) {
2391 struct p_context *new = xmalloc(sizeof(struct p_context));
2392 debug_printf("push stack\n");
2393 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2394 syntax();
2395 free(new);
2396 ctx->w = RES_SNTX;
2397 b_reset(dest);
2398 return 1;
2399 }
2400 *new = *ctx; /* physical copy */
2401 initialize_context(ctx);
2402 ctx->stack=new;
2403 } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
2404 syntax();
2405 ctx->w = RES_SNTX;
2406 b_reset(dest);
2407 return 1;
2408 }
2409 ctx->w=r->code;
2410 ctx->old_flag = r->flag;
2411 if (ctx->old_flag & FLAG_END) {
2412 struct p_context *old;
2413 debug_printf("pop stack\n");
2414 done_pipe(ctx,PIPE_SEQ);
2415 old = ctx->stack;
2416 old->child->group = ctx->list_head;
2417#ifndef __U_BOOT__
2418 old->child->subshell = 0;
2419#endif
2420 *ctx = *old; /* physical copy */
2421 free(old);
2422 }
2423 b_reset (dest);
2424 return 1;
2425 }
2426 }
2427 return 0;
2428}
2429
2430/* normal return is 0.
2431 * Syntax or xglob errors return 1. */
2432static int done_word(o_string *dest, struct p_context *ctx)
2433{
2434 struct child_prog *child=ctx->child;
2435#ifndef __U_BOOT__
2436 glob_t *glob_target;
2437 int gr, flags = 0;
2438#else
2439 char *str, *s;
2440 int argc, cnt;
2441#endif
2442
2443 debug_printf("done_word: %s %p\n", dest->data, child);
2444 if (dest->length == 0 && !dest->nonnull) {
2445 debug_printf(" true null, ignored\n");
2446 return 0;
2447 }
2448#ifndef __U_BOOT__
2449 if (ctx->pending_redirect) {
2450 glob_target = &ctx->pending_redirect->word;
2451 } else {
2452#endif
2453 if (child->group) {
2454 syntax();
2455 return 1; /* syntax error, groups and arglists don't mix */
2456 }
2457 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2458 debug_printf("checking %s for reserved-ness\n",dest->data);
2459 if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
2460 }
2461#ifndef __U_BOOT__
2462 glob_target = &child->glob_result;
wdenk57b2d802003-06-27 21:31:46 +00002463 if (child->argv) flags |= GLOB_APPEND;
wdenkfe8c2802002-11-03 00:38:21 +00002464#else
2465 for (cnt = 1, s = dest->data; s && *s; s++) {
2466 if (*s == '\\') s++;
2467 cnt++;
2468 }
2469 str = malloc(cnt);
2470 if (!str) return 1;
2471 if ( child->argv == NULL) {
2472 child->argc=0;
2473 }
2474 argc = ++child->argc;
2475 child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv));
2476 if (child->argv == NULL) return 1;
Stephen Warren60c38c92014-03-01 22:16:10 -07002477 child->argv_nonnull = realloc(child->argv_nonnull,
2478 (argc+1)*sizeof(*child->argv_nonnull));
2479 if (child->argv_nonnull == NULL)
2480 return 1;
wdenkfe8c2802002-11-03 00:38:21 +00002481 child->argv[argc-1]=str;
Stephen Warren60c38c92014-03-01 22:16:10 -07002482 child->argv_nonnull[argc-1] = dest->nonnull;
wdenkfe8c2802002-11-03 00:38:21 +00002483 child->argv[argc]=NULL;
Stephen Warren60c38c92014-03-01 22:16:10 -07002484 child->argv_nonnull[argc] = 0;
wdenkfe8c2802002-11-03 00:38:21 +00002485 for (s = dest->data; s && *s; s++,str++) {
2486 if (*s == '\\') s++;
2487 *str = *s;
2488 }
2489 *str = '\0';
2490#endif
2491#ifndef __U_BOOT__
2492 }
2493 gr = xglob(dest, flags, glob_target);
2494 if (gr != 0) return 1;
2495#endif
2496
2497 b_reset(dest);
2498#ifndef __U_BOOT__
2499 if (ctx->pending_redirect) {
2500 ctx->pending_redirect=NULL;
2501 if (glob_target->gl_pathc != 1) {
2502 error_msg("ambiguous redirect");
2503 return 1;
2504 }
2505 } else {
2506 child->argv = glob_target->gl_pathv;
2507 }
2508#endif
2509 if (ctx->w == RES_FOR) {
2510 done_word(dest,ctx);
2511 done_pipe(ctx,PIPE_SEQ);
2512 }
2513 return 0;
2514}
2515
2516/* The only possible error here is out of memory, in which case
2517 * xmalloc exits. */
2518static int done_command(struct p_context *ctx)
2519{
2520 /* The child is really already in the pipe structure, so
2521 * advance the pipe counter and make a new, null child.
2522 * Only real trickiness here is that the uncommitted
2523 * child structure, to which ctx->child points, is not
2524 * counted in pi->num_progs. */
2525 struct pipe *pi=ctx->pipe;
2526 struct child_prog *prog=ctx->child;
2527
2528 if (prog && prog->group == NULL
wdenk57b2d802003-06-27 21:31:46 +00002529 && prog->argv == NULL
wdenkfe8c2802002-11-03 00:38:21 +00002530#ifndef __U_BOOT__
wdenk57b2d802003-06-27 21:31:46 +00002531 && prog->redirects == NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002532#else
2533 ) {
2534#endif
2535 debug_printf("done_command: skipping null command\n");
2536 return 0;
2537 } else if (prog) {
2538 pi->num_progs++;
2539 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
2540 } else {
2541 debug_printf("done_command: initializing\n");
2542 }
2543 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2544
2545 prog = pi->progs + pi->num_progs;
2546#ifndef __U_BOOT__
2547 prog->redirects = NULL;
2548#endif
2549 prog->argv = NULL;
Stephen Warren60c38c92014-03-01 22:16:10 -07002550 prog->argv_nonnull = NULL;
wdenkfe8c2802002-11-03 00:38:21 +00002551#ifndef __U_BOOT__
2552 prog->is_stopped = 0;
2553#endif
2554 prog->group = NULL;
2555#ifndef __U_BOOT__
2556 prog->glob_result.gl_pathv = NULL;
2557 prog->family = pi;
2558#endif
2559 prog->sp = 0;
2560 ctx->child = prog;
2561 prog->type = ctx->type;
2562
2563 /* but ctx->pipe and ctx->list_head remain unchanged */
2564 return 0;
2565}
2566
2567static int done_pipe(struct p_context *ctx, pipe_style type)
2568{
2569 struct pipe *new_p;
2570 done_command(ctx); /* implicit closure of previous command */
2571 debug_printf("done_pipe, type %d\n", type);
2572 ctx->pipe->followup = type;
2573 ctx->pipe->r_mode = ctx->w;
2574 new_p=new_pipe();
2575 ctx->pipe->next = new_p;
2576 ctx->pipe = new_p;
2577 ctx->child = NULL;
2578 done_command(ctx); /* set up new pipe to accept commands */
2579 return 0;
2580}
2581
2582#ifndef __U_BOOT__
2583/* peek ahead in the in_str to find out if we have a "&n" construct,
2584 * as in "2>&1", that represents duplicating a file descriptor.
2585 * returns either -2 (syntax error), -1 (no &), or the number found.
2586 */
2587static int redirect_dup_num(struct in_str *input)
2588{
2589 int ch, d=0, ok=0;
2590 ch = b_peek(input);
2591 if (ch != '&') return -1;
2592
2593 b_getch(input); /* get the & */
2594 ch=b_peek(input);
2595 if (ch == '-') {
2596 b_getch(input);
2597 return -3; /* "-" represents "close me" */
2598 }
2599 while (isdigit(ch)) {
2600 d = d*10+(ch-'0');
2601 ok=1;
2602 b_getch(input);
2603 ch = b_peek(input);
2604 }
2605 if (ok) return d;
2606
2607 error_msg("ambiguous redirect");
2608 return -2;
2609}
2610
2611/* If a redirect is immediately preceded by a number, that number is
2612 * supposed to tell which file descriptor to redirect. This routine
2613 * looks for such preceding numbers. In an ideal world this routine
2614 * needs to handle all the following classes of redirects...
2615 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2616 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2617 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2618 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2619 * A -1 output from this program means no valid number was found, so the
2620 * caller should use the appropriate default for this redirection.
2621 */
2622static int redirect_opt_num(o_string *o)
2623{
2624 int num;
2625
2626 if (o->length==0) return -1;
2627 for(num=0; num<o->length; num++) {
2628 if (!isdigit(*(o->data+num))) {
2629 return -1;
2630 }
2631 }
2632 /* reuse num (and save an int) */
2633 num=atoi(o->data);
2634 b_reset(o);
2635 return num;
2636}
2637
2638FILE *generate_stream_from_list(struct pipe *head)
2639{
2640 FILE *pf;
2641#if 1
2642 int pid, channel[2];
2643 if (pipe(channel)<0) perror_msg_and_die("pipe");
2644 pid=fork();
2645 if (pid<0) {
2646 perror_msg_and_die("fork");
2647 } else if (pid==0) {
2648 close(channel[0]);
2649 if (channel[1] != 1) {
2650 dup2(channel[1],1);
2651 close(channel[1]);
2652 }
2653#if 0
2654#define SURROGATE "surrogate response"
2655 write(1,SURROGATE,sizeof(SURROGATE));
2656 _exit(run_list(head));
2657#else
2658 _exit(run_list_real(head)); /* leaks memory */
2659#endif
2660 }
2661 debug_printf("forked child %d\n",pid);
2662 close(channel[1]);
2663 pf = fdopen(channel[0],"r");
2664 debug_printf("pipe on FILE *%p\n",pf);
2665#else
2666 free_pipe_list(head,0);
2667 pf=popen("echo surrogate response","r");
2668 debug_printf("started fake pipe on FILE *%p\n",pf);
2669#endif
2670 return pf;
2671}
2672
2673/* this version hacked for testing purposes */
2674/* return code is exit status of the process that is run. */
2675static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2676{
2677 int retcode;
2678 o_string result=NULL_O_STRING;
2679 struct p_context inner;
2680 FILE *p;
2681 struct in_str pipe_str;
2682 initialize_context(&inner);
2683
2684 /* recursion to generate command */
2685 retcode = parse_stream(&result, &inner, input, subst_end);
2686 if (retcode != 0) return retcode; /* syntax error or EOF */
2687 done_word(&result, &inner);
2688 done_pipe(&inner, PIPE_SEQ);
2689 b_free(&result);
2690
2691 p=generate_stream_from_list(inner.list_head);
2692 if (p==NULL) return 1;
2693 mark_open(fileno(p));
2694 setup_file_in_str(&pipe_str, p);
2695
2696 /* now send results of command back into original context */
2697 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2698 /* XXX In case of a syntax error, should we try to kill the child?
2699 * That would be tough to do right, so just read until EOF. */
2700 if (retcode == 1) {
2701 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
2702 }
2703
2704 debug_printf("done reading from pipe, pclose()ing\n");
2705 /* This is the step that wait()s for the child. Should be pretty
2706 * safe, since we just read an EOF from its stdout. We could try
2707 * to better, by using wait(), and keeping track of background jobs
2708 * at the same time. That would be a lot of work, and contrary
2709 * to the KISS philosophy of this program. */
2710 mark_closed(fileno(p));
2711 retcode=pclose(p);
2712 free_pipe_list(inner.list_head,0);
2713 debug_printf("pclosed, retcode=%d\n",retcode);
2714 /* XXX this process fails to trim a single trailing newline */
2715 return retcode;
2716}
2717
2718static int parse_group(o_string *dest, struct p_context *ctx,
2719 struct in_str *input, int ch)
2720{
2721 int rcode, endch=0;
2722 struct p_context sub;
2723 struct child_prog *child = ctx->child;
2724 if (child->argv) {
2725 syntax();
2726 return 1; /* syntax error, groups and arglists don't mix */
2727 }
2728 initialize_context(&sub);
2729 switch(ch) {
2730 case '(': endch=')'; child->subshell=1; break;
2731 case '{': endch='}'; break;
2732 default: syntax(); /* really logic error */
2733 }
2734 rcode=parse_stream(dest,&sub,input,endch);
2735 done_word(dest,&sub); /* finish off the final word in the subcontext */
2736 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2737 child->group = sub.list_head;
2738 return rcode;
2739 /* child remains "open", available for possible redirects */
2740}
2741#endif
2742
2743/* basically useful version until someone wants to get fancier,
2744 * see the bash man page under "Parameter Expansion" */
2745static char *lookup_param(char *src)
2746{
wdenk6203e402004-04-18 10:13:26 +00002747 char *p;
Joe Hershberger82fea772012-08-17 10:26:29 +00002748 char *sep;
2749 char *default_val = NULL;
2750 int assign = 0;
2751 int expand_empty = 0;
wdenk6203e402004-04-18 10:13:26 +00002752
2753 if (!src)
2754 return NULL;
2755
Joe Hershberger82fea772012-08-17 10:26:29 +00002756 sep = strchr(src, ':');
2757
2758 if (sep) {
2759 *sep = '\0';
2760 if (*(sep + 1) == '-')
2761 default_val = sep+2;
2762 if (*(sep + 1) == '=') {
2763 default_val = sep+2;
2764 assign = 1;
2765 }
2766 if (*(sep + 1) == '+') {
2767 default_val = sep+2;
2768 expand_empty = 1;
2769 }
2770 }
2771
2772 p = getenv(src);
2773 if (!p)
2774 p = get_local_var(src);
2775
2776 if (!p || strlen(p) == 0) {
2777 p = default_val;
2778 if (assign) {
2779 char *var = malloc(strlen(src)+strlen(default_val)+2);
2780 if (var) {
2781 sprintf(var, "%s=%s", src, default_val);
2782 set_local_var(var, 0);
2783 }
2784 free(var);
2785 }
2786 } else if (expand_empty) {
2787 p += strlen(p);
2788 }
2789
2790 if (sep)
2791 *sep = ':';
wdenk6203e402004-04-18 10:13:26 +00002792
wdenkfe8c2802002-11-03 00:38:21 +00002793 return p;
2794}
wdenk6203e402004-04-18 10:13:26 +00002795
2796#ifdef __U_BOOT__
2797static char *get_dollar_var(char ch)
2798{
2799 static char buf[40];
2800
2801 buf[0] = '\0';
2802 switch (ch) {
2803 case '?':
2804 sprintf(buf, "%u", (unsigned int)last_return_code);
2805 break;
2806 default:
2807 return NULL;
2808 }
2809 return buf;
2810}
2811#endif
wdenkfe8c2802002-11-03 00:38:21 +00002812
2813/* return code: 0 for OK, 1 for syntax error */
2814static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2815{
2816#ifndef __U_BOOT__
2817 int i, advance=0;
2818#else
2819 int advance=0;
2820#endif
2821#ifndef __U_BOOT__
2822 char sep[]=" ";
2823#endif
2824 int ch = input->peek(input); /* first character after the $ */
2825 debug_printf("handle_dollar: ch=%c\n",ch);
2826 if (isalpha(ch)) {
2827 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2828 ctx->child->sp++;
2829 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
2830 b_getch(input);
2831 b_addchr(dest,ch);
2832 }
2833 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2834#ifndef __U_BOOT__
2835 } else if (isdigit(ch)) {
2836 i = ch-'0'; /* XXX is $0 special? */
2837 if (i<global_argc) {
2838 parse_string(dest, ctx, global_argv[i]); /* recursion */
2839 }
2840 advance = 1;
2841#endif
2842 } else switch (ch) {
2843#ifndef __U_BOOT__
2844 case '$':
2845 b_adduint(dest,getpid());
2846 advance = 1;
2847 break;
2848 case '!':
2849 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2850 advance = 1;
2851 break;
2852#endif
2853 case '?':
wdenk6203e402004-04-18 10:13:26 +00002854#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00002855 b_adduint(dest,last_return_code);
wdenk6203e402004-04-18 10:13:26 +00002856#else
2857 ctx->child->sp++;
2858 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2859 b_addchr(dest, '$');
2860 b_addchr(dest, '?');
2861 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2862#endif
wdenkfe8c2802002-11-03 00:38:21 +00002863 advance = 1;
2864 break;
2865#ifndef __U_BOOT__
2866 case '#':
2867 b_adduint(dest,global_argc ? global_argc-1 : 0);
2868 advance = 1;
2869 break;
2870#endif
2871 case '{':
2872 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2873 ctx->child->sp++;
2874 b_getch(input);
2875 /* XXX maybe someone will try to escape the '}' */
2876 while(ch=b_getch(input),ch!=EOF && ch!='}') {
2877 b_addchr(dest,ch);
2878 }
2879 if (ch != '}') {
2880 syntax();
2881 return 1;
2882 }
2883 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2884 break;
2885#ifndef __U_BOOT__
2886 case '(':
2887 b_getch(input);
2888 process_command_subs(dest, ctx, input, ')');
2889 break;
2890 case '*':
2891 sep[0]=ifs[0];
2892 for (i=1; i<global_argc; i++) {
2893 parse_string(dest, ctx, global_argv[i]);
2894 if (i+1 < global_argc) parse_string(dest, ctx, sep);
2895 }
2896 break;
2897 case '@':
2898 case '-':
2899 case '_':
2900 /* still unhandled, but should be eventually */
2901 error_msg("unhandled syntax: $%c",ch);
2902 return 1;
2903 break;
2904#endif
2905 default:
2906 b_addqchr(dest,'$',dest->quote);
2907 }
2908 /* Eat the character if the flag was set. If the compiler
2909 * is smart enough, we could substitute "b_getch(input);"
2910 * for all the "advance = 1;" above, and also end up with
2911 * a nice size-optimized program. Hah! That'll be the day.
2912 */
2913 if (advance) b_getch(input);
2914 return 0;
2915}
2916
2917#ifndef __U_BOOT__
2918int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2919{
2920 struct in_str foo;
2921 setup_string_in_str(&foo, src);
2922 return parse_stream(dest, ctx, &foo, '\0');
2923}
2924#endif
2925
2926/* return code is 0 for normal exit, 1 for syntax error */
Kim Phillipsb052b602012-10-29 13:34:32 +00002927static int parse_stream(o_string *dest, struct p_context *ctx,
2928 struct in_str *input, int end_trigger)
wdenkfe8c2802002-11-03 00:38:21 +00002929{
2930 unsigned int ch, m;
2931#ifndef __U_BOOT__
2932 int redir_fd;
2933 redir_type redir_style;
2934#endif
2935 int next;
2936
2937 /* Only double-quote state is handled in the state variable dest->quote.
2938 * A single-quote triggers a bypass of the main loop until its mate is
2939 * found. When recursing, quote state is passed in via dest->quote. */
2940
2941 debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
2942 while ((ch=b_getch(input))!=EOF) {
2943 m = map[ch];
2944#ifdef __U_BOOT__
2945 if (input->__promptme == 0) return 1;
2946#endif
2947 next = (ch == '\n') ? 0 : b_peek(input);
wdenk6203e402004-04-18 10:13:26 +00002948
2949 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n",
2950 ch >= ' ' ? ch : '.', ch, m,
2951 dest->quote, ctx->stack == NULL ? '*' : '.');
2952
wdenkfe8c2802002-11-03 00:38:21 +00002953 if (m==0 || ((m==1 || m==2) && dest->quote)) {
2954 b_addqchr(dest, ch, dest->quote);
2955 } else {
2956 if (m==2) { /* unquoted IFS */
2957 if (done_word(dest, ctx)) {
2958 return 1;
2959 }
2960 /* If we aren't performing a substitution, treat a newline as a
2961 * command separator. */
2962 if (end_trigger != '\0' && ch=='\n')
2963 done_pipe(ctx,PIPE_SEQ);
2964 }
2965 if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
2966 debug_printf("leaving parse_stream (triggered)\n");
2967 return 0;
2968 }
2969#if 0
2970 if (ch=='\n') {
2971 /* Yahoo! Time to run with it! */
2972 done_pipe(ctx,PIPE_SEQ);
2973 run_list(ctx->list_head);
2974 initialize_context(ctx);
2975 }
2976#endif
2977 if (m!=2) switch (ch) {
2978 case '#':
2979 if (dest->length == 0 && !dest->quote) {
2980 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
2981 } else {
2982 b_addqchr(dest, ch, dest->quote);
2983 }
2984 break;
2985 case '\\':
2986 if (next == EOF) {
2987 syntax();
2988 return 1;
2989 }
2990 b_addqchr(dest, '\\', dest->quote);
2991 b_addqchr(dest, b_getch(input), dest->quote);
2992 break;
2993 case '$':
2994 if (handle_dollar(dest, ctx, input)!=0) return 1;
2995 break;
2996 case '\'':
2997 dest->nonnull = 1;
2998 while(ch=b_getch(input),ch!=EOF && ch!='\'') {
2999#ifdef __U_BOOT__
3000 if(input->__promptme == 0) return 1;
3001#endif
3002 b_addchr(dest,ch);
3003 }
3004 if (ch==EOF) {
3005 syntax();
3006 return 1;
3007 }
3008 break;
3009 case '"':
3010 dest->nonnull = 1;
3011 dest->quote = !dest->quote;
3012 break;
3013#ifndef __U_BOOT__
3014 case '`':
3015 process_command_subs(dest, ctx, input, '`');
3016 break;
3017 case '>':
3018 redir_fd = redirect_opt_num(dest);
3019 done_word(dest, ctx);
3020 redir_style=REDIRECT_OVERWRITE;
3021 if (next == '>') {
3022 redir_style=REDIRECT_APPEND;
3023 b_getch(input);
3024 } else if (next == '(') {
3025 syntax(); /* until we support >(list) Process Substitution */
3026 return 1;
3027 }
3028 setup_redirect(ctx, redir_fd, redir_style, input);
3029 break;
3030 case '<':
3031 redir_fd = redirect_opt_num(dest);
3032 done_word(dest, ctx);
3033 redir_style=REDIRECT_INPUT;
3034 if (next == '<') {
3035 redir_style=REDIRECT_HEREIS;
3036 b_getch(input);
3037 } else if (next == '>') {
3038 redir_style=REDIRECT_IO;
3039 b_getch(input);
3040 } else if (next == '(') {
3041 syntax(); /* until we support <(list) Process Substitution */
3042 return 1;
3043 }
3044 setup_redirect(ctx, redir_fd, redir_style, input);
3045 break;
3046#endif
3047 case ';':
3048 done_word(dest, ctx);
3049 done_pipe(ctx,PIPE_SEQ);
3050 break;
3051 case '&':
3052 done_word(dest, ctx);
3053 if (next=='&') {
3054 b_getch(input);
3055 done_pipe(ctx,PIPE_AND);
3056 } else {
3057#ifndef __U_BOOT__
3058 done_pipe(ctx,PIPE_BG);
3059#else
3060 syntax_err();
3061 return 1;
3062#endif
3063 }
3064 break;
3065 case '|':
3066 done_word(dest, ctx);
3067 if (next=='|') {
3068 b_getch(input);
3069 done_pipe(ctx,PIPE_OR);
3070 } else {
3071 /* we could pick up a file descriptor choice here
3072 * with redirect_opt_num(), but bash doesn't do it.
3073 * "echo foo 2| cat" yields "foo 2". */
3074#ifndef __U_BOOT__
3075 done_command(ctx);
3076#else
3077 syntax_err();
3078 return 1;
3079#endif
3080 }
3081 break;
3082#ifndef __U_BOOT__
3083 case '(':
3084 case '{':
3085 if (parse_group(dest, ctx, input, ch)!=0) return 1;
3086 break;
3087 case ')':
3088 case '}':
3089 syntax(); /* Proper use of this character caught by end_trigger */
3090 return 1;
3091 break;
3092#endif
Joe Hershberger38de0b62012-08-17 10:26:30 +00003093 case SUBSTED_VAR_SYMBOL:
3094 dest->nonnull = 1;
3095 while (ch = b_getch(input), ch != EOF &&
3096 ch != SUBSTED_VAR_SYMBOL) {
3097 debug_printf("subst, pass=%d\n", ch);
3098 if (input->__promptme == 0)
3099 return 1;
3100 b_addchr(dest, ch);
3101 }
3102 debug_printf("subst, term=%d\n", ch);
3103 if (ch == EOF) {
3104 syntax();
3105 return 1;
3106 }
3107 break;
wdenkfe8c2802002-11-03 00:38:21 +00003108 default:
3109 syntax(); /* this is really an internal logic error */
3110 return 1;
3111 }
3112 }
3113 }
3114 /* complain if quote? No, maybe we just finished a command substitution
3115 * that was quoted. Example:
3116 * $ echo "`cat foo` plus more"
3117 * and we just got the EOF generated by the subshell that ran "cat foo"
3118 * The only real complaint is if we got an EOF when end_trigger != '\0',
3119 * that is, we were really supposed to get end_trigger, and never got
3120 * one before the EOF. Can't use the standard "syntax error" return code,
3121 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3122 debug_printf("leaving parse_stream (EOF)\n");
3123 if (end_trigger != '\0') return -1;
3124 return 0;
3125}
3126
Kim Phillipsb052b602012-10-29 13:34:32 +00003127static void mapset(const unsigned char *set, int code)
wdenkfe8c2802002-11-03 00:38:21 +00003128{
3129 const unsigned char *s;
3130 for (s=set; *s; s++) map[*s] = code;
3131}
3132
Kim Phillipsb052b602012-10-29 13:34:32 +00003133static void update_ifs_map(void)
wdenkfe8c2802002-11-03 00:38:21 +00003134{
3135 /* char *ifs and char map[256] are both globals. */
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003136 ifs = (uchar *)getenv("IFS");
3137 if (ifs == NULL) ifs=(uchar *)" \t\n";
wdenkfe8c2802002-11-03 00:38:21 +00003138 /* Precompute a list of 'flow through' behavior so it can be treated
3139 * quickly up front. Computation is necessary because of IFS.
3140 * Special case handling of IFS == " \t\n" is not implemented.
3141 * The map[] array only really needs two bits each, and on most machines
3142 * that would be faster because of the reduced L1 cache footprint.
3143 */
3144 memset(map,0,sizeof(map)); /* most characters flow through always */
3145#ifndef __U_BOOT__
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003146 mapset((uchar *)"\\$'\"`", 3); /* never flow through */
3147 mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */
wdenkfe8c2802002-11-03 00:38:21 +00003148#else
Joe Hershberger38de0b62012-08-17 10:26:30 +00003149 {
3150 uchar subst[2] = {SUBSTED_VAR_SYMBOL, 0};
3151 mapset(subst, 3); /* never flow through */
3152 }
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003153 mapset((uchar *)"\\$'\"", 3); /* never flow through */
3154 mapset((uchar *)";&|#", 1); /* flow through if quoted */
wdenkfe8c2802002-11-03 00:38:21 +00003155#endif
3156 mapset(ifs, 2); /* also flow through if quoted */
3157}
3158
3159/* most recursion does not come through here, the exeception is
3160 * from builtin_source() */
Kim Phillipsb052b602012-10-29 13:34:32 +00003161static int parse_stream_outer(struct in_str *inp, int flag)
wdenkfe8c2802002-11-03 00:38:21 +00003162{
3163
3164 struct p_context ctx;
3165 o_string temp=NULL_O_STRING;
3166 int rcode;
3167#ifdef __U_BOOT__
3168 int code = 0;
3169#endif
3170 do {
3171 ctx.type = flag;
3172 initialize_context(&ctx);
3173 update_ifs_map();
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003174 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0);
wdenkfe8c2802002-11-03 00:38:21 +00003175 inp->promptmode=1;
3176 rcode = parse_stream(&temp, &ctx, inp, '\n');
3177#ifdef __U_BOOT__
3178 if (rcode == 1) flag_repeat = 0;
3179#endif
3180 if (rcode != 1 && ctx.old_flag != 0) {
3181 syntax();
3182#ifdef __U_BOOT__
3183 flag_repeat = 0;
3184#endif
3185 }
3186 if (rcode != 1 && ctx.old_flag == 0) {
3187 done_word(&temp, &ctx);
3188 done_pipe(&ctx,PIPE_SEQ);
3189#ifndef __U_BOOT__
3190 run_list(ctx.list_head);
3191#else
wdenk6203e402004-04-18 10:13:26 +00003192 code = run_list(ctx.list_head);
3193 if (code == -2) { /* exit */
3194 b_free(&temp);
3195 code = 0;
3196 /* XXX hackish way to not allow exit from main loop */
3197 if (inp->peek == file_peek) {
3198 printf("exit not allowed from main input shell.\n");
3199 continue;
3200 }
3201 break;
3202 }
3203 if (code == -1)
wdenkfe8c2802002-11-03 00:38:21 +00003204 flag_repeat = 0;
3205#endif
3206 } else {
3207 if (ctx.old_flag != 0) {
3208 free(ctx.stack);
3209 b_reset(&temp);
3210 }
3211#ifdef __U_BOOT__
3212 if (inp->__promptme == 0) printf("<INTERRUPT>\n");
3213 inp->__promptme = 1;
3214#endif
3215 temp.nonnull = 0;
3216 temp.quote = 0;
3217 inp->p = NULL;
3218 free_pipe_list(ctx.list_head,0);
3219 }
3220 b_free(&temp);
3221 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */
3222#ifndef __U_BOOT__
3223 return 0;
3224#else
3225 return (code != 0) ? 1 : 0;
3226#endif /* __U_BOOT__ */
3227}
3228
3229#ifndef __U_BOOT__
3230static int parse_string_outer(const char *s, int flag)
3231#else
Jason Hobbsa56febb2011-08-31 05:37:24 +00003232int parse_string_outer(const char *s, int flag)
wdenkfe8c2802002-11-03 00:38:21 +00003233#endif /* __U_BOOT__ */
3234{
3235 struct in_str input;
3236#ifdef __U_BOOT__
3237 char *p = NULL;
3238 int rcode;
3239 if ( !s || !*s)
3240 return 1;
3241 if (!(p = strchr(s, '\n')) || *++p) {
3242 p = xmalloc(strlen(s) + 2);
3243 strcpy(p, s);
3244 strcat(p, "\n");
3245 setup_string_in_str(&input, p);
3246 rcode = parse_stream_outer(&input, flag);
3247 free(p);
3248 return rcode;
3249 } else {
3250#endif
3251 setup_string_in_str(&input, s);
3252 return parse_stream_outer(&input, flag);
3253#ifdef __U_BOOT__
3254 }
3255#endif
3256}
3257
3258#ifndef __U_BOOT__
3259static int parse_file_outer(FILE *f)
3260#else
3261int parse_file_outer(void)
3262#endif
3263{
3264 int rcode;
3265 struct in_str input;
3266#ifndef __U_BOOT__
3267 setup_file_in_str(&input, f);
3268#else
3269 setup_file_in_str(&input);
3270#endif
3271 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3272 return rcode;
3273}
3274
3275#ifdef __U_BOOT__
Wolfgang Denkd0813e52010-10-28 20:00:11 +02003276#ifdef CONFIG_NEEDS_MANUAL_RELOC
wdenkb02744a2003-04-05 00:53:31 +00003277static void u_boot_hush_reloc(void)
3278{
wdenkb02744a2003-04-05 00:53:31 +00003279 unsigned long addr;
3280 struct reserved_combo *r;
3281
3282 for (r=reserved_list; r<reserved_list+NRES; r++) {
3283 addr = (ulong) (r->literal) + gd->reloc_off;
3284 r->literal = (char *)addr;
3285 }
3286}
Peter Tyser9057cbf2009-09-21 11:20:36 -05003287#endif
wdenkb02744a2003-04-05 00:53:31 +00003288
wdenkfe8c2802002-11-03 00:38:21 +00003289int u_boot_hush_start(void)
3290{
wdenkbd1575f2003-10-14 19:43:55 +00003291 if (top_vars == NULL) {
3292 top_vars = malloc(sizeof(struct variables));
3293 top_vars->name = "HUSH_VERSION";
3294 top_vars->value = "0.01";
Kim Phillipsb052b602012-10-29 13:34:32 +00003295 top_vars->next = NULL;
wdenkbd1575f2003-10-14 19:43:55 +00003296 top_vars->flg_export = 0;
3297 top_vars->flg_read_only = 1;
Wolfgang Denkd0813e52010-10-28 20:00:11 +02003298#ifdef CONFIG_NEEDS_MANUAL_RELOC
wdenkbd1575f2003-10-14 19:43:55 +00003299 u_boot_hush_reloc();
Peter Tyser9057cbf2009-09-21 11:20:36 -05003300#endif
wdenkbd1575f2003-10-14 19:43:55 +00003301 }
wdenkfe8c2802002-11-03 00:38:21 +00003302 return 0;
3303}
3304
3305static void *xmalloc(size_t size)
3306{
3307 void *p = NULL;
3308
3309 if (!(p = malloc(size))) {
3310 printf("ERROR : memory not allocated\n");
3311 for(;;);
3312 }
3313 return p;
3314}
3315
3316static void *xrealloc(void *ptr, size_t size)
3317{
3318 void *p = NULL;
3319
3320 if (!(p = realloc(ptr, size))) {
3321 printf("ERROR : memory not allocated\n");
3322 for(;;);
3323 }
3324 return p;
3325}
3326#endif /* __U_BOOT__ */
3327
3328#ifndef __U_BOOT__
3329/* Make sure we have a controlling tty. If we get started under a job
3330 * aware app (like bash for example), make sure we are now in charge so
3331 * we don't fight over who gets the foreground */
wdenke7f34c62003-01-11 09:48:40 +00003332static void setup_job_control(void)
wdenkfe8c2802002-11-03 00:38:21 +00003333{
3334 static pid_t shell_pgrp;
3335 /* Loop until we are in the foreground. */
3336 while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
3337 kill (- shell_pgrp, SIGTTIN);
3338
3339 /* Ignore interactive and job-control signals. */
3340 signal(SIGINT, SIG_IGN);
3341 signal(SIGQUIT, SIG_IGN);
3342 signal(SIGTERM, SIG_IGN);
3343 signal(SIGTSTP, SIG_IGN);
3344 signal(SIGTTIN, SIG_IGN);
3345 signal(SIGTTOU, SIG_IGN);
3346 signal(SIGCHLD, SIG_IGN);
3347
3348 /* Put ourselves in our own process group. */
3349 setsid();
3350 shell_pgrp = getpid ();
3351 setpgid (shell_pgrp, shell_pgrp);
3352
3353 /* Grab control of the terminal. */
3354 tcsetpgrp(shell_terminal, shell_pgrp);
3355}
3356
Wolfgang Denk6262d0212010-06-28 22:00:46 +02003357int hush_main(int argc, char * const *argv)
wdenkfe8c2802002-11-03 00:38:21 +00003358{
3359 int opt;
3360 FILE *input;
3361 char **e = environ;
3362
3363 /* XXX what should these be while sourcing /etc/profile? */
3364 global_argc = argc;
3365 global_argv = argv;
3366
3367 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3368 * hush_main(), therefore we cannot rely on the BSS to zero out this
3369 * stuff. Reset these to 0 every time. */
3370 ifs = NULL;
3371 /* map[] is taken care of with call to update_ifs_map() */
3372 fake_mode = 0;
3373 interactive = 0;
3374 close_me_head = NULL;
3375 last_bg_pid = 0;
3376 job_list = NULL;
3377 last_jobid = 0;
3378
3379 /* Initialize some more globals to non-zero values */
3380 set_cwd();
wdenke7f34c62003-01-11 09:48:40 +00003381#ifdef CONFIG_FEATURE_COMMAND_EDITING
wdenkfe8c2802002-11-03 00:38:21 +00003382 cmdedit_set_initial_prompt();
3383#else
3384 PS1 = NULL;
3385#endif
3386 PS2 = "> ";
3387
3388 /* initialize our shell local variables with the values
3389 * currently living in the environment */
3390 if (e) {
3391 for (; *e; e++)
3392 set_local_var(*e, 2); /* without call putenv() */
3393 }
3394
3395 last_return_code=EXIT_SUCCESS;
3396
3397
3398 if (argv[0] && argv[0][0] == '-') {
3399 debug_printf("\nsourcing /etc/profile\n");
3400 if ((input = fopen("/etc/profile", "r")) != NULL) {
3401 mark_open(fileno(input));
3402 parse_file_outer(input);
3403 mark_closed(fileno(input));
3404 fclose(input);
3405 }
3406 }
3407 input=stdin;
3408
3409 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3410 switch (opt) {
3411 case 'c':
3412 {
3413 global_argv = argv+optind;
3414 global_argc = argc-optind;
3415 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3416 goto final_return;
3417 }
3418 break;
3419 case 'i':
3420 interactive++;
3421 break;
3422 case 'f':
3423 fake_mode++;
3424 break;
3425 default:
3426#ifndef BB_VER
3427 fprintf(stderr, "Usage: sh [FILE]...\n"
3428 " or: sh -c command [args]...\n\n");
3429 exit(EXIT_FAILURE);
3430#else
3431 show_usage();
3432#endif
3433 }
3434 }
3435 /* A shell is interactive if the `-i' flag was given, or if all of
3436 * the following conditions are met:
3437 * no -c command
3438 * no arguments remaining or the -s flag given
3439 * standard input is a terminal
3440 * standard output is a terminal
3441 * Refer to Posix.2, the description of the `sh' utility. */
3442 if (argv[optind]==NULL && input==stdin &&
3443 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
3444 interactive++;
3445 }
3446
3447 debug_printf("\ninteractive=%d\n", interactive);
3448 if (interactive) {
3449 /* Looks like they want an interactive shell */
wdenk57b2d802003-06-27 21:31:46 +00003450#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
wdenke7f34c62003-01-11 09:48:40 +00003451 printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n");
3452 printf( "Enter 'help' for a list of built-in commands.\n\n");
3453#endif
wdenkfe8c2802002-11-03 00:38:21 +00003454 setup_job_control();
3455 }
3456
3457 if (argv[optind]==NULL) {
3458 opt=parse_file_outer(stdin);
3459 goto final_return;
3460 }
3461
3462 debug_printf("\nrunning script '%s'\n", argv[optind]);
3463 global_argv = argv+optind;
3464 global_argc = argc-optind;
3465 input = xfopen(argv[optind], "r");
3466 opt = parse_file_outer(input);
3467
wdenke7f34c62003-01-11 09:48:40 +00003468#ifdef CONFIG_FEATURE_CLEAN_UP
wdenkfe8c2802002-11-03 00:38:21 +00003469 fclose(input);
3470 if (cwd && cwd != unknown)
3471 free((char*)cwd);
3472 {
3473 struct variables *cur, *tmp;
3474 for(cur = top_vars; cur; cur = tmp) {
3475 tmp = cur->next;
3476 if (!cur->flg_read_only) {
3477 free(cur->name);
3478 free(cur->value);
3479 free(cur);
3480 }
3481 }
3482 }
3483#endif
3484
3485final_return:
3486 return(opt?opt:last_return_code);
3487}
3488#endif
3489
3490static char *insert_var_value(char *inp)
3491{
Joe Hershberger38de0b62012-08-17 10:26:30 +00003492 return insert_var_value_sub(inp, 0);
3493}
3494
3495static char *insert_var_value_sub(char *inp, int tag_subst)
3496{
wdenkfe8c2802002-11-03 00:38:21 +00003497 int res_str_len = 0;
3498 int len;
3499 int done = 0;
3500 char *p, *p1, *res_str = NULL;
3501
3502 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003503 /* check the beginning of the string for normal charachters */
wdenkfe8c2802002-11-03 00:38:21 +00003504 if (p != inp) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003505 /* copy any charachters to the result string */
wdenkfe8c2802002-11-03 00:38:21 +00003506 len = p - inp;
3507 res_str = xrealloc(res_str, (res_str_len + len));
3508 strncpy((res_str + res_str_len), inp, len);
3509 res_str_len += len;
3510 }
3511 inp = ++p;
Joe Hershberger38de0b62012-08-17 10:26:30 +00003512 /* find the ending marker */
wdenkfe8c2802002-11-03 00:38:21 +00003513 p = strchr(inp, SPECIAL_VAR_SYMBOL);
3514 *p = '\0';
Joe Hershberger38de0b62012-08-17 10:26:30 +00003515 /* look up the value to substitute */
wdenkfe8c2802002-11-03 00:38:21 +00003516 if ((p1 = lookup_param(inp))) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003517 if (tag_subst)
3518 len = res_str_len + strlen(p1) + 2;
3519 else
3520 len = res_str_len + strlen(p1);
wdenkfe8c2802002-11-03 00:38:21 +00003521 res_str = xrealloc(res_str, (1 + len));
Joe Hershberger38de0b62012-08-17 10:26:30 +00003522 if (tag_subst) {
3523 /*
3524 * copy the variable value to the result
3525 * string
3526 */
3527 strcpy((res_str + res_str_len + 1), p1);
3528
3529 /*
3530 * mark the replaced text to be accepted as
3531 * is
3532 */
3533 res_str[res_str_len] = SUBSTED_VAR_SYMBOL;
3534 res_str[res_str_len + 1 + strlen(p1)] =
3535 SUBSTED_VAR_SYMBOL;
3536 } else
3537 /*
3538 * copy the variable value to the result
3539 * string
3540 */
3541 strcpy((res_str + res_str_len), p1);
3542
wdenkfe8c2802002-11-03 00:38:21 +00003543 res_str_len = len;
3544 }
3545 *p = SPECIAL_VAR_SYMBOL;
3546 inp = ++p;
3547 done = 1;
3548 }
3549 if (done) {
3550 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
3551 strcpy((res_str + res_str_len), inp);
3552 while ((p = strchr(res_str, '\n'))) {
3553 *p = ' ';
3554 }
3555 }
3556 return (res_str == NULL) ? inp : res_str;
3557}
3558
3559static char **make_list_in(char **inp, char *name)
3560{
3561 int len, i;
3562 int name_len = strlen(name);
3563 int n = 0;
3564 char **list;
3565 char *p1, *p2, *p3;
3566
3567 /* create list of variable values */
3568 list = xmalloc(sizeof(*list));
3569 for (i = 0; inp[i]; i++) {
3570 p3 = insert_var_value(inp[i]);
3571 p1 = p3;
3572 while (*p1) {
3573 if ((*p1 == ' ')) {
3574 p1++;
3575 continue;
3576 }
3577 if ((p2 = strchr(p1, ' '))) {
3578 len = p2 - p1;
3579 } else {
3580 len = strlen(p1);
3581 p2 = p1 + len;
3582 }
3583 /* we use n + 2 in realloc for list,because we add
3584 * new element and then we will add NULL element */
3585 list = xrealloc(list, sizeof(*list) * (n + 2));
3586 list[n] = xmalloc(2 + name_len + len);
3587 strcpy(list[n], name);
3588 strcat(list[n], "=");
3589 strncat(list[n], p1, len);
3590 list[n++][name_len + len + 1] = '\0';
3591 p1 = p2;
3592 }
3593 if (p3 != inp[i]) free(p3);
3594 }
3595 list[n] = NULL;
3596 return list;
3597}
3598
Stephen Warren60c38c92014-03-01 22:16:10 -07003599/*
3600 * Make new string for parser
3601 * inp - array of argument strings to flatten
3602 * nonnull - indicates argument was quoted when originally parsed
3603 */
3604static char *make_string(char **inp, int *nonnull)
wdenkfe8c2802002-11-03 00:38:21 +00003605{
3606 char *p;
3607 char *str = NULL;
3608 int n;
3609 int len = 2;
Joe Hershberger38de0b62012-08-17 10:26:30 +00003610 char *noeval_str;
3611 int noeval = 0;
wdenkfe8c2802002-11-03 00:38:21 +00003612
Joe Hershberger38de0b62012-08-17 10:26:30 +00003613 noeval_str = get_local_var("HUSH_NO_EVAL");
3614 if (noeval_str != NULL && *noeval_str != '0' && *noeval_str != '\0')
3615 noeval = 1;
wdenkfe8c2802002-11-03 00:38:21 +00003616 for (n = 0; inp[n]; n++) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003617 p = insert_var_value_sub(inp[n], noeval);
Stephen Warren60c38c92014-03-01 22:16:10 -07003618 str = xrealloc(str, (len + strlen(p) + (2 * nonnull[n])));
wdenkfe8c2802002-11-03 00:38:21 +00003619 if (n) {
3620 strcat(str, " ");
3621 } else {
3622 *str = '\0';
3623 }
Stephen Warren60c38c92014-03-01 22:16:10 -07003624 if (nonnull[n])
3625 strcat(str, "'");
wdenkfe8c2802002-11-03 00:38:21 +00003626 strcat(str, p);
Stephen Warren60c38c92014-03-01 22:16:10 -07003627 if (nonnull[n])
3628 strcat(str, "'");
wdenkfe8c2802002-11-03 00:38:21 +00003629 len = strlen(str) + 3;
3630 if (p != inp[n]) free(p);
3631 }
3632 len = strlen(str);
3633 *(str + len) = '\n';
3634 *(str + len + 1) = '\0';
3635 return str;
3636}
3637
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003638#ifdef __U_BOOT__
Kim Phillipsb052b602012-10-29 13:34:32 +00003639static int do_showvar(cmd_tbl_t *cmdtp, int flag, int argc,
3640 char * const argv[])
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003641{
3642 int i, k;
3643 int rcode = 0;
3644 struct variables *cur;
3645
3646 if (argc == 1) { /* Print all env variables */
3647 for (cur = top_vars; cur; cur = cur->next) {
3648 printf ("%s=%s\n", cur->name, cur->value);
3649 if (ctrlc ()) {
3650 puts ("\n ** Abort\n");
3651 return 1;
3652 }
3653 }
3654 return 0;
3655 }
3656 for (i = 1; i < argc; ++i) { /* print single env variables */
3657 char *name = argv[i];
3658
3659 k = -1;
3660 for (cur = top_vars; cur; cur = cur->next) {
3661 if(strcmp (cur->name, name) == 0) {
3662 k = 0;
3663 printf ("%s=%s\n", cur->name, cur->value);
3664 }
3665 if (ctrlc ()) {
3666 puts ("\n ** Abort\n");
3667 return 1;
3668 }
3669 }
3670 if (k < 0) {
3671 printf ("## Error: \"%s\" not defined\n", name);
3672 rcode ++;
3673 }
3674 }
3675 return rcode;
3676}
3677
3678U_BOOT_CMD(
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02003679 showvar, CONFIG_SYS_MAXARGS, 1, do_showvar,
Peter Tyserdfb72b82009-01-27 18:03:12 -06003680 "print local hushshell variables",
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003681 "\n - print values of all hushshell variables\n"
3682 "showvar name ...\n"
Wolfgang Denkc54781c2009-05-24 17:06:54 +02003683 " - print value of hushshell variable 'name'"
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003684);
3685
3686#endif
wdenkfe8c2802002-11-03 00:38:21 +00003687/****************************************************************************/