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