blob: cbaf22e9129a7078a0912067e92c536b84eadd87 [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 */
Simon Glassa73bda42015-11-08 23:47:45 -070082#include <console.h>
Simon Glass399ed9a2014-04-10 20:01:30 -060083#include <bootretry.h>
Simon Glassdec3c012014-04-10 20:01:25 -060084#include <cli.h>
Simon Glass299f0be2014-04-10 20:01:24 -060085#include <cli_hush.h>
wdenkfe8c2802002-11-03 00:38:21 +000086#include <command.h> /* find_cmd */
Tom Rini584c0ea2012-06-19 15:54:35 -070087#ifndef CONFIG_SYS_PROMPT_HUSH_PS2
88#define CONFIG_SYS_PROMPT_HUSH_PS2 "> "
89#endif
wdenkfe8c2802002-11-03 00:38:21 +000090#endif
wdenkfe8c2802002-11-03 00:38:21 +000091#ifndef __U_BOOT__
92#include <ctype.h> /* isalpha, isdigit */
93#include <unistd.h> /* getpid */
94#include <stdlib.h> /* getenv, atoi */
95#include <string.h> /* strchr */
96#include <stdio.h> /* popen etc. */
97#include <glob.h> /* glob, of course */
98#include <stdarg.h> /* va_list */
99#include <errno.h>
100#include <fcntl.h>
101#include <getopt.h> /* should be pretty obvious */
102
103#include <sys/stat.h> /* ulimit */
104#include <sys/types.h>
105#include <sys/wait.h>
106#include <signal.h>
107
108/* #include <dmalloc.h> */
wdenkfe8c2802002-11-03 00:38:21 +0000109
wdenke7f34c62003-01-11 09:48:40 +0000110#if 1
wdenkfe8c2802002-11-03 00:38:21 +0000111#include "busybox.h"
112#include "cmdedit.h"
113#else
114#define applet_name "hush"
115#include "standalone.h"
116#define hush_main main
wdenke7f34c62003-01-11 09:48:40 +0000117#undef CONFIG_FEATURE_SH_FANCY_PROMPT
118#define BB_BANNER
wdenkfe8c2802002-11-03 00:38:21 +0000119#endif
120#endif
121#define SPECIAL_VAR_SYMBOL 03
Joe Hershberger38de0b62012-08-17 10:26:30 +0000122#define SUBSTED_VAR_SYMBOL 04
wdenkfe8c2802002-11-03 00:38:21 +0000123#ifndef __U_BOOT__
124#define FLAG_EXIT_FROM_LOOP 1
125#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
126#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
127
128#endif
129
130#ifdef __U_BOOT__
Wolfgang Denk6405a152006-03-31 18:32:53 +0200131DECLARE_GLOBAL_DATA_PTR;
132
wdenkfe8c2802002-11-03 00:38:21 +0000133#define EXIT_SUCCESS 0
134#define EOF -1
135#define syntax() syntax_err()
136#define xstrdup strdup
137#define error_msg printf
138#else
139typedef enum {
140 REDIRECT_INPUT = 1,
141 REDIRECT_OVERWRITE = 2,
142 REDIRECT_APPEND = 3,
143 REDIRECT_HEREIS = 4,
144 REDIRECT_IO = 5
145} redir_type;
146
147/* The descrip member of this structure is only used to make debugging
148 * output pretty */
149struct {int mode; int default_fd; char *descrip;} redir_table[] = {
150 { 0, 0, "()" },
151 { O_RDONLY, 0, "<" },
152 { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
153 { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
154 { O_RDONLY, -1, "<<" },
155 { O_RDWR, 1, "<>" }
156};
157#endif
158
159typedef enum {
160 PIPE_SEQ = 1,
161 PIPE_AND = 2,
162 PIPE_OR = 3,
163 PIPE_BG = 4,
164} pipe_style;
165
166/* might eventually control execution */
167typedef enum {
168 RES_NONE = 0,
169 RES_IF = 1,
170 RES_THEN = 2,
171 RES_ELIF = 3,
172 RES_ELSE = 4,
173 RES_FI = 5,
174 RES_FOR = 6,
175 RES_WHILE = 7,
176 RES_UNTIL = 8,
177 RES_DO = 9,
178 RES_DONE = 10,
179 RES_XXXX = 11,
180 RES_IN = 12,
181 RES_SNTX = 13
182} reserved_style;
183#define FLAG_END (1<<RES_NONE)
184#define FLAG_IF (1<<RES_IF)
185#define FLAG_THEN (1<<RES_THEN)
186#define FLAG_ELIF (1<<RES_ELIF)
187#define FLAG_ELSE (1<<RES_ELSE)
188#define FLAG_FI (1<<RES_FI)
189#define FLAG_FOR (1<<RES_FOR)
190#define FLAG_WHILE (1<<RES_WHILE)
191#define FLAG_UNTIL (1<<RES_UNTIL)
192#define FLAG_DO (1<<RES_DO)
193#define FLAG_DONE (1<<RES_DONE)
194#define FLAG_IN (1<<RES_IN)
195#define FLAG_START (1<<RES_XXXX)
196
197/* This holds pointers to the various results of parsing */
198struct p_context {
199 struct child_prog *child;
200 struct pipe *list_head;
201 struct pipe *pipe;
202#ifndef __U_BOOT__
203 struct redir_struct *pending_redirect;
204#endif
205 reserved_style w;
206 int old_flag; /* for figuring out valid reserved words */
207 struct p_context *stack;
208 int type; /* define type of parser : ";$" common or special symbol */
209 /* How about quoting status? */
210};
211
212#ifndef __U_BOOT__
213struct redir_struct {
214 redir_type type; /* type of redirection */
215 int fd; /* file descriptor being redirected */
216 int dup; /* -1, or file descriptor being duplicated */
217 struct redir_struct *next; /* pointer to the next redirect in the list */
218 glob_t word; /* *word.gl_pathv is the filename */
219};
220#endif
221
222struct child_prog {
223#ifndef __U_BOOT__
224 pid_t pid; /* 0 if exited */
225#endif
226 char **argv; /* program name and arguments */
Stephen Warren60c38c92014-03-01 22:16:10 -0700227 /* was quoted when parsed; copy of struct o_string.nonnull field */
Simon Glass299f0be2014-04-10 20:01:24 -0600228 int *argv_nonnull;
wdenkfe8c2802002-11-03 00:38:21 +0000229#ifdef __U_BOOT__
230 int argc; /* number of program arguments */
231#endif
232 struct pipe *group; /* if non-NULL, first in group or subshell */
233#ifndef __U_BOOT__
234 int subshell; /* flag, non-zero if group must be forked */
235 struct redir_struct *redirects; /* I/O redirections */
236 glob_t glob_result; /* result of parameter globbing */
237 int is_stopped; /* is the program currently running? */
238 struct pipe *family; /* pointer back to the child's parent pipe */
239#endif
240 int sp; /* number of SPECIAL_VAR_SYMBOL */
241 int type;
242};
243
244struct pipe {
245#ifndef __U_BOOT__
246 int jobid; /* job number */
247#endif
248 int num_progs; /* total number of programs in job */
249#ifndef __U_BOOT__
250 int running_progs; /* number of programs running */
251 char *text; /* name of job */
252 char *cmdbuf; /* buffer various argv's point into */
253 pid_t pgrp; /* process group ID for the job */
254#endif
255 struct child_prog *progs; /* array of commands in pipe */
256 struct pipe *next; /* to track background commands */
257#ifndef __U_BOOT__
258 int stopped_progs; /* number of programs alive, but stopped */
259 int job_context; /* bitmask defining current context */
260#endif
261 pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
262 reserved_style r_mode; /* supports if, for, while, until */
263};
264
265#ifndef __U_BOOT__
266struct close_me {
267 int fd;
268 struct close_me *next;
269};
270#endif
271
272struct variables {
273 char *name;
274 char *value;
275 int flg_export;
276 int flg_read_only;
277 struct variables *next;
278};
279
280/* globals, connect us to the outside world
281 * the first three support $?, $#, and $1 */
282#ifndef __U_BOOT__
283char **global_argv;
284unsigned int global_argc;
285#endif
Kim Phillipsb052b602012-10-29 13:34:32 +0000286static unsigned int last_return_code;
wdenkfe8c2802002-11-03 00:38:21 +0000287#ifndef __U_BOOT__
288extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
289#endif
290
291/* "globals" within this file */
Wolfgang Denk7fb52662005-10-13 16:45:02 +0200292static uchar *ifs;
wdenkfe8c2802002-11-03 00:38:21 +0000293static char map[256];
294#ifndef __U_BOOT__
295static int fake_mode;
296static int interactive;
297static struct close_me *close_me_head;
298static const char *cwd;
299static struct pipe *job_list;
300static unsigned int last_bg_pid;
301static unsigned int last_jobid;
302static unsigned int shell_terminal;
303static char *PS1;
304static char *PS2;
305struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
306struct variables *top_vars = &shell_ver;
307#else
308static int flag_repeat = 0;
309static int do_repeat = 0;
wdenkbd1575f2003-10-14 19:43:55 +0000310static struct variables *top_vars = NULL ;
wdenkfe8c2802002-11-03 00:38:21 +0000311#endif /*__U_BOOT__ */
312
313#define B_CHUNK (100)
314#define B_NOSPAC 1
315
316typedef struct {
317 char *data;
318 int length;
319 int maxlen;
320 int quote;
321 int nonnull;
322} o_string;
323#define NULL_O_STRING {NULL,0,0,0,0}
324/* used for initialization:
325 o_string foo = NULL_O_STRING; */
326
327/* I can almost use ordinary FILE *. Is open_memstream() universally
328 * available? Where is it documented? */
329struct in_str {
330 const char *p;
331#ifndef __U_BOOT__
332 char peek_buf[2];
333#endif
334 int __promptme;
335 int promptmode;
336#ifndef __U_BOOT__
337 FILE *file;
338#endif
339 int (*get) (struct in_str *);
340 int (*peek) (struct in_str *);
341};
342#define b_getch(input) ((input)->get(input))
343#define b_peek(input) ((input)->peek(input))
344
345#ifndef __U_BOOT__
346#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
347
348struct built_in_command {
349 char *cmd; /* name */
350 char *descr; /* description */
351 int (*function) (struct child_prog *); /* function ptr */
352};
353#endif
354
Stefan Roesec23634d2008-08-19 14:57:55 +0200355/* define DEBUG_SHELL for debugging output (obviously ;-)) */
356#if 0
357#define DEBUG_SHELL
358#endif
359
wdenkfe8c2802002-11-03 00:38:21 +0000360/* This should be in utility.c */
361#ifdef DEBUG_SHELL
362#ifndef __U_BOOT__
363static void debug_printf(const char *format, ...)
364{
365 va_list args;
366 va_start(args, format);
367 vfprintf(stderr, format, args);
368 va_end(args);
369}
370#else
Stefan Roesec23634d2008-08-19 14:57:55 +0200371#define debug_printf(fmt,args...) printf (fmt ,##args)
wdenkfe8c2802002-11-03 00:38:21 +0000372#endif
373#else
374static inline void debug_printf(const char *format, ...) { }
375#endif
376#define final_printf debug_printf
377
378#ifdef __U_BOOT__
379static void syntax_err(void) {
380 printf("syntax error\n");
381}
382#else
383static void __syntax(char *file, int line) {
384 error_msg("syntax error %s:%d", file, line);
385}
386#define syntax() __syntax(__FILE__, __LINE__)
387#endif
388
389#ifdef __U_BOOT__
390static void *xmalloc(size_t size);
391static void *xrealloc(void *ptr, size_t size);
392#else
393/* Index of subroutines: */
394/* function prototypes for builtins */
395static int builtin_cd(struct child_prog *child);
396static int builtin_env(struct child_prog *child);
397static int builtin_eval(struct child_prog *child);
398static int builtin_exec(struct child_prog *child);
399static int builtin_exit(struct child_prog *child);
400static int builtin_export(struct child_prog *child);
401static int builtin_fg_bg(struct child_prog *child);
402static int builtin_help(struct child_prog *child);
403static int builtin_jobs(struct child_prog *child);
404static int builtin_pwd(struct child_prog *child);
405static int builtin_read(struct child_prog *child);
406static int builtin_set(struct child_prog *child);
407static int builtin_shift(struct child_prog *child);
408static int builtin_source(struct child_prog *child);
409static int builtin_umask(struct child_prog *child);
410static int builtin_unset(struct child_prog *child);
411static int builtin_not_written(struct child_prog *child);
412#endif
413/* o_string manipulation: */
414static int b_check_space(o_string *o, int len);
415static int b_addchr(o_string *o, int ch);
416static void b_reset(o_string *o);
417static int b_addqchr(o_string *o, int ch, int quote);
wdenk6203e402004-04-18 10:13:26 +0000418#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +0000419static int b_adduint(o_string *o, unsigned int i);
wdenk6203e402004-04-18 10:13:26 +0000420#endif
wdenkfe8c2802002-11-03 00:38:21 +0000421/* in_str manipulations: */
422static int static_get(struct in_str *i);
423static int static_peek(struct in_str *i);
424static int file_get(struct in_str *i);
425static int file_peek(struct in_str *i);
426#ifndef __U_BOOT__
427static void setup_file_in_str(struct in_str *i, FILE *f);
428#else
429static void setup_file_in_str(struct in_str *i);
430#endif
431static void setup_string_in_str(struct in_str *i, const char *s);
432#ifndef __U_BOOT__
433/* close_me manipulations: */
434static void mark_open(int fd);
435static void mark_closed(int fd);
wdenke7f34c62003-01-11 09:48:40 +0000436static void close_all(void);
wdenkfe8c2802002-11-03 00:38:21 +0000437#endif
438/* "run" the final data structures: */
439static char *indenter(int i);
440static int free_pipe_list(struct pipe *head, int indent);
441static int free_pipe(struct pipe *pi, int indent);
442/* really run the final data structures: */
443#ifndef __U_BOOT__
444static int setup_redirects(struct child_prog *prog, int squirrel[]);
445#endif
446static int run_list_real(struct pipe *pi);
447#ifndef __U_BOOT__
448static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
449#endif
450static int run_pipe_real(struct pipe *pi);
451/* extended glob support: */
452#ifndef __U_BOOT__
453static int globhack(const char *src, int flags, glob_t *pglob);
454static int glob_needed(const char *s);
455static int xglob(o_string *dest, int flags, glob_t *pglob);
456#endif
457/* variable assignment: */
458static int is_assignment(const char *s);
459/* data structure manipulation: */
460#ifndef __U_BOOT__
461static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
462#endif
463static void initialize_context(struct p_context *ctx);
464static int done_word(o_string *dest, struct p_context *ctx);
465static int done_command(struct p_context *ctx);
466static int done_pipe(struct p_context *ctx, pipe_style type);
467/* primary string parsing: */
468#ifndef __U_BOOT__
469static int redirect_dup_num(struct in_str *input);
470static int redirect_opt_num(o_string *o);
471static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
472static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
473#endif
474static char *lookup_param(char *src);
Stephen Warren60c38c92014-03-01 22:16:10 -0700475static char *make_string(char **inp, int *nonnull);
wdenkfe8c2802002-11-03 00:38:21 +0000476static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
477#ifndef __U_BOOT__
478static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
479#endif
480static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
481/* setup: */
482static int parse_stream_outer(struct in_str *inp, int flag);
483#ifndef __U_BOOT__
484static int parse_string_outer(const char *s, int flag);
485static int parse_file_outer(FILE *f);
486#endif
487#ifndef __U_BOOT__
488/* job management: */
489static int checkjobs(struct pipe* fg_pipe);
490static void insert_bg_job(struct pipe *pi);
491static void remove_bg_job(struct pipe *pi);
492#endif
493/* local variable support */
494static char **make_list_in(char **inp, char *name);
495static char *insert_var_value(char *inp);
Joe Hershberger38de0b62012-08-17 10:26:30 +0000496static char *insert_var_value_sub(char *inp, int tag_subst);
wdenkfe8c2802002-11-03 00:38:21 +0000497
498#ifndef __U_BOOT__
499/* Table of built-in functions. They can be forked or not, depending on
500 * context: within pipes, they fork. As simple commands, they do not.
501 * When used in non-forking context, they can change global variables
502 * in the parent shell process. If forked, of course they can not.
503 * For example, 'unset foo | whatever' will parse and run, but foo will
504 * still be set at the end. */
505static struct built_in_command bltins[] = {
506 {"bg", "Resume a job in the background", builtin_fg_bg},
507 {"break", "Exit for, while or until loop", builtin_not_written},
508 {"cd", "Change working directory", builtin_cd},
509 {"continue", "Continue for, while or until loop", builtin_not_written},
510 {"env", "Print all environment variables", builtin_env},
511 {"eval", "Construct and run shell command", builtin_eval},
512 {"exec", "Exec command, replacing this shell with the exec'd process",
513 builtin_exec},
514 {"exit", "Exit from shell()", builtin_exit},
515 {"export", "Set environment variable", builtin_export},
516 {"fg", "Bring job into the foreground", builtin_fg_bg},
517 {"jobs", "Lists the active jobs", builtin_jobs},
518 {"pwd", "Print current directory", builtin_pwd},
519 {"read", "Input environment variable", builtin_read},
520 {"return", "Return from a function", builtin_not_written},
521 {"set", "Set/unset shell local variables", builtin_set},
522 {"shift", "Shift positional parameters", builtin_shift},
523 {"trap", "Trap signals", builtin_not_written},
524 {"ulimit","Controls resource limits", builtin_not_written},
525 {"umask","Sets file creation mask", builtin_umask},
526 {"unset", "Unset environment variable", builtin_unset},
527 {".", "Source-in and run commands in a file", builtin_source},
528 {"help", "List shell built-in commands", builtin_help},
529 {NULL, NULL, NULL}
530};
531
532static const char *set_cwd(void)
533{
534 if(cwd==unknown)
535 cwd = NULL; /* xgetcwd(arg) called free(arg) */
536 cwd = xgetcwd((char *)cwd);
537 if (!cwd)
538 cwd = unknown;
539 return cwd;
540}
541
542/* built-in 'eval' handler */
543static int builtin_eval(struct child_prog *child)
544{
545 char *str = NULL;
546 int rcode = EXIT_SUCCESS;
547
548 if (child->argv[1]) {
549 str = make_string(child->argv + 1);
550 parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
551 FLAG_PARSE_SEMICOLON);
552 free(str);
553 rcode = last_return_code;
554 }
555 return rcode;
556}
557
558/* built-in 'cd <path>' handler */
559static int builtin_cd(struct child_prog *child)
560{
561 char *newdir;
562 if (child->argv[1] == NULL)
563 newdir = getenv("HOME");
564 else
565 newdir = child->argv[1];
566 if (chdir(newdir)) {
567 printf("cd: %s: %s\n", newdir, strerror(errno));
568 return EXIT_FAILURE;
569 }
570 set_cwd();
571 return EXIT_SUCCESS;
572}
573
574/* built-in 'env' handler */
575static int builtin_env(struct child_prog *dummy)
576{
577 char **e = environ;
578 if (e == NULL) return EXIT_FAILURE;
579 for (; *e; e++) {
580 puts(*e);
581 }
582 return EXIT_SUCCESS;
583}
584
585/* built-in 'exec' handler */
586static int builtin_exec(struct child_prog *child)
587{
588 if (child->argv[1] == NULL)
589 return EXIT_SUCCESS; /* Really? */
590 child->argv++;
591 pseudo_exec(child);
592 /* never returns */
593}
594
595/* built-in 'exit' handler */
596static int builtin_exit(struct child_prog *child)
597{
598 if (child->argv[1] == NULL)
599 exit(last_return_code);
600 exit (atoi(child->argv[1]));
601}
602
603/* built-in 'export VAR=value' handler */
604static int builtin_export(struct child_prog *child)
605{
606 int res = 0;
607 char *name = child->argv[1];
608
609 if (name == NULL) {
610 return (builtin_env(child));
611 }
612
613 name = strdup(name);
614
615 if(name) {
616 char *value = strchr(name, '=');
617
618 if (!value) {
619 char *tmp;
620 /* They are exporting something without an =VALUE */
621
622 value = get_local_var(name);
623 if (value) {
624 size_t ln = strlen(name);
625
626 tmp = realloc(name, ln+strlen(value)+2);
627 if(tmp==NULL)
628 res = -1;
629 else {
630 sprintf(tmp+ln, "=%s", value);
631 name = tmp;
632 }
633 } else {
634 /* bash does not return an error when trying to export
635 * an undefined variable. Do likewise. */
636 res = 1;
637 }
638 }
639 }
640 if (res<0)
641 perror_msg("export");
642 else if(res==0)
643 res = set_local_var(name, 1);
644 else
645 res = 0;
646 free(name);
647 return res;
648}
649
650/* built-in 'fg' and 'bg' handler */
651static int builtin_fg_bg(struct child_prog *child)
652{
653 int i, jobnum;
654 struct pipe *pi=NULL;
655
656 if (!interactive)
657 return EXIT_FAILURE;
658 /* If they gave us no args, assume they want the last backgrounded task */
659 if (!child->argv[1]) {
660 for (pi = job_list; pi; pi = pi->next) {
661 if (pi->jobid == last_jobid) {
662 break;
663 }
664 }
665 if (!pi) {
666 error_msg("%s: no current job", child->argv[0]);
667 return EXIT_FAILURE;
668 }
669 } else {
670 if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
671 error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
672 return EXIT_FAILURE;
673 }
674 for (pi = job_list; pi; pi = pi->next) {
675 if (pi->jobid == jobnum) {
676 break;
677 }
678 }
679 if (!pi) {
680 error_msg("%s: %d: no such job", child->argv[0], jobnum);
681 return EXIT_FAILURE;
682 }
683 }
684
685 if (*child->argv[0] == 'f') {
686 /* Put the job into the foreground. */
687 tcsetpgrp(shell_terminal, pi->pgrp);
688 }
689
690 /* Restart the processes in the job */
691 for (i = 0; i < pi->num_progs; i++)
692 pi->progs[i].is_stopped = 0;
693
694 if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) {
695 if (i == ESRCH) {
696 remove_bg_job(pi);
697 } else {
698 perror_msg("kill (SIGCONT)");
699 }
700 }
701
702 pi->stopped_progs = 0;
703 return EXIT_SUCCESS;
704}
705
706/* built-in 'help' handler */
707static int builtin_help(struct child_prog *dummy)
708{
709 struct built_in_command *x;
710
711 printf("\nBuilt-in commands:\n");
712 printf("-------------------\n");
713 for (x = bltins; x->cmd; x++) {
714 if (x->descr==NULL)
715 continue;
716 printf("%s\t%s\n", x->cmd, x->descr);
717 }
718 printf("\n\n");
719 return EXIT_SUCCESS;
720}
721
722/* built-in 'jobs' handler */
723static int builtin_jobs(struct child_prog *child)
724{
725 struct pipe *job;
726 char *status_string;
727
728 for (job = job_list; job; job = job->next) {
729 if (job->running_progs == job->stopped_progs)
730 status_string = "Stopped";
731 else
732 status_string = "Running";
733
734 printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
735 }
736 return EXIT_SUCCESS;
737}
738
739
740/* built-in 'pwd' handler */
741static int builtin_pwd(struct child_prog *dummy)
742{
743 puts(set_cwd());
744 return EXIT_SUCCESS;
745}
746
747/* built-in 'read VAR' handler */
748static int builtin_read(struct child_prog *child)
749{
750 int res;
751
752 if (child->argv[1]) {
753 char string[BUFSIZ];
754 char *var = 0;
755
756 string[0] = 0; /* In case stdin has only EOF */
757 /* read string */
758 fgets(string, sizeof(string), stdin);
759 chomp(string);
760 var = malloc(strlen(child->argv[1])+strlen(string)+2);
761 if(var) {
762 sprintf(var, "%s=%s", child->argv[1], string);
763 res = set_local_var(var, 0);
764 } else
765 res = -1;
766 if (res)
767 fprintf(stderr, "read: %m\n");
768 free(var); /* So not move up to avoid breaking errno */
769 return res;
770 } else {
771 do res=getchar(); while(res!='\n' && res!=EOF);
772 return 0;
773 }
774}
775
776/* built-in 'set VAR=value' handler */
777static int builtin_set(struct child_prog *child)
778{
779 char *temp = child->argv[1];
780 struct variables *e;
781
782 if (temp == NULL)
783 for(e = top_vars; e; e=e->next)
784 printf("%s=%s\n", e->name, e->value);
785 else
786 set_local_var(temp, 0);
787
788 return EXIT_SUCCESS;
789}
790
791
792/* Built-in 'shift' handler */
793static int builtin_shift(struct child_prog *child)
794{
795 int n=1;
796 if (child->argv[1]) {
797 n=atoi(child->argv[1]);
798 }
799 if (n>=0 && n<global_argc) {
800 /* XXX This probably breaks $0 */
801 global_argc -= n;
802 global_argv += n;
803 return EXIT_SUCCESS;
804 } else {
805 return EXIT_FAILURE;
806 }
807}
808
809/* Built-in '.' handler (read-in and execute commands from file) */
810static int builtin_source(struct child_prog *child)
811{
812 FILE *input;
813 int status;
814
815 if (child->argv[1] == NULL)
816 return EXIT_FAILURE;
817
818 /* XXX search through $PATH is missing */
819 input = fopen(child->argv[1], "r");
820 if (!input) {
821 error_msg("Couldn't open file '%s'", child->argv[1]);
822 return EXIT_FAILURE;
823 }
824
825 /* Now run the file */
826 /* XXX argv and argc are broken; need to save old global_argv
827 * (pointer only is OK!) on this stack frame,
828 * set global_argv=child->argv+1, recurse, and restore. */
829 mark_open(fileno(input));
830 status = parse_file_outer(input);
831 mark_closed(fileno(input));
832 fclose(input);
833 return (status);
834}
835
836static int builtin_umask(struct child_prog *child)
837{
838 mode_t new_umask;
839 const char *arg = child->argv[1];
840 char *end;
841 if (arg) {
842 new_umask=strtoul(arg, &end, 8);
843 if (*end!='\0' || end == arg) {
844 return EXIT_FAILURE;
845 }
846 } else {
847 printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
848 }
849 umask(new_umask);
850 return EXIT_SUCCESS;
851}
852
853/* built-in 'unset VAR' handler */
854static int builtin_unset(struct child_prog *child)
855{
856 /* bash returned already true */
857 unset_local_var(child->argv[1]);
858 return EXIT_SUCCESS;
859}
860
861static int builtin_not_written(struct child_prog *child)
862{
863 printf("builtin_%s not written\n",child->argv[0]);
864 return EXIT_FAILURE;
865}
866#endif
867
868static int b_check_space(o_string *o, int len)
869{
870 /* It would be easy to drop a more restrictive policy
871 * in here, such as setting a maximum string length */
872 if (o->length + len > o->maxlen) {
873 char *old_data = o->data;
874 /* assert (data == NULL || o->maxlen != 0); */
875 o->maxlen += max(2*len, B_CHUNK);
876 o->data = realloc(o->data, 1 + o->maxlen);
877 if (o->data == NULL) {
878 free(old_data);
879 }
880 }
881 return o->data == NULL;
882}
883
884static int b_addchr(o_string *o, int ch)
885{
886 debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
887 if (b_check_space(o, 1)) return B_NOSPAC;
888 o->data[o->length] = ch;
889 o->length++;
890 o->data[o->length] = '\0';
891 return 0;
892}
893
894static void b_reset(o_string *o)
895{
896 o->length = 0;
897 o->nonnull = 0;
898 if (o->data != NULL) *o->data = '\0';
899}
900
901static void b_free(o_string *o)
902{
903 b_reset(o);
wdenke7f34c62003-01-11 09:48:40 +0000904 free(o->data);
wdenkfe8c2802002-11-03 00:38:21 +0000905 o->data = NULL;
906 o->maxlen = 0;
907}
908
909/* My analysis of quoting semantics tells me that state information
910 * is associated with a destination, not a source.
911 */
912static int b_addqchr(o_string *o, int ch, int quote)
913{
914 if (quote && strchr("*?[\\",ch)) {
915 int rc;
916 rc = b_addchr(o, '\\');
917 if (rc) return rc;
918 }
919 return b_addchr(o, ch);
920}
921
wdenk6203e402004-04-18 10:13:26 +0000922#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +0000923static int b_adduint(o_string *o, unsigned int i)
924{
925 int r;
926 char *p = simple_itoa(i);
927 /* no escape checking necessary */
928 do r=b_addchr(o, *p++); while (r==0 && *p);
929 return r;
930}
wdenk6203e402004-04-18 10:13:26 +0000931#endif
wdenkfe8c2802002-11-03 00:38:21 +0000932
933static int static_get(struct in_str *i)
934{
Wolfgang Denkdc770c72008-07-14 15:19:07 +0200935 int ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +0000936 if (ch=='\0') return EOF;
937 return ch;
938}
939
940static int static_peek(struct in_str *i)
941{
942 return *i->p;
943}
944
945#ifndef __U_BOOT__
946static inline void cmdedit_set_initial_prompt(void)
947{
wdenke7f34c62003-01-11 09:48:40 +0000948#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
wdenkfe8c2802002-11-03 00:38:21 +0000949 PS1 = NULL;
950#else
951 PS1 = getenv("PS1");
952 if(PS1==0)
953 PS1 = "\\w \\$ ";
954#endif
955}
956
957static inline void setup_prompt_string(int promptmode, char **prompt_str)
958{
959 debug_printf("setup_prompt_string %d ",promptmode);
wdenke7f34c62003-01-11 09:48:40 +0000960#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
wdenkfe8c2802002-11-03 00:38:21 +0000961 /* Set up the prompt */
962 if (promptmode == 1) {
wdenke7f34c62003-01-11 09:48:40 +0000963 free(PS1);
wdenkfe8c2802002-11-03 00:38:21 +0000964 PS1=xmalloc(strlen(cwd)+4);
965 sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
966 *prompt_str = PS1;
967 } else {
968 *prompt_str = PS2;
969 }
970#else
971 *prompt_str = (promptmode==1)? PS1 : PS2;
972#endif
973 debug_printf("result %s\n",*prompt_str);
974}
975#endif
976
Marek Vasut755e12d2016-01-27 04:47:54 +0100977#ifdef __U_BOOT__
978static int uboot_cli_readline(struct in_str *i)
979{
980 char *prompt;
981
982 if (i->promptmode == 1)
983 prompt = CONFIG_SYS_PROMPT;
984 else
985 prompt = CONFIG_SYS_PROMPT_HUSH_PS2;
986
987 return cli_readline(prompt);
988}
989#endif
990
wdenkfe8c2802002-11-03 00:38:21 +0000991static void get_user_input(struct in_str *i)
992{
993#ifndef __U_BOOT__
994 char *prompt_str;
995 static char the_command[BUFSIZ];
996
997 setup_prompt_string(i->promptmode, &prompt_str);
wdenke7f34c62003-01-11 09:48:40 +0000998#ifdef CONFIG_FEATURE_COMMAND_EDITING
wdenkfe8c2802002-11-03 00:38:21 +0000999 /*
1000 ** enable command line editing only while a command line
1001 ** is actually being read; otherwise, we'll end up bequeathing
1002 ** atexit() handlers and other unwanted stuff to our
1003 ** child processes (rob@sysgo.de)
1004 */
1005 cmdedit_read_input(prompt_str, the_command);
1006#else
1007 fputs(prompt_str, stdout);
1008 fflush(stdout);
1009 the_command[0]=fgetc(i->file);
1010 the_command[1]='\0';
1011#endif
1012 fflush(stdout);
1013 i->p = the_command;
1014#else
wdenkfe8c2802002-11-03 00:38:21 +00001015 int n;
Kristian Otnes2a262cd2014-04-25 15:35:43 +02001016 static char the_command[CONFIG_SYS_CBSIZE + 1];
wdenkfe8c2802002-11-03 00:38:21 +00001017
Simon Glass09007c42014-04-10 20:01:31 -06001018 bootretry_reset_cmd_timeout();
wdenkfe8c2802002-11-03 00:38:21 +00001019 i->__promptme = 1;
Marek Vasut755e12d2016-01-27 04:47:54 +01001020 n = uboot_cli_readline(i);
1021
Wolfgang Denk2b7976a2005-08-12 23:34:51 +02001022#ifdef CONFIG_BOOT_RETRY_TIME
1023 if (n == -2) {
1024 puts("\nTimeout waiting for command\n");
1025# ifdef CONFIG_RESET_TO_RETRY
1026 do_reset(NULL, 0, 0, NULL);
1027# else
1028# error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
1029# endif
1030 }
1031#endif
wdenkfe8c2802002-11-03 00:38:21 +00001032 if (n == -1 ) {
1033 flag_repeat = 0;
1034 i->__promptme = 0;
1035 }
1036 n = strlen(console_buffer);
1037 console_buffer[n] = '\n';
1038 console_buffer[n+1]= '\0';
1039 if (had_ctrlc()) flag_repeat = 0;
1040 clear_ctrlc();
1041 do_repeat = 0;
1042 if (i->promptmode == 1) {
1043 if (console_buffer[0] == '\n'&& flag_repeat == 0) {
1044 strcpy(the_command,console_buffer);
1045 }
1046 else {
1047 if (console_buffer[0] != '\n') {
1048 strcpy(the_command,console_buffer);
1049 flag_repeat = 1;
1050 }
1051 else {
1052 do_repeat = 1;
1053 }
1054 }
1055 i->p = the_command;
1056 }
1057 else {
wdenk57b2d802003-06-27 21:31:46 +00001058 if (console_buffer[0] != '\n') {
1059 if (strlen(the_command) + strlen(console_buffer)
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02001060 < CONFIG_SYS_CBSIZE) {
wdenk57b2d802003-06-27 21:31:46 +00001061 n = strlen(the_command);
1062 the_command[n-1] = ' ';
1063 strcpy(&the_command[n],console_buffer);
wdenkfe8c2802002-11-03 00:38:21 +00001064 }
1065 else {
1066 the_command[0] = '\n';
1067 the_command[1] = '\0';
1068 flag_repeat = 0;
1069 }
1070 }
1071 if (i->__promptme == 0) {
1072 the_command[0] = '\n';
1073 the_command[1] = '\0';
1074 }
1075 i->p = console_buffer;
1076 }
1077#endif
1078}
1079
1080/* This is the magic location that prints prompts
1081 * and gets data back from the user */
1082static int file_get(struct in_str *i)
1083{
1084 int ch;
1085
1086 ch = 0;
1087 /* If there is data waiting, eat it up */
1088 if (i->p && *i->p) {
Wolfgang Denkdc770c72008-07-14 15:19:07 +02001089 ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +00001090 } else {
1091 /* need to double check i->file because we might be doing something
1092 * more complicated by now, like sourcing or substituting. */
1093#ifndef __U_BOOT__
1094 if (i->__promptme && interactive && i->file == stdin) {
1095 while(! i->p || (interactive && strlen(i->p)==0) ) {
1096#else
1097 while(! i->p || strlen(i->p)==0 ) {
1098#endif
1099 get_user_input(i);
1100 }
1101 i->promptmode=2;
1102#ifndef __U_BOOT__
1103 i->__promptme = 0;
1104#endif
1105 if (i->p && *i->p) {
Wolfgang Denkdc770c72008-07-14 15:19:07 +02001106 ch = *i->p++;
wdenkfe8c2802002-11-03 00:38:21 +00001107 }
1108#ifndef __U_BOOT__
1109 } else {
1110 ch = fgetc(i->file);
1111 }
1112
1113#endif
1114 debug_printf("b_getch: got a %d\n", ch);
1115 }
1116#ifndef __U_BOOT__
1117 if (ch == '\n') i->__promptme=1;
1118#endif
1119 return ch;
1120}
1121
1122/* All the callers guarantee this routine will never be
1123 * used right after a newline, so prompting is not needed.
1124 */
1125static int file_peek(struct in_str *i)
1126{
1127#ifndef __U_BOOT__
1128 if (i->p && *i->p) {
1129#endif
1130 return *i->p;
1131#ifndef __U_BOOT__
1132 } else {
1133 i->peek_buf[0] = fgetc(i->file);
1134 i->peek_buf[1] = '\0';
1135 i->p = i->peek_buf;
1136 debug_printf("b_peek: got a %d\n", *i->p);
1137 return *i->p;
1138 }
1139#endif
1140}
1141
1142#ifndef __U_BOOT__
1143static void setup_file_in_str(struct in_str *i, FILE *f)
1144#else
1145static void setup_file_in_str(struct in_str *i)
1146#endif
1147{
1148 i->peek = file_peek;
1149 i->get = file_get;
1150 i->__promptme=1;
1151 i->promptmode=1;
1152#ifndef __U_BOOT__
1153 i->file = f;
1154#endif
1155 i->p = NULL;
1156}
1157
1158static void setup_string_in_str(struct in_str *i, const char *s)
1159{
1160 i->peek = static_peek;
1161 i->get = static_get;
1162 i->__promptme=1;
1163 i->promptmode=1;
1164 i->p = s;
1165}
1166
1167#ifndef __U_BOOT__
1168static void mark_open(int fd)
1169{
1170 struct close_me *new = xmalloc(sizeof(struct close_me));
1171 new->fd = fd;
1172 new->next = close_me_head;
1173 close_me_head = new;
1174}
1175
1176static void mark_closed(int fd)
1177{
1178 struct close_me *tmp;
1179 if (close_me_head == NULL || close_me_head->fd != fd)
1180 error_msg_and_die("corrupt close_me");
1181 tmp = close_me_head;
1182 close_me_head = close_me_head->next;
1183 free(tmp);
1184}
1185
wdenke7f34c62003-01-11 09:48:40 +00001186static void close_all(void)
wdenkfe8c2802002-11-03 00:38:21 +00001187{
1188 struct close_me *c;
1189 for (c=close_me_head; c; c=c->next) {
1190 close(c->fd);
1191 }
1192 close_me_head = NULL;
1193}
1194
1195/* squirrel != NULL means we squirrel away copies of stdin, stdout,
1196 * and stderr if they are redirected. */
1197static int setup_redirects(struct child_prog *prog, int squirrel[])
1198{
1199 int openfd, mode;
1200 struct redir_struct *redir;
1201
1202 for (redir=prog->redirects; redir; redir=redir->next) {
1203 if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
1204 /* something went wrong in the parse. Pretend it didn't happen */
1205 continue;
1206 }
1207 if (redir->dup == -1) {
1208 mode=redir_table[redir->type].mode;
1209 openfd = open(redir->word.gl_pathv[0], mode, 0666);
1210 if (openfd < 0) {
1211 /* this could get lost if stderr has been redirected, but
1212 bash and ash both lose it as well (though zsh doesn't!) */
1213 perror_msg("error opening %s", redir->word.gl_pathv[0]);
1214 return 1;
1215 }
1216 } else {
1217 openfd = redir->dup;
1218 }
1219
1220 if (openfd != redir->fd) {
1221 if (squirrel && redir->fd < 3) {
1222 squirrel[redir->fd] = dup(redir->fd);
1223 }
1224 if (openfd == -3) {
1225 close(openfd);
1226 } else {
1227 dup2(openfd, redir->fd);
1228 if (redir->dup == -1)
1229 close (openfd);
1230 }
1231 }
1232 }
1233 return 0;
1234}
1235
1236static void restore_redirects(int squirrel[])
1237{
1238 int i, fd;
1239 for (i=0; i<3; i++) {
1240 fd = squirrel[i];
1241 if (fd != -1) {
1242 /* No error checking. I sure wouldn't know what
1243 * to do with an error if I found one! */
1244 dup2(fd, i);
1245 close(fd);
1246 }
1247 }
1248}
1249
1250/* never returns */
1251/* XXX no exit() here. If you don't exec, use _exit instead.
1252 * The at_exit handlers apparently confuse the calling process,
1253 * in particular stdin handling. Not sure why? */
1254static void pseudo_exec(struct child_prog *child)
1255{
1256 int i, rcode;
1257 char *p;
1258 struct built_in_command *x;
1259 if (child->argv) {
1260 for (i=0; is_assignment(child->argv[i]); i++) {
1261 debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]);
1262 p = insert_var_value(child->argv[i]);
1263 putenv(strdup(p));
1264 if (p != child->argv[i]) free(p);
1265 }
1266 child->argv+=i; /* XXX this hack isn't so horrible, since we are about
wdenk57b2d802003-06-27 21:31:46 +00001267 to exit, and therefore don't need to keep data
1268 structures consistent for free() use. */
wdenkfe8c2802002-11-03 00:38:21 +00001269 /* If a variable is assigned in a forest, and nobody listens,
1270 * was it ever really set?
1271 */
1272 if (child->argv[0] == NULL) {
1273 _exit(EXIT_SUCCESS);
1274 }
1275
1276 /*
1277 * Check if the command matches any of the builtins.
1278 * Depending on context, this might be redundant. But it's
1279 * easier to waste a few CPU cycles than it is to figure out
1280 * if this is one of those cases.
1281 */
1282 for (x = bltins; x->cmd; x++) {
1283 if (strcmp(child->argv[0], x->cmd) == 0 ) {
1284 debug_printf("builtin exec %s\n", child->argv[0]);
1285 rcode = x->function(child);
1286 fflush(stdout);
1287 _exit(rcode);
1288 }
1289 }
1290
1291 /* Check if the command matches any busybox internal commands
1292 * ("applets") here.
1293 * FIXME: This feature is not 100% safe, since
1294 * BusyBox is not fully reentrant, so we have no guarantee the things
1295 * from the .bss are still zeroed, or that things from .data are still
1296 * at their defaults. We could exec ourself from /proc/self/exe, but I
1297 * really dislike relying on /proc for things. We could exec ourself
1298 * from global_argv[0], but if we are in a chroot, we may not be able
1299 * to find ourself... */
wdenke7f34c62003-01-11 09:48:40 +00001300#ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
wdenkfe8c2802002-11-03 00:38:21 +00001301 {
1302 int argc_l;
1303 char** argv_l=child->argv;
1304 char *name = child->argv[0];
1305
wdenke7f34c62003-01-11 09:48:40 +00001306#ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
wdenkfe8c2802002-11-03 00:38:21 +00001307 /* Following discussions from November 2000 on the busybox mailing
1308 * list, the default configuration, (without
1309 * get_last_path_component()) lets the user force use of an
1310 * external command by specifying the full (with slashes) filename.
wdenke7f34c62003-01-11 09:48:40 +00001311 * If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets
wdenkfe8c2802002-11-03 00:38:21 +00001312 * _aways_ override external commands, so if you want to run
1313 * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
1314 * filesystem and is _not_ busybox. Some systems may want this,
1315 * most do not. */
1316 name = get_last_path_component(name);
1317#endif
1318 /* Count argc for use in a second... */
1319 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
1320 optind = 1;
1321 debug_printf("running applet %s\n", name);
1322 run_applet_by_name(name, argc_l, child->argv);
1323 }
1324#endif
1325 debug_printf("exec of %s\n",child->argv[0]);
1326 execvp(child->argv[0],child->argv);
1327 perror_msg("couldn't exec: %s",child->argv[0]);
1328 _exit(1);
1329 } else if (child->group) {
1330 debug_printf("runtime nesting to group\n");
1331 interactive=0; /* crucial!!!! */
1332 rcode = run_list_real(child->group);
1333 /* OK to leak memory by not calling free_pipe_list,
1334 * since this process is about to exit */
1335 _exit(rcode);
1336 } else {
1337 /* Can happen. See what bash does with ">foo" by itself. */
1338 debug_printf("trying to pseudo_exec null command\n");
1339 _exit(EXIT_SUCCESS);
1340 }
1341}
1342
1343static void insert_bg_job(struct pipe *pi)
1344{
1345 struct pipe *thejob;
1346
1347 /* Linear search for the ID of the job to use */
1348 pi->jobid = 1;
1349 for (thejob = job_list; thejob; thejob = thejob->next)
1350 if (thejob->jobid >= pi->jobid)
1351 pi->jobid = thejob->jobid + 1;
1352
1353 /* add thejob to the list of running jobs */
1354 if (!job_list) {
1355 thejob = job_list = xmalloc(sizeof(*thejob));
1356 } else {
1357 for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */;
1358 thejob->next = xmalloc(sizeof(*thejob));
1359 thejob = thejob->next;
1360 }
1361
1362 /* physically copy the struct job */
1363 memcpy(thejob, pi, sizeof(struct pipe));
1364 thejob->next = NULL;
1365 thejob->running_progs = thejob->num_progs;
1366 thejob->stopped_progs = 0;
1367 thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
1368
1369 /*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */
1370 {
1371 char *bar=thejob->text;
1372 char **foo=pi->progs[0].argv;
1373 while(foo && *foo) {
1374 bar += sprintf(bar, "%s ", *foo++);
1375 }
1376 }
1377
1378 /* we don't wait for background thejobs to return -- append it
1379 to the list of backgrounded thejobs and leave it alone */
1380 printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
1381 last_bg_pid = thejob->progs[0].pid;
1382 last_jobid = thejob->jobid;
1383}
1384
1385/* remove a backgrounded job */
1386static void remove_bg_job(struct pipe *pi)
1387{
1388 struct pipe *prev_pipe;
1389
1390 if (pi == job_list) {
1391 job_list = pi->next;
1392 } else {
1393 prev_pipe = job_list;
1394 while (prev_pipe->next != pi)
1395 prev_pipe = prev_pipe->next;
1396 prev_pipe->next = pi->next;
1397 }
1398 if (job_list)
1399 last_jobid = job_list->jobid;
1400 else
1401 last_jobid = 0;
1402
1403 pi->stopped_progs = 0;
1404 free_pipe(pi, 0);
1405 free(pi);
1406}
1407
1408/* Checks to see if any processes have exited -- if they
1409 have, figure out why and see if a job has completed */
1410static int checkjobs(struct pipe* fg_pipe)
1411{
1412 int attributes;
1413 int status;
1414 int prognum = 0;
1415 struct pipe *pi;
1416 pid_t childpid;
1417
1418 attributes = WUNTRACED;
1419 if (fg_pipe==NULL) {
1420 attributes |= WNOHANG;
1421 }
1422
1423 while ((childpid = waitpid(-1, &status, attributes)) > 0) {
1424 if (fg_pipe) {
1425 int i, rcode = 0;
1426 for (i=0; i < fg_pipe->num_progs; i++) {
1427 if (fg_pipe->progs[i].pid == childpid) {
1428 if (i==fg_pipe->num_progs-1)
1429 rcode=WEXITSTATUS(status);
1430 (fg_pipe->num_progs)--;
1431 return(rcode);
1432 }
1433 }
1434 }
1435
1436 for (pi = job_list; pi; pi = pi->next) {
1437 prognum = 0;
1438 while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) {
1439 prognum++;
1440 }
1441 if (prognum < pi->num_progs)
1442 break;
1443 }
1444
1445 if(pi==NULL) {
1446 debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
1447 continue;
1448 }
1449
1450 if (WIFEXITED(status) || WIFSIGNALED(status)) {
1451 /* child exited */
1452 pi->running_progs--;
1453 pi->progs[prognum].pid = 0;
1454
1455 if (!pi->running_progs) {
1456 printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
1457 remove_bg_job(pi);
1458 }
1459 } else {
1460 /* child stopped */
1461 pi->stopped_progs++;
1462 pi->progs[prognum].is_stopped = 1;
1463
1464#if 0
1465 /* Printing this stuff is a pain, since it tends to
1466 * overwrite the prompt an inconveinient moments. So
1467 * don't do that. */
1468 if (pi->stopped_progs == pi->num_progs) {
1469 printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text);
1470 }
1471#endif
1472 }
1473 }
1474
1475 if (childpid == -1 && errno != ECHILD)
1476 perror_msg("waitpid");
1477
1478 /* move the shell to the foreground */
1479 /*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */
1480 /* perror_msg("tcsetpgrp-2"); */
1481 return -1;
1482}
1483
1484/* Figure out our controlling tty, checking in order stderr,
1485 * stdin, and stdout. If check_pgrp is set, also check that
1486 * we belong to the foreground process group associated with
1487 * that tty. The value of shell_terminal is needed in order to call
1488 * tcsetpgrp(shell_terminal, ...); */
1489void controlling_tty(int check_pgrp)
1490{
1491 pid_t curpgrp;
1492
1493 if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0
1494 && (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0
1495 && (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0)
1496 goto shell_terminal_error;
1497
1498 if (check_pgrp && curpgrp != getpgid(0))
1499 goto shell_terminal_error;
1500
1501 return;
1502
1503shell_terminal_error:
1504 shell_terminal = -1;
1505 return;
1506}
1507#endif
1508
1509/* run_pipe_real() starts all the jobs, but doesn't wait for anything
1510 * to finish. See checkjobs().
1511 *
1512 * return code is normally -1, when the caller has to wait for children
1513 * to finish to determine the exit status of the pipe. If the pipe
1514 * is a simple builtin command, however, the action is done by the
1515 * time run_pipe_real returns, and the exit code is provided as the
1516 * return value.
1517 *
1518 * The input of the pipe is always stdin, the output is always
1519 * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
1520 * because it tries to avoid running the command substitution in
1521 * subshell, when that is in fact necessary. The subshell process
1522 * now has its stdout directed to the input of the appropriate pipe,
1523 * so this routine is noticeably simpler.
1524 */
1525static int run_pipe_real(struct pipe *pi)
1526{
1527 int i;
1528#ifndef __U_BOOT__
1529 int nextin, nextout;
1530 int pipefds[2]; /* pipefds[0] is for reading */
1531 struct child_prog *child;
1532 struct built_in_command *x;
1533 char *p;
wdenke7f34c62003-01-11 09:48:40 +00001534# if __GNUC__
1535 /* Avoid longjmp clobbering */
1536 (void) &i;
1537 (void) &nextin;
1538 (void) &nextout;
1539 (void) &child;
1540# endif
wdenkfe8c2802002-11-03 00:38:21 +00001541#else
1542 int nextin;
1543 int flag = do_repeat ? CMD_FLAG_REPEAT : 0;
1544 struct child_prog *child;
wdenkfe8c2802002-11-03 00:38:21 +00001545 char *p;
wdenke7f34c62003-01-11 09:48:40 +00001546# if __GNUC__
1547 /* Avoid longjmp clobbering */
1548 (void) &i;
1549 (void) &nextin;
1550 (void) &child;
1551# endif
1552#endif /* __U_BOOT__ */
wdenkfe8c2802002-11-03 00:38:21 +00001553
1554 nextin = 0;
1555#ifndef __U_BOOT__
1556 pi->pgrp = -1;
1557#endif
1558
1559 /* Check if this is a simple builtin (not part of a pipe).
1560 * Builtins within pipes have to fork anyway, and are handled in
1561 * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
1562 */
1563 if (pi->num_progs == 1) child = & (pi->progs[0]);
1564#ifndef __U_BOOT__
1565 if (pi->num_progs == 1 && child->group && child->subshell == 0) {
1566 int squirrel[] = {-1, -1, -1};
1567 int rcode;
1568 debug_printf("non-subshell grouping\n");
1569 setup_redirects(child, squirrel);
1570 /* XXX could we merge code with following builtin case,
1571 * by creating a pseudo builtin that calls run_list_real? */
1572 rcode = run_list_real(child->group);
1573 restore_redirects(squirrel);
1574#else
1575 if (pi->num_progs == 1 && child->group) {
1576 int rcode;
1577 debug_printf("non-subshell grouping\n");
1578 rcode = run_list_real(child->group);
1579#endif
1580 return rcode;
1581 } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
1582 for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
1583 if (i!=0 && child->argv[i]==NULL) {
1584 /* assignments, but no command: set the local environment */
1585 for (i=0; child->argv[i]!=NULL; i++) {
1586
1587 /* Ok, this case is tricky. We have to decide if this is a
1588 * local variable, or an already exported variable. If it is
1589 * already exported, we have to export the new value. If it is
1590 * not exported, we need only set this as a local variable.
1591 * This junk is all to decide whether or not to export this
1592 * variable. */
1593 int export_me=0;
1594 char *name, *value;
1595 name = xstrdup(child->argv[i]);
1596 debug_printf("Local environment set: %s\n", name);
1597 value = strchr(name, '=');
1598 if (value)
1599 *value=0;
1600#ifndef __U_BOOT__
1601 if ( get_local_var(name)) {
1602 export_me=1;
1603 }
1604#endif
1605 free(name);
1606 p = insert_var_value(child->argv[i]);
1607 set_local_var(p, export_me);
1608 if (p != child->argv[i]) free(p);
1609 }
1610 return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
1611 }
1612 for (i = 0; is_assignment(child->argv[i]); i++) {
1613 p = insert_var_value(child->argv[i]);
1614#ifndef __U_BOOT__
1615 putenv(strdup(p));
1616#else
1617 set_local_var(p, 0);
1618#endif
1619 if (p != child->argv[i]) {
1620 child->sp--;
1621 free(p);
1622 }
1623 }
1624 if (child->sp) {
1625 char * str = NULL;
1626
Stephen Warren60c38c92014-03-01 22:16:10 -07001627 str = make_string(child->argv + i,
1628 child->argv_nonnull + i);
wdenkfe8c2802002-11-03 00:38:21 +00001629 parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
1630 free(str);
1631 return last_return_code;
1632 }
1633#ifndef __U_BOOT__
1634 for (x = bltins; x->cmd; x++) {
1635 if (strcmp(child->argv[i], x->cmd) == 0 ) {
1636 int squirrel[] = {-1, -1, -1};
1637 int rcode;
1638 if (x->function == builtin_exec && child->argv[i+1]==NULL) {
1639 debug_printf("magic exec\n");
1640 setup_redirects(child,NULL);
1641 return EXIT_SUCCESS;
1642 }
1643 debug_printf("builtin inline %s\n", child->argv[0]);
1644 /* XXX setup_redirects acts on file descriptors, not FILEs.
1645 * This is perfect for work that comes after exec().
1646 * Is it really safe for inline use? Experimentally,
1647 * things seem to work with glibc. */
1648 setup_redirects(child, squirrel);
Simon Glasse79731e2011-12-06 19:47:53 +00001649
1650 child->argv += i; /* XXX horrible hack */
1651 rcode = x->function(child);
1652 /* XXX restore hack so free() can work right */
1653 child->argv -= i;
1654 restore_redirects(squirrel);
1655 }
1656 return rcode;
1657 }
wdenkfe8c2802002-11-03 00:38:21 +00001658#else
Simon Glass1727b942012-02-14 19:59:25 +00001659 /* check ";", because ,example , argv consist from
1660 * "help;flinfo" must not execute
1661 */
1662 if (strchr(child->argv[i], ';')) {
1663 printf("Unknown command '%s' - try 'help' or use "
1664 "'run' command\n", child->argv[i]);
1665 return -1;
wdenkfe8c2802002-11-03 00:38:21 +00001666 }
Simon Glass1727b942012-02-14 19:59:25 +00001667 /* Process the command */
1668 return cmd_process(flag, child->argc, child->argv,
Richard Genoud94ff0672012-12-03 06:28:28 +00001669 &flag_repeat, NULL);
Simon Glass1727b942012-02-14 19:59:25 +00001670#endif
wdenkfe8c2802002-11-03 00:38:21 +00001671 }
Simon Glass1727b942012-02-14 19:59:25 +00001672#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00001673
1674 for (i = 0; i < pi->num_progs; i++) {
1675 child = & (pi->progs[i]);
1676
1677 /* pipes are inserted between pairs of commands */
1678 if ((i + 1) < pi->num_progs) {
1679 if (pipe(pipefds)<0) perror_msg_and_die("pipe");
1680 nextout = pipefds[1];
1681 } else {
1682 nextout=1;
1683 pipefds[0] = -1;
1684 }
1685
1686 /* XXX test for failed fork()? */
1687 if (!(child->pid = fork())) {
1688 /* Set the handling for job control signals back to the default. */
1689 signal(SIGINT, SIG_DFL);
1690 signal(SIGQUIT, SIG_DFL);
1691 signal(SIGTERM, SIG_DFL);
1692 signal(SIGTSTP, SIG_DFL);
1693 signal(SIGTTIN, SIG_DFL);
1694 signal(SIGTTOU, SIG_DFL);
1695 signal(SIGCHLD, SIG_DFL);
1696
1697 close_all();
1698
1699 if (nextin != 0) {
1700 dup2(nextin, 0);
1701 close(nextin);
1702 }
1703 if (nextout != 1) {
1704 dup2(nextout, 1);
1705 close(nextout);
1706 }
1707 if (pipefds[0]!=-1) {
1708 close(pipefds[0]); /* opposite end of our output pipe */
1709 }
1710
1711 /* Like bash, explicit redirects override pipes,
1712 * and the pipe fd is available for dup'ing. */
1713 setup_redirects(child,NULL);
1714
1715 if (interactive && pi->followup!=PIPE_BG) {
1716 /* If we (the child) win the race, put ourselves in the process
1717 * group whose leader is the first process in this pipe. */
1718 if (pi->pgrp < 0) {
1719 pi->pgrp = getpid();
1720 }
1721 if (setpgid(0, pi->pgrp) == 0) {
1722 tcsetpgrp(2, pi->pgrp);
1723 }
1724 }
1725
1726 pseudo_exec(child);
1727 }
1728
1729
1730 /* put our child in the process group whose leader is the
1731 first process in this pipe */
1732 if (pi->pgrp < 0) {
1733 pi->pgrp = child->pid;
1734 }
1735 /* Don't check for errors. The child may be dead already,
1736 * in which case setpgid returns error code EACCES. */
1737 setpgid(child->pid, pi->pgrp);
1738
1739 if (nextin != 0)
1740 close(nextin);
1741 if (nextout != 1)
1742 close(nextout);
1743
1744 /* If there isn't another process, nextin is garbage
1745 but it doesn't matter */
1746 nextin = pipefds[0];
1747 }
1748#endif
1749 return -1;
1750}
1751
1752static int run_list_real(struct pipe *pi)
1753{
1754 char *save_name = NULL;
1755 char **list = NULL;
1756 char **save_list = NULL;
1757 struct pipe *rpipe;
1758 int flag_rep = 0;
1759#ifndef __U_BOOT__
1760 int save_num_progs;
1761#endif
1762 int rcode=0, flag_skip=1;
1763 int flag_restore = 0;
1764 int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
1765 reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
1766 /* check syntax for "for" */
1767 for (rpipe = pi; rpipe; rpipe = rpipe->next) {
1768 if ((rpipe->r_mode == RES_IN ||
1769 rpipe->r_mode == RES_FOR) &&
1770 (rpipe->next == NULL)) {
1771 syntax();
1772#ifdef __U_BOOT__
1773 flag_repeat = 0;
1774#endif
1775 return 1;
1776 }
1777 if ((rpipe->r_mode == RES_IN &&
1778 (rpipe->next->r_mode == RES_IN &&
1779 rpipe->next->progs->argv != NULL))||
1780 (rpipe->r_mode == RES_FOR &&
1781 rpipe->next->r_mode != RES_IN)) {
1782 syntax();
1783#ifdef __U_BOOT__
1784 flag_repeat = 0;
1785#endif
1786 return 1;
1787 }
1788 }
1789 for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
1790 if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL ||
1791 pi->r_mode == RES_FOR) {
1792#ifdef __U_BOOT__
1793 /* check Ctrl-C */
1794 ctrlc();
1795 if ((had_ctrlc())) {
1796 return 1;
1797 }
1798#endif
1799 flag_restore = 0;
1800 if (!rpipe) {
1801 flag_rep = 0;
1802 rpipe = pi;
1803 }
1804 }
1805 rmode = pi->r_mode;
1806 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);
1807 if (rmode == skip_more_in_this_rmode && flag_skip) {
1808 if (pi->followup == PIPE_SEQ) flag_skip=0;
1809 continue;
1810 }
1811 flag_skip = 1;
1812 skip_more_in_this_rmode = RES_XXXX;
1813 if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
1814 if (rmode == RES_THEN && if_code) continue;
1815 if (rmode == RES_ELSE && !if_code) continue;
wdenk33591052004-04-12 14:31:43 +00001816 if (rmode == RES_ELIF && !if_code) break;
wdenkfe8c2802002-11-03 00:38:21 +00001817 if (rmode == RES_FOR && pi->num_progs) {
1818 if (!list) {
1819 /* if no variable values after "in" we skip "for" */
1820 if (!pi->next->progs->argv) continue;
1821 /* create list of variable values */
1822 list = make_list_in(pi->next->progs->argv,
1823 pi->progs->argv[0]);
1824 save_list = list;
1825 save_name = pi->progs->argv[0];
1826 pi->progs->argv[0] = NULL;
1827 flag_rep = 1;
1828 }
1829 if (!(*list)) {
1830 free(pi->progs->argv[0]);
1831 free(save_list);
1832 list = NULL;
1833 flag_rep = 0;
1834 pi->progs->argv[0] = save_name;
1835#ifndef __U_BOOT__
1836 pi->progs->glob_result.gl_pathv[0] =
1837 pi->progs->argv[0];
1838#endif
1839 continue;
1840 } else {
1841 /* insert new value from list for variable */
1842 if (pi->progs->argv[0])
1843 free(pi->progs->argv[0]);
1844 pi->progs->argv[0] = *list++;
1845#ifndef __U_BOOT__
1846 pi->progs->glob_result.gl_pathv[0] =
1847 pi->progs->argv[0];
1848#endif
1849 }
1850 }
1851 if (rmode == RES_IN) continue;
1852 if (rmode == RES_DO) {
1853 if (!flag_rep) continue;
1854 }
Jeroen Hofstee95ab0d32014-06-11 00:28:47 +02001855 if (rmode == RES_DONE) {
wdenkfe8c2802002-11-03 00:38:21 +00001856 if (flag_rep) {
1857 flag_restore = 1;
1858 } else {
1859 rpipe = NULL;
1860 }
1861 }
1862 if (pi->num_progs == 0) continue;
1863#ifndef __U_BOOT__
1864 save_num_progs = pi->num_progs; /* save number of programs */
1865#endif
1866 rcode = run_pipe_real(pi);
1867 debug_printf("run_pipe_real returned %d\n",rcode);
1868#ifndef __U_BOOT__
1869 if (rcode!=-1) {
1870 /* We only ran a builtin: rcode was set by the return value
1871 * of run_pipe_real(), and we don't need to wait for anything. */
1872 } else if (pi->followup==PIPE_BG) {
1873 /* XXX check bash's behavior with nontrivial pipes */
1874 /* XXX compute jobid */
1875 /* XXX what does bash do with attempts to background builtins? */
1876 insert_bg_job(pi);
1877 rcode = EXIT_SUCCESS;
1878 } else {
1879 if (interactive) {
1880 /* move the new process group into the foreground */
1881 if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY)
1882 perror_msg("tcsetpgrp-3");
1883 rcode = checkjobs(pi);
1884 /* move the shell to the foreground */
1885 if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY)
1886 perror_msg("tcsetpgrp-4");
1887 } else {
1888 rcode = checkjobs(pi);
1889 }
1890 debug_printf("checkjobs returned %d\n",rcode);
1891 }
1892 last_return_code=rcode;
1893#else
wdenk6203e402004-04-18 10:13:26 +00001894 if (rcode < -1) {
1895 last_return_code = -rcode - 2;
1896 return -2; /* exit */
1897 }
wdenkfe8c2802002-11-03 00:38:21 +00001898 last_return_code=(rcode == 0) ? 0 : 1;
1899#endif
1900#ifndef __U_BOOT__
1901 pi->num_progs = save_num_progs; /* restore number of programs */
1902#endif
1903 if ( rmode == RES_IF || rmode == RES_ELIF )
1904 next_if_code=rcode; /* can be overwritten a number of times */
1905 if (rmode == RES_WHILE)
1906 flag_rep = !last_return_code;
1907 if (rmode == RES_UNTIL)
1908 flag_rep = last_return_code;
1909 if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
1910 (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
1911 skip_more_in_this_rmode=rmode;
1912#ifndef __U_BOOT__
1913 checkjobs(NULL);
1914#endif
1915 }
1916 return rcode;
1917}
1918
1919/* broken, of course, but OK for testing */
1920static char *indenter(int i)
1921{
1922 static char blanks[]=" ";
1923 return &blanks[sizeof(blanks)-i-1];
1924}
1925
1926/* return code is the exit status of the pipe */
1927static int free_pipe(struct pipe *pi, int indent)
1928{
1929 char **p;
1930 struct child_prog *child;
1931#ifndef __U_BOOT__
1932 struct redir_struct *r, *rnext;
1933#endif
1934 int a, i, ret_code=0;
1935 char *ind = indenter(indent);
1936
1937#ifndef __U_BOOT__
1938 if (pi->stopped_progs > 0)
1939 return ret_code;
1940 final_printf("%s run pipe: (pid %d)\n",ind,getpid());
1941#endif
1942 for (i=0; i<pi->num_progs; i++) {
1943 child = &pi->progs[i];
1944 final_printf("%s command %d:\n",ind,i);
1945 if (child->argv) {
1946 for (a=0,p=child->argv; *p; a++,p++) {
1947 final_printf("%s argv[%d] = %s\n",ind,a,*p);
1948 }
1949#ifndef __U_BOOT__
1950 globfree(&child->glob_result);
1951#else
Peter Tysercc215a12009-08-05 16:18:44 -05001952 for (a = 0; a < child->argc; a++) {
wdenk57b2d802003-06-27 21:31:46 +00001953 free(child->argv[a]);
1954 }
Stephen Warren60c38c92014-03-01 22:16:10 -07001955 free(child->argv);
1956 free(child->argv_nonnull);
wdenk57b2d802003-06-27 21:31:46 +00001957 child->argc = 0;
wdenkfe8c2802002-11-03 00:38:21 +00001958#endif
1959 child->argv=NULL;
1960 } else if (child->group) {
1961#ifndef __U_BOOT__
1962 final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
1963#endif
1964 ret_code = free_pipe_list(child->group,indent+3);
1965 final_printf("%s end group\n",ind);
1966 } else {
1967 final_printf("%s (nil)\n",ind);
1968 }
1969#ifndef __U_BOOT__
1970 for (r=child->redirects; r; r=rnext) {
1971 final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
1972 if (r->dup == -1) {
1973 /* guard against the case >$FOO, where foo is unset or blank */
1974 if (r->word.gl_pathv) {
1975 final_printf(" %s\n", *r->word.gl_pathv);
1976 globfree(&r->word);
1977 }
1978 } else {
1979 final_printf("&%d\n", r->dup);
1980 }
1981 rnext=r->next;
1982 free(r);
1983 }
1984 child->redirects=NULL;
1985#endif
1986 }
1987 free(pi->progs); /* children are an array, they get freed all at once */
1988 pi->progs=NULL;
1989 return ret_code;
1990}
1991
1992static int free_pipe_list(struct pipe *head, int indent)
1993{
1994 int rcode=0; /* if list has no members */
1995 struct pipe *pi, *next;
1996 char *ind = indenter(indent);
1997 for (pi=head; pi; pi=next) {
1998 final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
1999 rcode = free_pipe(pi, indent);
2000 final_printf("%s pipe followup code %d\n", ind, pi->followup);
2001 next=pi->next;
2002 pi->next=NULL;
2003 free(pi);
2004 }
2005 return rcode;
2006}
2007
2008/* Select which version we will use */
2009static int run_list(struct pipe *pi)
2010{
2011 int rcode=0;
2012#ifndef __U_BOOT__
2013 if (fake_mode==0) {
2014#endif
2015 rcode = run_list_real(pi);
2016#ifndef __U_BOOT__
2017 }
2018#endif
2019 /* free_pipe_list has the side effect of clearing memory
2020 * In the long run that function can be merged with run_list_real,
2021 * but doing that now would hobble the debugging effort. */
2022 free_pipe_list(pi,0);
2023 return rcode;
2024}
2025
2026/* The API for glob is arguably broken. This routine pushes a non-matching
2027 * string into the output structure, removing non-backslashed backslashes.
2028 * If someone can prove me wrong, by performing this function within the
2029 * original glob(3) api, feel free to rewrite this routine into oblivion.
2030 * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
2031 * XXX broken if the last character is '\\', check that before calling.
2032 */
2033#ifndef __U_BOOT__
2034static int globhack(const char *src, int flags, glob_t *pglob)
2035{
2036 int cnt=0, pathc;
2037 const char *s;
2038 char *dest;
2039 for (cnt=1, s=src; s && *s; s++) {
2040 if (*s == '\\') s++;
2041 cnt++;
2042 }
2043 dest = malloc(cnt);
2044 if (!dest) return GLOB_NOSPACE;
2045 if (!(flags & GLOB_APPEND)) {
2046 pglob->gl_pathv=NULL;
2047 pglob->gl_pathc=0;
2048 pglob->gl_offs=0;
2049 pglob->gl_offs=0;
2050 }
2051 pathc = ++pglob->gl_pathc;
2052 pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
2053 if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
2054 pglob->gl_pathv[pathc-1]=dest;
2055 pglob->gl_pathv[pathc]=NULL;
2056 for (s=src; s && *s; s++, dest++) {
2057 if (*s == '\\') s++;
2058 *dest = *s;
2059 }
2060 *dest='\0';
2061 return 0;
2062}
2063
2064/* XXX broken if the last character is '\\', check that before calling */
2065static int glob_needed(const char *s)
2066{
2067 for (; *s; s++) {
2068 if (*s == '\\') s++;
2069 if (strchr("*[?",*s)) return 1;
2070 }
2071 return 0;
2072}
2073
2074#if 0
2075static void globprint(glob_t *pglob)
2076{
2077 int i;
2078 debug_printf("glob_t at %p:\n", pglob);
2079 debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
2080 pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
2081 for (i=0; i<pglob->gl_pathc; i++)
2082 debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
2083 pglob->gl_pathv[i], pglob->gl_pathv[i]);
2084}
2085#endif
2086
2087static int xglob(o_string *dest, int flags, glob_t *pglob)
2088{
2089 int gr;
2090
wdenk57b2d802003-06-27 21:31:46 +00002091 /* short-circuit for null word */
wdenkfe8c2802002-11-03 00:38:21 +00002092 /* we can code this better when the debug_printf's are gone */
wdenk57b2d802003-06-27 21:31:46 +00002093 if (dest->length == 0) {
2094 if (dest->nonnull) {
2095 /* bash man page calls this an "explicit" null */
2096 gr = globhack(dest->data, flags, pglob);
2097 debug_printf("globhack returned %d\n",gr);
2098 } else {
wdenkfe8c2802002-11-03 00:38:21 +00002099 return 0;
2100 }
wdenk57b2d802003-06-27 21:31:46 +00002101 } else if (glob_needed(dest->data)) {
wdenkfe8c2802002-11-03 00:38:21 +00002102 gr = glob(dest->data, flags, NULL, pglob);
2103 debug_printf("glob returned %d\n",gr);
2104 if (gr == GLOB_NOMATCH) {
2105 /* quote removal, or more accurately, backslash removal */
2106 gr = globhack(dest->data, flags, pglob);
2107 debug_printf("globhack returned %d\n",gr);
2108 }
2109 } else {
2110 gr = globhack(dest->data, flags, pglob);
2111 debug_printf("globhack returned %d\n",gr);
2112 }
2113 if (gr == GLOB_NOSPACE)
2114 error_msg_and_die("out of memory during glob");
2115 if (gr != 0) { /* GLOB_ABORTED ? */
2116 error_msg("glob(3) error %d",gr);
2117 }
2118 /* globprint(glob_target); */
2119 return gr;
2120}
2121#endif
2122
wdenk6203e402004-04-18 10:13:26 +00002123#ifdef __U_BOOT__
2124static char *get_dollar_var(char ch);
2125#endif
2126
wdenkfe8c2802002-11-03 00:38:21 +00002127/* This is used to get/check local shell variables */
Holger Brunck50950222011-04-08 02:47:42 +00002128char *get_local_var(const char *s)
wdenkfe8c2802002-11-03 00:38:21 +00002129{
2130 struct variables *cur;
2131
2132 if (!s)
2133 return NULL;
wdenk6203e402004-04-18 10:13:26 +00002134
2135#ifdef __U_BOOT__
2136 if (*s == '$')
2137 return get_dollar_var(s[1]);
2138#endif
2139
wdenkfe8c2802002-11-03 00:38:21 +00002140 for (cur = top_vars; cur; cur=cur->next)
2141 if(strcmp(cur->name, s)==0)
2142 return cur->value;
2143 return NULL;
2144}
2145
2146/* This is used to set local shell variables
2147 flg_export==0 if only local (not exporting) variable
2148 flg_export==1 if "new" exporting environ
2149 flg_export>1 if current startup environ (not call putenv()) */
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002150int set_local_var(const char *s, int flg_export)
wdenkfe8c2802002-11-03 00:38:21 +00002151{
2152 char *name, *value;
2153 int result=0;
2154 struct variables *cur;
2155
wdenk6203e402004-04-18 10:13:26 +00002156#ifdef __U_BOOT__
2157 /* might be possible! */
2158 if (!isalpha(*s))
2159 return -1;
2160#endif
2161
wdenkfe8c2802002-11-03 00:38:21 +00002162 name=strdup(s);
2163
2164#ifdef __U_BOOT__
2165 if (getenv(name) != NULL) {
2166 printf ("ERROR: "
wdenk2ebee312004-02-23 19:30:57 +00002167 "There is a global environment variable with the same name.\n");
wdenk6203e402004-04-18 10:13:26 +00002168 free(name);
wdenkfe8c2802002-11-03 00:38:21 +00002169 return -1;
2170 }
2171#endif
2172 /* Assume when we enter this function that we are already in
2173 * NAME=VALUE format. So the first order of business is to
2174 * split 's' on the '=' into 'name' and 'value' */
2175 value = strchr(name, '=');
Peng Fan0db5f0b2015-11-24 16:54:21 +08002176 if (value == NULL || *(value + 1) == 0) {
wdenkfe8c2802002-11-03 00:38:21 +00002177 free(name);
2178 return -1;
2179 }
2180 *value++ = 0;
2181
2182 for(cur = top_vars; cur; cur = cur->next) {
2183 if(strcmp(cur->name, name)==0)
2184 break;
2185 }
2186
2187 if(cur) {
2188 if(strcmp(cur->value, value)==0) {
2189 if(flg_export>0 && cur->flg_export==0)
2190 cur->flg_export=flg_export;
2191 else
2192 result++;
2193 } else {
2194 if(cur->flg_read_only) {
2195 error_msg("%s: readonly variable", name);
2196 result = -1;
2197 } else {
2198 if(flg_export>0 || cur->flg_export>1)
2199 cur->flg_export=1;
2200 free(cur->value);
2201
2202 cur->value = strdup(value);
2203 }
2204 }
2205 } else {
2206 cur = malloc(sizeof(struct variables));
2207 if(!cur) {
2208 result = -1;
2209 } else {
2210 cur->name = strdup(name);
Kim Phillipsb052b602012-10-29 13:34:32 +00002211 if (cur->name == NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002212 free(cur);
2213 result = -1;
2214 } else {
2215 struct variables *bottom = top_vars;
2216 cur->value = strdup(value);
Kim Phillipsb052b602012-10-29 13:34:32 +00002217 cur->next = NULL;
wdenkfe8c2802002-11-03 00:38:21 +00002218 cur->flg_export = flg_export;
2219 cur->flg_read_only = 0;
2220 while(bottom->next) bottom=bottom->next;
2221 bottom->next = cur;
2222 }
2223 }
2224 }
2225
2226#ifndef __U_BOOT__
2227 if(result==0 && cur->flg_export==1) {
2228 *(value-1) = '=';
2229 result = putenv(name);
2230 } else {
2231#endif
2232 free(name);
2233#ifndef __U_BOOT__
2234 if(result>0) /* equivalent to previous set */
2235 result = 0;
2236 }
2237#endif
2238 return result;
2239}
2240
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002241void unset_local_var(const char *name)
wdenkfe8c2802002-11-03 00:38:21 +00002242{
2243 struct variables *cur;
2244
2245 if (name) {
2246 for (cur = top_vars; cur; cur=cur->next) {
2247 if(strcmp(cur->name, name)==0)
2248 break;
2249 }
Kim Phillipsb052b602012-10-29 13:34:32 +00002250 if (cur != NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002251 struct variables *next = top_vars;
2252 if(cur->flg_read_only) {
2253 error_msg("%s: readonly variable", name);
2254 return;
2255 } else {
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002256#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00002257 if(cur->flg_export)
2258 unsetenv(cur->name);
Heiko Schocher49ebcb52008-10-15 09:40:28 +02002259#endif
wdenkfe8c2802002-11-03 00:38:21 +00002260 free(cur->name);
2261 free(cur->value);
2262 while (next->next != cur)
2263 next = next->next;
2264 next->next = cur->next;
2265 }
2266 free(cur);
2267 }
2268 }
2269}
wdenkfe8c2802002-11-03 00:38:21 +00002270
2271static int is_assignment(const char *s)
2272{
wdenk6203e402004-04-18 10:13:26 +00002273 if (s == NULL)
2274 return 0;
2275
2276 if (!isalpha(*s)) return 0;
wdenkfe8c2802002-11-03 00:38:21 +00002277 ++s;
2278 while(isalnum(*s) || *s=='_') ++s;
2279 return *s=='=';
2280}
2281
2282#ifndef __U_BOOT__
2283/* the src parameter allows us to peek forward to a possible &n syntax
2284 * for file descriptor duplication, e.g., "2>&1".
2285 * Return code is 0 normally, 1 if a syntax error is detected in src.
2286 * Resource errors (in xmalloc) cause the process to exit */
2287static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
2288 struct in_str *input)
2289{
2290 struct child_prog *child=ctx->child;
2291 struct redir_struct *redir = child->redirects;
2292 struct redir_struct *last_redir=NULL;
2293
2294 /* Create a new redir_struct and drop it onto the end of the linked list */
2295 while(redir) {
2296 last_redir=redir;
2297 redir=redir->next;
2298 }
2299 redir = xmalloc(sizeof(struct redir_struct));
2300 redir->next=NULL;
2301 redir->word.gl_pathv=NULL;
2302 if (last_redir) {
2303 last_redir->next=redir;
2304 } else {
2305 child->redirects=redir;
2306 }
2307
2308 redir->type=style;
2309 redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
2310
2311 debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
2312
2313 /* Check for a '2>&1' type redirect */
2314 redir->dup = redirect_dup_num(input);
2315 if (redir->dup == -2) return 1; /* syntax error */
2316 if (redir->dup != -1) {
2317 /* Erik had a check here that the file descriptor in question
2318 * is legit; I postpone that to "run time"
2319 * A "-" representation of "close me" shows up as a -3 here */
2320 debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
2321 } else {
2322 /* We do _not_ try to open the file that src points to,
2323 * since we need to return and let src be expanded first.
2324 * Set ctx->pending_redirect, so we know what to do at the
2325 * end of the next parsed word.
2326 */
2327 ctx->pending_redirect = redir;
2328 }
2329 return 0;
2330}
2331#endif
2332
Kim Phillipsb052b602012-10-29 13:34:32 +00002333static struct pipe *new_pipe(void)
2334{
wdenkfe8c2802002-11-03 00:38:21 +00002335 struct pipe *pi;
2336 pi = xmalloc(sizeof(struct pipe));
2337 pi->num_progs = 0;
2338 pi->progs = NULL;
2339 pi->next = NULL;
2340 pi->followup = 0; /* invalid */
Wolfgang Denk00b67fd2005-09-28 01:49:47 +02002341 pi->r_mode = RES_NONE;
wdenkfe8c2802002-11-03 00:38:21 +00002342 return pi;
2343}
2344
2345static void initialize_context(struct p_context *ctx)
2346{
2347 ctx->pipe=NULL;
2348#ifndef __U_BOOT__
2349 ctx->pending_redirect=NULL;
2350#endif
2351 ctx->child=NULL;
2352 ctx->list_head=new_pipe();
2353 ctx->pipe=ctx->list_head;
2354 ctx->w=RES_NONE;
2355 ctx->stack=NULL;
2356#ifdef __U_BOOT__
2357 ctx->old_flag=0;
2358#endif
2359 done_command(ctx); /* creates the memory for working child */
2360}
2361
2362/* normal return is 0
2363 * if a reserved word is found, and processed, return 1
2364 * should handle if, then, elif, else, fi, for, while, until, do, done.
2365 * case, function, and select are obnoxious, save those for later.
2366 */
wdenkb02744a2003-04-05 00:53:31 +00002367struct reserved_combo {
2368 char *literal;
2369 int code;
2370 long flag;
2371};
2372/* Mostly a list of accepted follow-up reserved words.
2373 * FLAG_END means we are done with the sequence, and are ready
2374 * to turn the compound list into a command.
2375 * FLAG_START means the word must start a new compound list.
2376 */
2377static struct reserved_combo reserved_list[] = {
2378 { "if", RES_IF, FLAG_THEN | FLAG_START },
2379 { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
2380 { "elif", RES_ELIF, FLAG_THEN },
2381 { "else", RES_ELSE, FLAG_FI },
2382 { "fi", RES_FI, FLAG_END },
2383 { "for", RES_FOR, FLAG_IN | FLAG_START },
2384 { "while", RES_WHILE, FLAG_DO | FLAG_START },
2385 { "until", RES_UNTIL, FLAG_DO | FLAG_START },
2386 { "in", RES_IN, FLAG_DO },
2387 { "do", RES_DO, FLAG_DONE },
2388 { "done", RES_DONE, FLAG_END }
2389};
2390#define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo))
2391
Kim Phillipsb052b602012-10-29 13:34:32 +00002392static int reserved_word(o_string *dest, struct p_context *ctx)
wdenkfe8c2802002-11-03 00:38:21 +00002393{
wdenkfe8c2802002-11-03 00:38:21 +00002394 struct reserved_combo *r;
2395 for (r=reserved_list;
wdenkfe8c2802002-11-03 00:38:21 +00002396 r<reserved_list+NRES; r++) {
2397 if (strcmp(dest->data, r->literal) == 0) {
2398 debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
2399 if (r->flag & FLAG_START) {
2400 struct p_context *new = xmalloc(sizeof(struct p_context));
2401 debug_printf("push stack\n");
2402 if (ctx->w == RES_IN || ctx->w == RES_FOR) {
2403 syntax();
2404 free(new);
2405 ctx->w = RES_SNTX;
2406 b_reset(dest);
2407 return 1;
2408 }
2409 *new = *ctx; /* physical copy */
2410 initialize_context(ctx);
2411 ctx->stack=new;
2412 } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
2413 syntax();
2414 ctx->w = RES_SNTX;
2415 b_reset(dest);
2416 return 1;
2417 }
2418 ctx->w=r->code;
2419 ctx->old_flag = r->flag;
2420 if (ctx->old_flag & FLAG_END) {
2421 struct p_context *old;
2422 debug_printf("pop stack\n");
2423 done_pipe(ctx,PIPE_SEQ);
2424 old = ctx->stack;
2425 old->child->group = ctx->list_head;
2426#ifndef __U_BOOT__
2427 old->child->subshell = 0;
2428#endif
2429 *ctx = *old; /* physical copy */
2430 free(old);
2431 }
2432 b_reset (dest);
2433 return 1;
2434 }
2435 }
2436 return 0;
2437}
2438
2439/* normal return is 0.
2440 * Syntax or xglob errors return 1. */
2441static int done_word(o_string *dest, struct p_context *ctx)
2442{
2443 struct child_prog *child=ctx->child;
2444#ifndef __U_BOOT__
2445 glob_t *glob_target;
2446 int gr, flags = 0;
2447#else
2448 char *str, *s;
2449 int argc, cnt;
2450#endif
2451
2452 debug_printf("done_word: %s %p\n", dest->data, child);
2453 if (dest->length == 0 && !dest->nonnull) {
2454 debug_printf(" true null, ignored\n");
2455 return 0;
2456 }
2457#ifndef __U_BOOT__
2458 if (ctx->pending_redirect) {
2459 glob_target = &ctx->pending_redirect->word;
2460 } else {
2461#endif
2462 if (child->group) {
2463 syntax();
2464 return 1; /* syntax error, groups and arglists don't mix */
2465 }
2466 if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
2467 debug_printf("checking %s for reserved-ness\n",dest->data);
2468 if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
2469 }
2470#ifndef __U_BOOT__
2471 glob_target = &child->glob_result;
wdenk57b2d802003-06-27 21:31:46 +00002472 if (child->argv) flags |= GLOB_APPEND;
wdenkfe8c2802002-11-03 00:38:21 +00002473#else
2474 for (cnt = 1, s = dest->data; s && *s; s++) {
2475 if (*s == '\\') s++;
2476 cnt++;
2477 }
2478 str = malloc(cnt);
2479 if (!str) return 1;
2480 if ( child->argv == NULL) {
2481 child->argc=0;
2482 }
2483 argc = ++child->argc;
2484 child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv));
Peng Fan27a9d262015-11-27 10:12:02 +08002485 if (child->argv == NULL) {
2486 free(str);
2487 return 1;
2488 }
Stephen Warren60c38c92014-03-01 22:16:10 -07002489 child->argv_nonnull = realloc(child->argv_nonnull,
2490 (argc+1)*sizeof(*child->argv_nonnull));
Peng Fan27a9d262015-11-27 10:12:02 +08002491 if (child->argv_nonnull == NULL) {
2492 free(str);
Stephen Warren60c38c92014-03-01 22:16:10 -07002493 return 1;
Peng Fan27a9d262015-11-27 10:12:02 +08002494 }
wdenkfe8c2802002-11-03 00:38:21 +00002495 child->argv[argc-1]=str;
Stephen Warren60c38c92014-03-01 22:16:10 -07002496 child->argv_nonnull[argc-1] = dest->nonnull;
wdenkfe8c2802002-11-03 00:38:21 +00002497 child->argv[argc]=NULL;
Stephen Warren60c38c92014-03-01 22:16:10 -07002498 child->argv_nonnull[argc] = 0;
wdenkfe8c2802002-11-03 00:38:21 +00002499 for (s = dest->data; s && *s; s++,str++) {
2500 if (*s == '\\') s++;
2501 *str = *s;
2502 }
2503 *str = '\0';
2504#endif
2505#ifndef __U_BOOT__
2506 }
2507 gr = xglob(dest, flags, glob_target);
2508 if (gr != 0) return 1;
2509#endif
2510
2511 b_reset(dest);
2512#ifndef __U_BOOT__
2513 if (ctx->pending_redirect) {
2514 ctx->pending_redirect=NULL;
2515 if (glob_target->gl_pathc != 1) {
2516 error_msg("ambiguous redirect");
2517 return 1;
2518 }
2519 } else {
2520 child->argv = glob_target->gl_pathv;
2521 }
2522#endif
2523 if (ctx->w == RES_FOR) {
2524 done_word(dest,ctx);
2525 done_pipe(ctx,PIPE_SEQ);
2526 }
2527 return 0;
2528}
2529
2530/* The only possible error here is out of memory, in which case
2531 * xmalloc exits. */
2532static int done_command(struct p_context *ctx)
2533{
2534 /* The child is really already in the pipe structure, so
2535 * advance the pipe counter and make a new, null child.
2536 * Only real trickiness here is that the uncommitted
2537 * child structure, to which ctx->child points, is not
2538 * counted in pi->num_progs. */
2539 struct pipe *pi=ctx->pipe;
2540 struct child_prog *prog=ctx->child;
2541
2542 if (prog && prog->group == NULL
wdenk57b2d802003-06-27 21:31:46 +00002543 && prog->argv == NULL
wdenkfe8c2802002-11-03 00:38:21 +00002544#ifndef __U_BOOT__
wdenk57b2d802003-06-27 21:31:46 +00002545 && prog->redirects == NULL) {
wdenkfe8c2802002-11-03 00:38:21 +00002546#else
2547 ) {
2548#endif
2549 debug_printf("done_command: skipping null command\n");
2550 return 0;
2551 } else if (prog) {
2552 pi->num_progs++;
2553 debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
2554 } else {
2555 debug_printf("done_command: initializing\n");
2556 }
2557 pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
2558
2559 prog = pi->progs + pi->num_progs;
2560#ifndef __U_BOOT__
2561 prog->redirects = NULL;
2562#endif
2563 prog->argv = NULL;
Stephen Warren60c38c92014-03-01 22:16:10 -07002564 prog->argv_nonnull = NULL;
wdenkfe8c2802002-11-03 00:38:21 +00002565#ifndef __U_BOOT__
2566 prog->is_stopped = 0;
2567#endif
2568 prog->group = NULL;
2569#ifndef __U_BOOT__
2570 prog->glob_result.gl_pathv = NULL;
2571 prog->family = pi;
2572#endif
2573 prog->sp = 0;
2574 ctx->child = prog;
2575 prog->type = ctx->type;
2576
2577 /* but ctx->pipe and ctx->list_head remain unchanged */
2578 return 0;
2579}
2580
2581static int done_pipe(struct p_context *ctx, pipe_style type)
2582{
2583 struct pipe *new_p;
2584 done_command(ctx); /* implicit closure of previous command */
2585 debug_printf("done_pipe, type %d\n", type);
2586 ctx->pipe->followup = type;
2587 ctx->pipe->r_mode = ctx->w;
2588 new_p=new_pipe();
2589 ctx->pipe->next = new_p;
2590 ctx->pipe = new_p;
2591 ctx->child = NULL;
2592 done_command(ctx); /* set up new pipe to accept commands */
2593 return 0;
2594}
2595
2596#ifndef __U_BOOT__
2597/* peek ahead in the in_str to find out if we have a "&n" construct,
2598 * as in "2>&1", that represents duplicating a file descriptor.
2599 * returns either -2 (syntax error), -1 (no &), or the number found.
2600 */
2601static int redirect_dup_num(struct in_str *input)
2602{
2603 int ch, d=0, ok=0;
2604 ch = b_peek(input);
2605 if (ch != '&') return -1;
2606
2607 b_getch(input); /* get the & */
2608 ch=b_peek(input);
2609 if (ch == '-') {
2610 b_getch(input);
2611 return -3; /* "-" represents "close me" */
2612 }
2613 while (isdigit(ch)) {
2614 d = d*10+(ch-'0');
2615 ok=1;
2616 b_getch(input);
2617 ch = b_peek(input);
2618 }
2619 if (ok) return d;
2620
2621 error_msg("ambiguous redirect");
2622 return -2;
2623}
2624
2625/* If a redirect is immediately preceded by a number, that number is
2626 * supposed to tell which file descriptor to redirect. This routine
2627 * looks for such preceding numbers. In an ideal world this routine
2628 * needs to handle all the following classes of redirects...
2629 * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
2630 * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
2631 * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
2632 * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
2633 * A -1 output from this program means no valid number was found, so the
2634 * caller should use the appropriate default for this redirection.
2635 */
2636static int redirect_opt_num(o_string *o)
2637{
2638 int num;
2639
2640 if (o->length==0) return -1;
2641 for(num=0; num<o->length; num++) {
2642 if (!isdigit(*(o->data+num))) {
2643 return -1;
2644 }
2645 }
2646 /* reuse num (and save an int) */
2647 num=atoi(o->data);
2648 b_reset(o);
2649 return num;
2650}
2651
2652FILE *generate_stream_from_list(struct pipe *head)
2653{
2654 FILE *pf;
2655#if 1
2656 int pid, channel[2];
2657 if (pipe(channel)<0) perror_msg_and_die("pipe");
2658 pid=fork();
2659 if (pid<0) {
2660 perror_msg_and_die("fork");
2661 } else if (pid==0) {
2662 close(channel[0]);
2663 if (channel[1] != 1) {
2664 dup2(channel[1],1);
2665 close(channel[1]);
2666 }
2667#if 0
2668#define SURROGATE "surrogate response"
2669 write(1,SURROGATE,sizeof(SURROGATE));
2670 _exit(run_list(head));
2671#else
2672 _exit(run_list_real(head)); /* leaks memory */
2673#endif
2674 }
2675 debug_printf("forked child %d\n",pid);
2676 close(channel[1]);
2677 pf = fdopen(channel[0],"r");
2678 debug_printf("pipe on FILE *%p\n",pf);
2679#else
2680 free_pipe_list(head,0);
2681 pf=popen("echo surrogate response","r");
2682 debug_printf("started fake pipe on FILE *%p\n",pf);
2683#endif
2684 return pf;
2685}
2686
2687/* this version hacked for testing purposes */
2688/* return code is exit status of the process that is run. */
2689static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
2690{
2691 int retcode;
2692 o_string result=NULL_O_STRING;
2693 struct p_context inner;
2694 FILE *p;
2695 struct in_str pipe_str;
2696 initialize_context(&inner);
2697
2698 /* recursion to generate command */
2699 retcode = parse_stream(&result, &inner, input, subst_end);
2700 if (retcode != 0) return retcode; /* syntax error or EOF */
2701 done_word(&result, &inner);
2702 done_pipe(&inner, PIPE_SEQ);
2703 b_free(&result);
2704
2705 p=generate_stream_from_list(inner.list_head);
2706 if (p==NULL) return 1;
2707 mark_open(fileno(p));
2708 setup_file_in_str(&pipe_str, p);
2709
2710 /* now send results of command back into original context */
2711 retcode = parse_stream(dest, ctx, &pipe_str, '\0');
2712 /* XXX In case of a syntax error, should we try to kill the child?
2713 * That would be tough to do right, so just read until EOF. */
2714 if (retcode == 1) {
2715 while (b_getch(&pipe_str)!=EOF) { /* discard */ };
2716 }
2717
2718 debug_printf("done reading from pipe, pclose()ing\n");
2719 /* This is the step that wait()s for the child. Should be pretty
2720 * safe, since we just read an EOF from its stdout. We could try
2721 * to better, by using wait(), and keeping track of background jobs
2722 * at the same time. That would be a lot of work, and contrary
2723 * to the KISS philosophy of this program. */
2724 mark_closed(fileno(p));
2725 retcode=pclose(p);
2726 free_pipe_list(inner.list_head,0);
2727 debug_printf("pclosed, retcode=%d\n",retcode);
2728 /* XXX this process fails to trim a single trailing newline */
2729 return retcode;
2730}
2731
2732static int parse_group(o_string *dest, struct p_context *ctx,
2733 struct in_str *input, int ch)
2734{
2735 int rcode, endch=0;
2736 struct p_context sub;
2737 struct child_prog *child = ctx->child;
2738 if (child->argv) {
2739 syntax();
2740 return 1; /* syntax error, groups and arglists don't mix */
2741 }
2742 initialize_context(&sub);
2743 switch(ch) {
2744 case '(': endch=')'; child->subshell=1; break;
2745 case '{': endch='}'; break;
2746 default: syntax(); /* really logic error */
2747 }
2748 rcode=parse_stream(dest,&sub,input,endch);
2749 done_word(dest,&sub); /* finish off the final word in the subcontext */
2750 done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
2751 child->group = sub.list_head;
2752 return rcode;
2753 /* child remains "open", available for possible redirects */
2754}
2755#endif
2756
2757/* basically useful version until someone wants to get fancier,
2758 * see the bash man page under "Parameter Expansion" */
2759static char *lookup_param(char *src)
2760{
wdenk6203e402004-04-18 10:13:26 +00002761 char *p;
Joe Hershberger82fea772012-08-17 10:26:29 +00002762 char *sep;
2763 char *default_val = NULL;
2764 int assign = 0;
2765 int expand_empty = 0;
wdenk6203e402004-04-18 10:13:26 +00002766
2767 if (!src)
2768 return NULL;
2769
Joe Hershberger82fea772012-08-17 10:26:29 +00002770 sep = strchr(src, ':');
2771
2772 if (sep) {
2773 *sep = '\0';
2774 if (*(sep + 1) == '-')
2775 default_val = sep+2;
2776 if (*(sep + 1) == '=') {
2777 default_val = sep+2;
2778 assign = 1;
2779 }
2780 if (*(sep + 1) == '+') {
2781 default_val = sep+2;
2782 expand_empty = 1;
2783 }
2784 }
2785
2786 p = getenv(src);
2787 if (!p)
2788 p = get_local_var(src);
2789
2790 if (!p || strlen(p) == 0) {
2791 p = default_val;
2792 if (assign) {
2793 char *var = malloc(strlen(src)+strlen(default_val)+2);
2794 if (var) {
2795 sprintf(var, "%s=%s", src, default_val);
2796 set_local_var(var, 0);
2797 }
2798 free(var);
2799 }
2800 } else if (expand_empty) {
2801 p += strlen(p);
2802 }
2803
2804 if (sep)
2805 *sep = ':';
wdenk6203e402004-04-18 10:13:26 +00002806
wdenkfe8c2802002-11-03 00:38:21 +00002807 return p;
2808}
wdenk6203e402004-04-18 10:13:26 +00002809
2810#ifdef __U_BOOT__
2811static char *get_dollar_var(char ch)
2812{
2813 static char buf[40];
2814
2815 buf[0] = '\0';
2816 switch (ch) {
2817 case '?':
2818 sprintf(buf, "%u", (unsigned int)last_return_code);
2819 break;
2820 default:
2821 return NULL;
2822 }
2823 return buf;
2824}
2825#endif
wdenkfe8c2802002-11-03 00:38:21 +00002826
2827/* return code: 0 for OK, 1 for syntax error */
2828static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
2829{
2830#ifndef __U_BOOT__
2831 int i, advance=0;
2832#else
2833 int advance=0;
2834#endif
2835#ifndef __U_BOOT__
2836 char sep[]=" ";
2837#endif
2838 int ch = input->peek(input); /* first character after the $ */
2839 debug_printf("handle_dollar: ch=%c\n",ch);
2840 if (isalpha(ch)) {
2841 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2842 ctx->child->sp++;
2843 while(ch=b_peek(input),isalnum(ch) || ch=='_') {
2844 b_getch(input);
2845 b_addchr(dest,ch);
2846 }
2847 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2848#ifndef __U_BOOT__
2849 } else if (isdigit(ch)) {
2850 i = ch-'0'; /* XXX is $0 special? */
2851 if (i<global_argc) {
2852 parse_string(dest, ctx, global_argv[i]); /* recursion */
2853 }
2854 advance = 1;
2855#endif
2856 } else switch (ch) {
2857#ifndef __U_BOOT__
2858 case '$':
2859 b_adduint(dest,getpid());
2860 advance = 1;
2861 break;
2862 case '!':
2863 if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
2864 advance = 1;
2865 break;
2866#endif
2867 case '?':
wdenk6203e402004-04-18 10:13:26 +00002868#ifndef __U_BOOT__
wdenkfe8c2802002-11-03 00:38:21 +00002869 b_adduint(dest,last_return_code);
wdenk6203e402004-04-18 10:13:26 +00002870#else
2871 ctx->child->sp++;
2872 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2873 b_addchr(dest, '$');
2874 b_addchr(dest, '?');
2875 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2876#endif
wdenkfe8c2802002-11-03 00:38:21 +00002877 advance = 1;
2878 break;
2879#ifndef __U_BOOT__
2880 case '#':
2881 b_adduint(dest,global_argc ? global_argc-1 : 0);
2882 advance = 1;
2883 break;
2884#endif
2885 case '{':
2886 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2887 ctx->child->sp++;
2888 b_getch(input);
2889 /* XXX maybe someone will try to escape the '}' */
2890 while(ch=b_getch(input),ch!=EOF && ch!='}') {
2891 b_addchr(dest,ch);
2892 }
2893 if (ch != '}') {
2894 syntax();
2895 return 1;
2896 }
2897 b_addchr(dest, SPECIAL_VAR_SYMBOL);
2898 break;
2899#ifndef __U_BOOT__
2900 case '(':
2901 b_getch(input);
2902 process_command_subs(dest, ctx, input, ')');
2903 break;
2904 case '*':
2905 sep[0]=ifs[0];
2906 for (i=1; i<global_argc; i++) {
2907 parse_string(dest, ctx, global_argv[i]);
2908 if (i+1 < global_argc) parse_string(dest, ctx, sep);
2909 }
2910 break;
2911 case '@':
2912 case '-':
2913 case '_':
2914 /* still unhandled, but should be eventually */
2915 error_msg("unhandled syntax: $%c",ch);
2916 return 1;
2917 break;
2918#endif
2919 default:
2920 b_addqchr(dest,'$',dest->quote);
2921 }
2922 /* Eat the character if the flag was set. If the compiler
2923 * is smart enough, we could substitute "b_getch(input);"
2924 * for all the "advance = 1;" above, and also end up with
2925 * a nice size-optimized program. Hah! That'll be the day.
2926 */
2927 if (advance) b_getch(input);
2928 return 0;
2929}
2930
2931#ifndef __U_BOOT__
2932int parse_string(o_string *dest, struct p_context *ctx, const char *src)
2933{
2934 struct in_str foo;
2935 setup_string_in_str(&foo, src);
2936 return parse_stream(dest, ctx, &foo, '\0');
2937}
2938#endif
2939
2940/* return code is 0 for normal exit, 1 for syntax error */
Kim Phillipsb052b602012-10-29 13:34:32 +00002941static int parse_stream(o_string *dest, struct p_context *ctx,
2942 struct in_str *input, int end_trigger)
wdenkfe8c2802002-11-03 00:38:21 +00002943{
2944 unsigned int ch, m;
2945#ifndef __U_BOOT__
2946 int redir_fd;
2947 redir_type redir_style;
2948#endif
2949 int next;
2950
2951 /* Only double-quote state is handled in the state variable dest->quote.
2952 * A single-quote triggers a bypass of the main loop until its mate is
2953 * found. When recursing, quote state is passed in via dest->quote. */
2954
2955 debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
2956 while ((ch=b_getch(input))!=EOF) {
2957 m = map[ch];
2958#ifdef __U_BOOT__
2959 if (input->__promptme == 0) return 1;
2960#endif
2961 next = (ch == '\n') ? 0 : b_peek(input);
wdenk6203e402004-04-18 10:13:26 +00002962
2963 debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n",
2964 ch >= ' ' ? ch : '.', ch, m,
2965 dest->quote, ctx->stack == NULL ? '*' : '.');
2966
wdenkfe8c2802002-11-03 00:38:21 +00002967 if (m==0 || ((m==1 || m==2) && dest->quote)) {
2968 b_addqchr(dest, ch, dest->quote);
2969 } else {
2970 if (m==2) { /* unquoted IFS */
2971 if (done_word(dest, ctx)) {
2972 return 1;
2973 }
2974 /* If we aren't performing a substitution, treat a newline as a
2975 * command separator. */
2976 if (end_trigger != '\0' && ch=='\n')
2977 done_pipe(ctx,PIPE_SEQ);
2978 }
2979 if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
2980 debug_printf("leaving parse_stream (triggered)\n");
2981 return 0;
2982 }
2983#if 0
2984 if (ch=='\n') {
2985 /* Yahoo! Time to run with it! */
2986 done_pipe(ctx,PIPE_SEQ);
2987 run_list(ctx->list_head);
2988 initialize_context(ctx);
2989 }
2990#endif
2991 if (m!=2) switch (ch) {
2992 case '#':
2993 if (dest->length == 0 && !dest->quote) {
2994 while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
2995 } else {
2996 b_addqchr(dest, ch, dest->quote);
2997 }
2998 break;
2999 case '\\':
3000 if (next == EOF) {
3001 syntax();
3002 return 1;
3003 }
3004 b_addqchr(dest, '\\', dest->quote);
3005 b_addqchr(dest, b_getch(input), dest->quote);
3006 break;
3007 case '$':
3008 if (handle_dollar(dest, ctx, input)!=0) return 1;
3009 break;
3010 case '\'':
3011 dest->nonnull = 1;
3012 while(ch=b_getch(input),ch!=EOF && ch!='\'') {
3013#ifdef __U_BOOT__
3014 if(input->__promptme == 0) return 1;
3015#endif
3016 b_addchr(dest,ch);
3017 }
3018 if (ch==EOF) {
3019 syntax();
3020 return 1;
3021 }
3022 break;
3023 case '"':
3024 dest->nonnull = 1;
3025 dest->quote = !dest->quote;
3026 break;
3027#ifndef __U_BOOT__
3028 case '`':
3029 process_command_subs(dest, ctx, input, '`');
3030 break;
3031 case '>':
3032 redir_fd = redirect_opt_num(dest);
3033 done_word(dest, ctx);
3034 redir_style=REDIRECT_OVERWRITE;
3035 if (next == '>') {
3036 redir_style=REDIRECT_APPEND;
3037 b_getch(input);
3038 } else if (next == '(') {
3039 syntax(); /* until we support >(list) Process Substitution */
3040 return 1;
3041 }
3042 setup_redirect(ctx, redir_fd, redir_style, input);
3043 break;
3044 case '<':
3045 redir_fd = redirect_opt_num(dest);
3046 done_word(dest, ctx);
3047 redir_style=REDIRECT_INPUT;
3048 if (next == '<') {
3049 redir_style=REDIRECT_HEREIS;
3050 b_getch(input);
3051 } else if (next == '>') {
3052 redir_style=REDIRECT_IO;
3053 b_getch(input);
3054 } else if (next == '(') {
3055 syntax(); /* until we support <(list) Process Substitution */
3056 return 1;
3057 }
3058 setup_redirect(ctx, redir_fd, redir_style, input);
3059 break;
3060#endif
3061 case ';':
3062 done_word(dest, ctx);
3063 done_pipe(ctx,PIPE_SEQ);
3064 break;
3065 case '&':
3066 done_word(dest, ctx);
3067 if (next=='&') {
3068 b_getch(input);
3069 done_pipe(ctx,PIPE_AND);
3070 } else {
3071#ifndef __U_BOOT__
3072 done_pipe(ctx,PIPE_BG);
3073#else
3074 syntax_err();
3075 return 1;
3076#endif
3077 }
3078 break;
3079 case '|':
3080 done_word(dest, ctx);
3081 if (next=='|') {
3082 b_getch(input);
3083 done_pipe(ctx,PIPE_OR);
3084 } else {
3085 /* we could pick up a file descriptor choice here
3086 * with redirect_opt_num(), but bash doesn't do it.
3087 * "echo foo 2| cat" yields "foo 2". */
3088#ifndef __U_BOOT__
3089 done_command(ctx);
3090#else
3091 syntax_err();
3092 return 1;
3093#endif
3094 }
3095 break;
3096#ifndef __U_BOOT__
3097 case '(':
3098 case '{':
3099 if (parse_group(dest, ctx, input, ch)!=0) return 1;
3100 break;
3101 case ')':
3102 case '}':
3103 syntax(); /* Proper use of this character caught by end_trigger */
3104 return 1;
3105 break;
3106#endif
Joe Hershberger38de0b62012-08-17 10:26:30 +00003107 case SUBSTED_VAR_SYMBOL:
3108 dest->nonnull = 1;
3109 while (ch = b_getch(input), ch != EOF &&
3110 ch != SUBSTED_VAR_SYMBOL) {
3111 debug_printf("subst, pass=%d\n", ch);
3112 if (input->__promptme == 0)
3113 return 1;
3114 b_addchr(dest, ch);
3115 }
3116 debug_printf("subst, term=%d\n", ch);
3117 if (ch == EOF) {
3118 syntax();
3119 return 1;
3120 }
3121 break;
wdenkfe8c2802002-11-03 00:38:21 +00003122 default:
3123 syntax(); /* this is really an internal logic error */
3124 return 1;
3125 }
3126 }
3127 }
3128 /* complain if quote? No, maybe we just finished a command substitution
3129 * that was quoted. Example:
3130 * $ echo "`cat foo` plus more"
3131 * and we just got the EOF generated by the subshell that ran "cat foo"
3132 * The only real complaint is if we got an EOF when end_trigger != '\0',
3133 * that is, we were really supposed to get end_trigger, and never got
3134 * one before the EOF. Can't use the standard "syntax error" return code,
3135 * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
3136 debug_printf("leaving parse_stream (EOF)\n");
3137 if (end_trigger != '\0') return -1;
3138 return 0;
3139}
3140
Kim Phillipsb052b602012-10-29 13:34:32 +00003141static void mapset(const unsigned char *set, int code)
wdenkfe8c2802002-11-03 00:38:21 +00003142{
3143 const unsigned char *s;
3144 for (s=set; *s; s++) map[*s] = code;
3145}
3146
Kim Phillipsb052b602012-10-29 13:34:32 +00003147static void update_ifs_map(void)
wdenkfe8c2802002-11-03 00:38:21 +00003148{
3149 /* char *ifs and char map[256] are both globals. */
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003150 ifs = (uchar *)getenv("IFS");
3151 if (ifs == NULL) ifs=(uchar *)" \t\n";
wdenkfe8c2802002-11-03 00:38:21 +00003152 /* Precompute a list of 'flow through' behavior so it can be treated
3153 * quickly up front. Computation is necessary because of IFS.
3154 * Special case handling of IFS == " \t\n" is not implemented.
3155 * The map[] array only really needs two bits each, and on most machines
3156 * that would be faster because of the reduced L1 cache footprint.
3157 */
3158 memset(map,0,sizeof(map)); /* most characters flow through always */
3159#ifndef __U_BOOT__
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003160 mapset((uchar *)"\\$'\"`", 3); /* never flow through */
3161 mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */
wdenkfe8c2802002-11-03 00:38:21 +00003162#else
Joe Hershberger38de0b62012-08-17 10:26:30 +00003163 {
3164 uchar subst[2] = {SUBSTED_VAR_SYMBOL, 0};
3165 mapset(subst, 3); /* never flow through */
3166 }
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003167 mapset((uchar *)"\\$'\"", 3); /* never flow through */
3168 mapset((uchar *)";&|#", 1); /* flow through if quoted */
wdenkfe8c2802002-11-03 00:38:21 +00003169#endif
3170 mapset(ifs, 2); /* also flow through if quoted */
3171}
3172
3173/* most recursion does not come through here, the exeception is
3174 * from builtin_source() */
Kim Phillipsb052b602012-10-29 13:34:32 +00003175static int parse_stream_outer(struct in_str *inp, int flag)
wdenkfe8c2802002-11-03 00:38:21 +00003176{
3177
3178 struct p_context ctx;
3179 o_string temp=NULL_O_STRING;
3180 int rcode;
3181#ifdef __U_BOOT__
Rabin Vincentc3249b82014-10-29 23:21:41 +01003182 int code = 1;
wdenkfe8c2802002-11-03 00:38:21 +00003183#endif
3184 do {
3185 ctx.type = flag;
3186 initialize_context(&ctx);
3187 update_ifs_map();
Wolfgang Denk7fb52662005-10-13 16:45:02 +02003188 if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0);
wdenkfe8c2802002-11-03 00:38:21 +00003189 inp->promptmode=1;
Simon Glass94cb9c22014-10-07 13:59:43 -06003190 rcode = parse_stream(&temp, &ctx, inp,
3191 flag & FLAG_CONT_ON_NEWLINE ? -1 : '\n');
wdenkfe8c2802002-11-03 00:38:21 +00003192#ifdef __U_BOOT__
3193 if (rcode == 1) flag_repeat = 0;
3194#endif
3195 if (rcode != 1 && ctx.old_flag != 0) {
3196 syntax();
3197#ifdef __U_BOOT__
3198 flag_repeat = 0;
3199#endif
3200 }
3201 if (rcode != 1 && ctx.old_flag == 0) {
3202 done_word(&temp, &ctx);
3203 done_pipe(&ctx,PIPE_SEQ);
3204#ifndef __U_BOOT__
3205 run_list(ctx.list_head);
3206#else
wdenk6203e402004-04-18 10:13:26 +00003207 code = run_list(ctx.list_head);
3208 if (code == -2) { /* exit */
3209 b_free(&temp);
3210 code = 0;
3211 /* XXX hackish way to not allow exit from main loop */
3212 if (inp->peek == file_peek) {
3213 printf("exit not allowed from main input shell.\n");
3214 continue;
3215 }
3216 break;
3217 }
3218 if (code == -1)
wdenkfe8c2802002-11-03 00:38:21 +00003219 flag_repeat = 0;
3220#endif
3221 } else {
3222 if (ctx.old_flag != 0) {
3223 free(ctx.stack);
3224 b_reset(&temp);
3225 }
3226#ifdef __U_BOOT__
3227 if (inp->__promptme == 0) printf("<INTERRUPT>\n");
3228 inp->__promptme = 1;
3229#endif
3230 temp.nonnull = 0;
3231 temp.quote = 0;
3232 inp->p = NULL;
3233 free_pipe_list(ctx.list_head,0);
3234 }
3235 b_free(&temp);
Simon Glass29617102014-05-30 14:41:50 -06003236 /* loop on syntax errors, return on EOF */
Rabin Vincentae68a822014-11-21 23:05:22 +01003237 } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP) &&
Simon Glass29617102014-05-30 14:41:50 -06003238 (inp->peek != static_peek || b_peek(inp)));
wdenkfe8c2802002-11-03 00:38:21 +00003239#ifndef __U_BOOT__
3240 return 0;
3241#else
3242 return (code != 0) ? 1 : 0;
3243#endif /* __U_BOOT__ */
3244}
3245
3246#ifndef __U_BOOT__
3247static int parse_string_outer(const char *s, int flag)
3248#else
Jason Hobbsa56febb2011-08-31 05:37:24 +00003249int parse_string_outer(const char *s, int flag)
wdenkfe8c2802002-11-03 00:38:21 +00003250#endif /* __U_BOOT__ */
3251{
3252 struct in_str input;
3253#ifdef __U_BOOT__
3254 char *p = NULL;
3255 int rcode;
Rabin Vincent401ac652014-10-29 23:21:39 +01003256 if (!s)
wdenkfe8c2802002-11-03 00:38:21 +00003257 return 1;
Rabin Vincent401ac652014-10-29 23:21:39 +01003258 if (!*s)
3259 return 0;
wdenkfe8c2802002-11-03 00:38:21 +00003260 if (!(p = strchr(s, '\n')) || *++p) {
3261 p = xmalloc(strlen(s) + 2);
3262 strcpy(p, s);
3263 strcat(p, "\n");
3264 setup_string_in_str(&input, p);
3265 rcode = parse_stream_outer(&input, flag);
3266 free(p);
3267 return rcode;
3268 } else {
3269#endif
3270 setup_string_in_str(&input, s);
3271 return parse_stream_outer(&input, flag);
3272#ifdef __U_BOOT__
3273 }
3274#endif
3275}
3276
3277#ifndef __U_BOOT__
3278static int parse_file_outer(FILE *f)
3279#else
3280int parse_file_outer(void)
3281#endif
3282{
3283 int rcode;
3284 struct in_str input;
3285#ifndef __U_BOOT__
3286 setup_file_in_str(&input, f);
3287#else
3288 setup_file_in_str(&input);
3289#endif
3290 rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
3291 return rcode;
3292}
3293
3294#ifdef __U_BOOT__
Wolfgang Denkd0813e52010-10-28 20:00:11 +02003295#ifdef CONFIG_NEEDS_MANUAL_RELOC
wdenkb02744a2003-04-05 00:53:31 +00003296static void u_boot_hush_reloc(void)
3297{
wdenkb02744a2003-04-05 00:53:31 +00003298 unsigned long addr;
3299 struct reserved_combo *r;
3300
3301 for (r=reserved_list; r<reserved_list+NRES; r++) {
3302 addr = (ulong) (r->literal) + gd->reloc_off;
3303 r->literal = (char *)addr;
3304 }
3305}
Peter Tyser9057cbf2009-09-21 11:20:36 -05003306#endif
wdenkb02744a2003-04-05 00:53:31 +00003307
wdenkfe8c2802002-11-03 00:38:21 +00003308int u_boot_hush_start(void)
3309{
wdenkbd1575f2003-10-14 19:43:55 +00003310 if (top_vars == NULL) {
3311 top_vars = malloc(sizeof(struct variables));
3312 top_vars->name = "HUSH_VERSION";
3313 top_vars->value = "0.01";
Kim Phillipsb052b602012-10-29 13:34:32 +00003314 top_vars->next = NULL;
wdenkbd1575f2003-10-14 19:43:55 +00003315 top_vars->flg_export = 0;
3316 top_vars->flg_read_only = 1;
Wolfgang Denkd0813e52010-10-28 20:00:11 +02003317#ifdef CONFIG_NEEDS_MANUAL_RELOC
wdenkbd1575f2003-10-14 19:43:55 +00003318 u_boot_hush_reloc();
Peter Tyser9057cbf2009-09-21 11:20:36 -05003319#endif
wdenkbd1575f2003-10-14 19:43:55 +00003320 }
wdenkfe8c2802002-11-03 00:38:21 +00003321 return 0;
3322}
3323
3324static void *xmalloc(size_t size)
3325{
3326 void *p = NULL;
3327
3328 if (!(p = malloc(size))) {
3329 printf("ERROR : memory not allocated\n");
3330 for(;;);
3331 }
3332 return p;
3333}
3334
3335static void *xrealloc(void *ptr, size_t size)
3336{
3337 void *p = NULL;
3338
3339 if (!(p = realloc(ptr, size))) {
3340 printf("ERROR : memory not allocated\n");
3341 for(;;);
3342 }
3343 return p;
3344}
3345#endif /* __U_BOOT__ */
3346
3347#ifndef __U_BOOT__
3348/* Make sure we have a controlling tty. If we get started under a job
3349 * aware app (like bash for example), make sure we are now in charge so
3350 * we don't fight over who gets the foreground */
wdenke7f34c62003-01-11 09:48:40 +00003351static void setup_job_control(void)
wdenkfe8c2802002-11-03 00:38:21 +00003352{
3353 static pid_t shell_pgrp;
3354 /* Loop until we are in the foreground. */
3355 while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
3356 kill (- shell_pgrp, SIGTTIN);
3357
3358 /* Ignore interactive and job-control signals. */
3359 signal(SIGINT, SIG_IGN);
3360 signal(SIGQUIT, SIG_IGN);
3361 signal(SIGTERM, SIG_IGN);
3362 signal(SIGTSTP, SIG_IGN);
3363 signal(SIGTTIN, SIG_IGN);
3364 signal(SIGTTOU, SIG_IGN);
3365 signal(SIGCHLD, SIG_IGN);
3366
3367 /* Put ourselves in our own process group. */
3368 setsid();
3369 shell_pgrp = getpid ();
3370 setpgid (shell_pgrp, shell_pgrp);
3371
3372 /* Grab control of the terminal. */
3373 tcsetpgrp(shell_terminal, shell_pgrp);
3374}
3375
Wolfgang Denk6262d0212010-06-28 22:00:46 +02003376int hush_main(int argc, char * const *argv)
wdenkfe8c2802002-11-03 00:38:21 +00003377{
3378 int opt;
3379 FILE *input;
3380 char **e = environ;
3381
3382 /* XXX what should these be while sourcing /etc/profile? */
3383 global_argc = argc;
3384 global_argv = argv;
3385
3386 /* (re?) initialize globals. Sometimes hush_main() ends up calling
3387 * hush_main(), therefore we cannot rely on the BSS to zero out this
3388 * stuff. Reset these to 0 every time. */
3389 ifs = NULL;
3390 /* map[] is taken care of with call to update_ifs_map() */
3391 fake_mode = 0;
3392 interactive = 0;
3393 close_me_head = NULL;
3394 last_bg_pid = 0;
3395 job_list = NULL;
3396 last_jobid = 0;
3397
3398 /* Initialize some more globals to non-zero values */
3399 set_cwd();
wdenke7f34c62003-01-11 09:48:40 +00003400#ifdef CONFIG_FEATURE_COMMAND_EDITING
wdenkfe8c2802002-11-03 00:38:21 +00003401 cmdedit_set_initial_prompt();
3402#else
3403 PS1 = NULL;
3404#endif
3405 PS2 = "> ";
3406
3407 /* initialize our shell local variables with the values
3408 * currently living in the environment */
3409 if (e) {
3410 for (; *e; e++)
3411 set_local_var(*e, 2); /* without call putenv() */
3412 }
3413
3414 last_return_code=EXIT_SUCCESS;
3415
3416
3417 if (argv[0] && argv[0][0] == '-') {
3418 debug_printf("\nsourcing /etc/profile\n");
3419 if ((input = fopen("/etc/profile", "r")) != NULL) {
3420 mark_open(fileno(input));
3421 parse_file_outer(input);
3422 mark_closed(fileno(input));
3423 fclose(input);
3424 }
3425 }
3426 input=stdin;
3427
3428 while ((opt = getopt(argc, argv, "c:xif")) > 0) {
3429 switch (opt) {
3430 case 'c':
3431 {
3432 global_argv = argv+optind;
3433 global_argc = argc-optind;
3434 opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
3435 goto final_return;
3436 }
3437 break;
3438 case 'i':
3439 interactive++;
3440 break;
3441 case 'f':
3442 fake_mode++;
3443 break;
3444 default:
3445#ifndef BB_VER
3446 fprintf(stderr, "Usage: sh [FILE]...\n"
3447 " or: sh -c command [args]...\n\n");
3448 exit(EXIT_FAILURE);
3449#else
3450 show_usage();
3451#endif
3452 }
3453 }
3454 /* A shell is interactive if the `-i' flag was given, or if all of
3455 * the following conditions are met:
3456 * no -c command
3457 * no arguments remaining or the -s flag given
3458 * standard input is a terminal
3459 * standard output is a terminal
3460 * Refer to Posix.2, the description of the `sh' utility. */
3461 if (argv[optind]==NULL && input==stdin &&
3462 isatty(fileno(stdin)) && isatty(fileno(stdout))) {
3463 interactive++;
3464 }
3465
3466 debug_printf("\ninteractive=%d\n", interactive);
3467 if (interactive) {
3468 /* Looks like they want an interactive shell */
wdenk57b2d802003-06-27 21:31:46 +00003469#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
wdenke7f34c62003-01-11 09:48:40 +00003470 printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n");
3471 printf( "Enter 'help' for a list of built-in commands.\n\n");
3472#endif
wdenkfe8c2802002-11-03 00:38:21 +00003473 setup_job_control();
3474 }
3475
3476 if (argv[optind]==NULL) {
3477 opt=parse_file_outer(stdin);
3478 goto final_return;
3479 }
3480
3481 debug_printf("\nrunning script '%s'\n", argv[optind]);
3482 global_argv = argv+optind;
3483 global_argc = argc-optind;
3484 input = xfopen(argv[optind], "r");
3485 opt = parse_file_outer(input);
3486
wdenke7f34c62003-01-11 09:48:40 +00003487#ifdef CONFIG_FEATURE_CLEAN_UP
wdenkfe8c2802002-11-03 00:38:21 +00003488 fclose(input);
3489 if (cwd && cwd != unknown)
3490 free((char*)cwd);
3491 {
3492 struct variables *cur, *tmp;
3493 for(cur = top_vars; cur; cur = tmp) {
3494 tmp = cur->next;
3495 if (!cur->flg_read_only) {
3496 free(cur->name);
3497 free(cur->value);
3498 free(cur);
3499 }
3500 }
3501 }
3502#endif
3503
3504final_return:
3505 return(opt?opt:last_return_code);
3506}
3507#endif
3508
3509static char *insert_var_value(char *inp)
3510{
Joe Hershberger38de0b62012-08-17 10:26:30 +00003511 return insert_var_value_sub(inp, 0);
3512}
3513
3514static char *insert_var_value_sub(char *inp, int tag_subst)
3515{
wdenkfe8c2802002-11-03 00:38:21 +00003516 int res_str_len = 0;
3517 int len;
3518 int done = 0;
3519 char *p, *p1, *res_str = NULL;
3520
3521 while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
Nishanth Menon0978ef32015-12-04 13:02:11 -06003522 /* check the beginning of the string for normal characters */
wdenkfe8c2802002-11-03 00:38:21 +00003523 if (p != inp) {
Nishanth Menon0978ef32015-12-04 13:02:11 -06003524 /* copy any characters to the result string */
wdenkfe8c2802002-11-03 00:38:21 +00003525 len = p - inp;
3526 res_str = xrealloc(res_str, (res_str_len + len));
3527 strncpy((res_str + res_str_len), inp, len);
3528 res_str_len += len;
3529 }
3530 inp = ++p;
Joe Hershberger38de0b62012-08-17 10:26:30 +00003531 /* find the ending marker */
wdenkfe8c2802002-11-03 00:38:21 +00003532 p = strchr(inp, SPECIAL_VAR_SYMBOL);
3533 *p = '\0';
Joe Hershberger38de0b62012-08-17 10:26:30 +00003534 /* look up the value to substitute */
wdenkfe8c2802002-11-03 00:38:21 +00003535 if ((p1 = lookup_param(inp))) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003536 if (tag_subst)
3537 len = res_str_len + strlen(p1) + 2;
3538 else
3539 len = res_str_len + strlen(p1);
wdenkfe8c2802002-11-03 00:38:21 +00003540 res_str = xrealloc(res_str, (1 + len));
Joe Hershberger38de0b62012-08-17 10:26:30 +00003541 if (tag_subst) {
3542 /*
3543 * copy the variable value to the result
3544 * string
3545 */
3546 strcpy((res_str + res_str_len + 1), p1);
3547
3548 /*
3549 * mark the replaced text to be accepted as
3550 * is
3551 */
3552 res_str[res_str_len] = SUBSTED_VAR_SYMBOL;
3553 res_str[res_str_len + 1 + strlen(p1)] =
3554 SUBSTED_VAR_SYMBOL;
3555 } else
3556 /*
3557 * copy the variable value to the result
3558 * string
3559 */
3560 strcpy((res_str + res_str_len), p1);
3561
wdenkfe8c2802002-11-03 00:38:21 +00003562 res_str_len = len;
3563 }
3564 *p = SPECIAL_VAR_SYMBOL;
3565 inp = ++p;
3566 done = 1;
3567 }
3568 if (done) {
3569 res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
3570 strcpy((res_str + res_str_len), inp);
3571 while ((p = strchr(res_str, '\n'))) {
3572 *p = ' ';
3573 }
3574 }
3575 return (res_str == NULL) ? inp : res_str;
3576}
3577
3578static char **make_list_in(char **inp, char *name)
3579{
3580 int len, i;
3581 int name_len = strlen(name);
3582 int n = 0;
3583 char **list;
3584 char *p1, *p2, *p3;
3585
3586 /* create list of variable values */
3587 list = xmalloc(sizeof(*list));
3588 for (i = 0; inp[i]; i++) {
3589 p3 = insert_var_value(inp[i]);
3590 p1 = p3;
3591 while (*p1) {
Jeroen Hofstee95ab0d32014-06-11 00:28:47 +02003592 if (*p1 == ' ') {
wdenkfe8c2802002-11-03 00:38:21 +00003593 p1++;
3594 continue;
3595 }
3596 if ((p2 = strchr(p1, ' '))) {
3597 len = p2 - p1;
3598 } else {
3599 len = strlen(p1);
3600 p2 = p1 + len;
3601 }
3602 /* we use n + 2 in realloc for list,because we add
3603 * new element and then we will add NULL element */
3604 list = xrealloc(list, sizeof(*list) * (n + 2));
3605 list[n] = xmalloc(2 + name_len + len);
3606 strcpy(list[n], name);
3607 strcat(list[n], "=");
3608 strncat(list[n], p1, len);
3609 list[n++][name_len + len + 1] = '\0';
3610 p1 = p2;
3611 }
3612 if (p3 != inp[i]) free(p3);
3613 }
3614 list[n] = NULL;
3615 return list;
3616}
3617
Stephen Warren60c38c92014-03-01 22:16:10 -07003618/*
3619 * Make new string for parser
3620 * inp - array of argument strings to flatten
3621 * nonnull - indicates argument was quoted when originally parsed
3622 */
3623static char *make_string(char **inp, int *nonnull)
wdenkfe8c2802002-11-03 00:38:21 +00003624{
3625 char *p;
3626 char *str = NULL;
3627 int n;
3628 int len = 2;
Joe Hershberger38de0b62012-08-17 10:26:30 +00003629 char *noeval_str;
3630 int noeval = 0;
wdenkfe8c2802002-11-03 00:38:21 +00003631
Joe Hershberger38de0b62012-08-17 10:26:30 +00003632 noeval_str = get_local_var("HUSH_NO_EVAL");
3633 if (noeval_str != NULL && *noeval_str != '0' && *noeval_str != '\0')
3634 noeval = 1;
wdenkfe8c2802002-11-03 00:38:21 +00003635 for (n = 0; inp[n]; n++) {
Joe Hershberger38de0b62012-08-17 10:26:30 +00003636 p = insert_var_value_sub(inp[n], noeval);
Stephen Warren60c38c92014-03-01 22:16:10 -07003637 str = xrealloc(str, (len + strlen(p) + (2 * nonnull[n])));
wdenkfe8c2802002-11-03 00:38:21 +00003638 if (n) {
3639 strcat(str, " ");
3640 } else {
3641 *str = '\0';
3642 }
Stephen Warren60c38c92014-03-01 22:16:10 -07003643 if (nonnull[n])
3644 strcat(str, "'");
wdenkfe8c2802002-11-03 00:38:21 +00003645 strcat(str, p);
Stephen Warren60c38c92014-03-01 22:16:10 -07003646 if (nonnull[n])
3647 strcat(str, "'");
wdenkfe8c2802002-11-03 00:38:21 +00003648 len = strlen(str) + 3;
3649 if (p != inp[n]) free(p);
3650 }
3651 len = strlen(str);
3652 *(str + len) = '\n';
3653 *(str + len + 1) = '\0';
3654 return str;
3655}
3656
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003657#ifdef __U_BOOT__
Kim Phillipsb052b602012-10-29 13:34:32 +00003658static int do_showvar(cmd_tbl_t *cmdtp, int flag, int argc,
3659 char * const argv[])
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003660{
3661 int i, k;
3662 int rcode = 0;
3663 struct variables *cur;
3664
3665 if (argc == 1) { /* Print all env variables */
3666 for (cur = top_vars; cur; cur = cur->next) {
3667 printf ("%s=%s\n", cur->name, cur->value);
3668 if (ctrlc ()) {
3669 puts ("\n ** Abort\n");
3670 return 1;
3671 }
3672 }
3673 return 0;
3674 }
3675 for (i = 1; i < argc; ++i) { /* print single env variables */
3676 char *name = argv[i];
3677
3678 k = -1;
3679 for (cur = top_vars; cur; cur = cur->next) {
3680 if(strcmp (cur->name, name) == 0) {
3681 k = 0;
3682 printf ("%s=%s\n", cur->name, cur->value);
3683 }
3684 if (ctrlc ()) {
3685 puts ("\n ** Abort\n");
3686 return 1;
3687 }
3688 }
3689 if (k < 0) {
3690 printf ("## Error: \"%s\" not defined\n", name);
3691 rcode ++;
3692 }
3693 }
3694 return rcode;
3695}
3696
3697U_BOOT_CMD(
Jean-Christophe PLAGNIOL-VILLARD03836942008-10-16 15:01:15 +02003698 showvar, CONFIG_SYS_MAXARGS, 1, do_showvar,
Peter Tyserdfb72b82009-01-27 18:03:12 -06003699 "print local hushshell variables",
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003700 "\n - print values of all hushshell variables\n"
3701 "showvar name ...\n"
Wolfgang Denkc54781c2009-05-24 17:06:54 +02003702 " - print value of hushshell variable 'name'"
Heiko Schocher49ebcb52008-10-15 09:40:28 +02003703);
3704
3705#endif
wdenkfe8c2802002-11-03 00:38:21 +00003706/****************************************************************************/