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