From 54c5d08a09e631f88738db54c75395c6457c2157 Mon Sep 17 00:00:00 2001 From: Heiko Schocher Date: Thu, 22 May 2014 12:43:05 +0200 Subject: dm: rename device struct to udevice using UBI and DM together leads in compiler error, as both define a "struct device", so rename "struct device" in include/dm/device.h to "struct udevice", as we use linux code (MTD/UBI/UBIFS some USB code,...) and cannot change the linux "struct device" Signed-off-by: Heiko Schocher Cc: Simon Glass Cc: Marek Vasut --- common/cmd_demo.c | 4 ++-- common/cmd_gpio.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/cmd_demo.c b/common/cmd_demo.c index a3bba7f..652c61c 100644 --- a/common/cmd_demo.c +++ b/common/cmd_demo.c @@ -11,7 +11,7 @@ #include #include -struct device *demo_dev; +struct udevice *demo_dev; static int do_demo_hello(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) @@ -41,7 +41,7 @@ static int do_demo_status(cmd_tbl_t *cmdtp, int flag, int argc, int do_demo_list(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { - struct device *dev; + struct udevice *dev; int i, ret; puts("Demo uclass entries:\n"); diff --git a/common/cmd_gpio.c b/common/cmd_gpio.c index aff0445..4634f91 100644 --- a/common/cmd_gpio.c +++ b/common/cmd_gpio.c @@ -30,7 +30,7 @@ static const char * const gpio_function[] = { "unknown", }; -static void show_gpio(struct device *dev, const char *bank_name, int offset) +static void show_gpio(struct udevice *dev, const char *bank_name, int offset) { struct dm_gpio_ops *ops = gpio_get_ops(dev); char buf[80]; @@ -62,7 +62,7 @@ static void show_gpio(struct device *dev, const char *bank_name, int offset) static int do_gpio_status(const char *gpio_name) { - struct device *dev; + struct udevice *dev; int newline = 0; int ret; -- cgit v1.1 From ae4223f4444d7e673ff6b4a066c8584858629025 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:23 -0600 Subject: Remove unnecessary use of hush header file Some files include hush.h but don't actually use it. Remove this where possible. Signed-off-by: Simon Glass --- common/cmd_bootm.c | 4 ---- common/cmd_bootmenu.c | 1 - 2 files changed, 5 deletions(-) (limited to 'common') diff --git a/common/cmd_bootm.c b/common/cmd_bootm.c index 34b4b58..449bb36 100644 --- a/common/cmd_bootm.c +++ b/common/cmd_bootm.c @@ -32,10 +32,6 @@ #include #endif -#ifdef CONFIG_SYS_HUSH_PARSER -#include -#endif - #if defined(CONFIG_OF_LIBFDT) #include #include diff --git a/common/cmd_bootmenu.c b/common/cmd_bootmenu.c index 163d5b2..5879065 100644 --- a/common/cmd_bootmenu.c +++ b/common/cmd_bootmenu.c @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include -- cgit v1.1 From eca86fad3d823c3c1e7e78b07752aa6a10e35283 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:24 -0600 Subject: Rename hush to cli_hush Hush is a command-line interpreter, so rename it to make that clearer. Signed-off-by: Simon Glass --- common/Makefile | 2 +- common/cli_hush.c | 3687 +++++++++++++++++++++++++++++++++++++++++++++++++++++ common/hush.c | 3687 ----------------------------------------------------- common/main.c | 2 +- 4 files changed, 3689 insertions(+), 3689 deletions(-) create mode 100644 common/cli_hush.c delete mode 100644 common/hush.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index 219cb51..da184a8 100644 --- a/common/Makefile +++ b/common/Makefile @@ -11,7 +11,7 @@ obj-y += main.o obj-y += command.o obj-y += exports.o obj-y += hash.o -obj-$(CONFIG_SYS_HUSH_PARSER) += hush.o +obj-$(CONFIG_SYS_HUSH_PARSER) += cli_hush.o obj-y += s_record.o obj-y += xyzModem.o obj-y += cmd_disk.o diff --git a/common/cli_hush.c b/common/cli_hush.c new file mode 100644 index 0000000..012004a --- /dev/null +++ b/common/cli_hush.c @@ -0,0 +1,3687 @@ +/* + * sh.c -- a prototype Bourne shell grammar parser + * Intended to follow the original Thompson and Ritchie + * "small and simple is beautiful" philosophy, which + * incidentally is a good match to today's BusyBox. + * + * Copyright (C) 2000,2001 Larry Doolittle + * + * Credits: + * The parser routines proper are all original material, first + * written Dec 2000 and Jan 2001 by Larry Doolittle. + * The execution engine, the builtins, and much of the underlying + * support has been adapted from busybox-0.49pre's lash, + * which is Copyright (C) 2000 by Lineo, Inc., and + * written by Erik Andersen , . + * That, in turn, is based in part on ladsh.c, by Michael K. Johnson and + * Erik W. Troan, which they placed in the public domain. I don't know + * how much of the Johnson/Troan code has survived the repeated rewrites. + * Other credits: + * b_addchr() derived from similar w_addchar function in glibc-2.2 + * setup_redirect(), redirect_opt_num(), and big chunks of main() + * and many builtins derived from contributions by Erik Andersen + * miscellaneous bugfixes from Matt Kraai + * + * There are two big (and related) architecture differences between + * this parser and the lash parser. One is that this version is + * actually designed from the ground up to understand nearly all + * of the Bourne grammar. The second, consequential change is that + * the parser and input reader have been turned inside out. Now, + * the parser is in control, and asks for input as needed. The old + * way had the input reader in control, and it asked for parsing to + * take place as needed. The new way makes it much easier to properly + * handle the recursion implicit in the various substitutions, especially + * across continuation lines. + * + * Bash grammar not implemented: (how many of these were in original sh?) + * $@ (those sure look like weird quoting rules) + * $_ + * ! negation operator for pipes + * &> and >& redirection of stdout+stderr + * Brace Expansion + * Tilde Expansion + * fancy forms of Parameter Expansion + * aliases + * Arithmetic Expansion + * <(list) and >(list) Process Substitution + * reserved words: case, esac, select, function + * Here Documents ( << word ) + * Functions + * Major bugs: + * job handling woefully incomplete and buggy + * reserved word execution woefully incomplete and buggy + * to-do: + * port selected bugfixes from post-0.49 busybox lash - done? + * finish implementing reserved words: for, while, until, do, done + * change { and } from special chars to reserved words + * builtins: break, continue, eval, return, set, trap, ulimit + * test magic exec + * handle children going into background + * clean up recognition of null pipes + * check setting of global_argc and global_argv + * control-C handling, probably with longjmp + * follow IFS rules more precisely, including update semantics + * figure out what to do with backslash-newline + * explain why we use signal instead of sigaction + * propagate syntax errors, die on resource errors? + * continuation lines, both explicit and implicit - done? + * memory leak finding and plugging - done? + * more testing, especially quoting rules and redirection + * document how quoting rules not precisely followed for variable assignments + * maybe change map[] to use 2-bit entries + * (eventually) remove all the printf's + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#define __U_BOOT__ +#ifdef __U_BOOT__ +#include /* malloc, free, realloc*/ +#include /* isalpha, isdigit */ +#include /* readline */ +#include +#include /* find_cmd */ +#ifndef CONFIG_SYS_PROMPT_HUSH_PS2 +#define CONFIG_SYS_PROMPT_HUSH_PS2 "> " +#endif +#endif +#ifndef __U_BOOT__ +#include /* isalpha, isdigit */ +#include /* getpid */ +#include /* getenv, atoi */ +#include /* strchr */ +#include /* popen etc. */ +#include /* glob, of course */ +#include /* va_list */ +#include +#include +#include /* should be pretty obvious */ + +#include /* ulimit */ +#include +#include +#include + +/* #include */ + +#if 1 +#include "busybox.h" +#include "cmdedit.h" +#else +#define applet_name "hush" +#include "standalone.h" +#define hush_main main +#undef CONFIG_FEATURE_SH_FANCY_PROMPT +#define BB_BANNER +#endif +#endif +#define SPECIAL_VAR_SYMBOL 03 +#define SUBSTED_VAR_SYMBOL 04 +#ifndef __U_BOOT__ +#define FLAG_EXIT_FROM_LOOP 1 +#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */ +#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */ + +#endif + +#ifdef __U_BOOT__ +DECLARE_GLOBAL_DATA_PTR; + +#define EXIT_SUCCESS 0 +#define EOF -1 +#define syntax() syntax_err() +#define xstrdup strdup +#define error_msg printf +#else +typedef enum { + REDIRECT_INPUT = 1, + REDIRECT_OVERWRITE = 2, + REDIRECT_APPEND = 3, + REDIRECT_HEREIS = 4, + REDIRECT_IO = 5 +} redir_type; + +/* The descrip member of this structure is only used to make debugging + * output pretty */ +struct {int mode; int default_fd; char *descrip;} redir_table[] = { + { 0, 0, "()" }, + { O_RDONLY, 0, "<" }, + { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" }, + { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" }, + { O_RDONLY, -1, "<<" }, + { O_RDWR, 1, "<>" } +}; +#endif + +typedef enum { + PIPE_SEQ = 1, + PIPE_AND = 2, + PIPE_OR = 3, + PIPE_BG = 4, +} pipe_style; + +/* might eventually control execution */ +typedef enum { + RES_NONE = 0, + RES_IF = 1, + RES_THEN = 2, + RES_ELIF = 3, + RES_ELSE = 4, + RES_FI = 5, + RES_FOR = 6, + RES_WHILE = 7, + RES_UNTIL = 8, + RES_DO = 9, + RES_DONE = 10, + RES_XXXX = 11, + RES_IN = 12, + RES_SNTX = 13 +} reserved_style; +#define FLAG_END (1<, but protected with __USE_GNU */ +#endif + +/* "globals" within this file */ +static uchar *ifs; +static char map[256]; +#ifndef __U_BOOT__ +static int fake_mode; +static int interactive; +static struct close_me *close_me_head; +static const char *cwd; +static struct pipe *job_list; +static unsigned int last_bg_pid; +static unsigned int last_jobid; +static unsigned int shell_terminal; +static char *PS1; +static char *PS2; +struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 }; +struct variables *top_vars = &shell_ver; +#else +static int flag_repeat = 0; +static int do_repeat = 0; +static struct variables *top_vars = NULL ; +#endif /*__U_BOOT__ */ + +#define B_CHUNK (100) +#define B_NOSPAC 1 + +typedef struct { + char *data; + int length; + int maxlen; + int quote; + int nonnull; +} o_string; +#define NULL_O_STRING {NULL,0,0,0,0} +/* used for initialization: + o_string foo = NULL_O_STRING; */ + +/* I can almost use ordinary FILE *. Is open_memstream() universally + * available? Where is it documented? */ +struct in_str { + const char *p; +#ifndef __U_BOOT__ + char peek_buf[2]; +#endif + int __promptme; + int promptmode; +#ifndef __U_BOOT__ + FILE *file; +#endif + int (*get) (struct in_str *); + int (*peek) (struct in_str *); +}; +#define b_getch(input) ((input)->get(input)) +#define b_peek(input) ((input)->peek(input)) + +#ifndef __U_BOOT__ +#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n" + +struct built_in_command { + char *cmd; /* name */ + char *descr; /* description */ + int (*function) (struct child_prog *); /* function ptr */ +}; +#endif + +/* define DEBUG_SHELL for debugging output (obviously ;-)) */ +#if 0 +#define DEBUG_SHELL +#endif + +/* This should be in utility.c */ +#ifdef DEBUG_SHELL +#ifndef __U_BOOT__ +static void debug_printf(const char *format, ...) +{ + va_list args; + va_start(args, format); + vfprintf(stderr, format, args); + va_end(args); +} +#else +#define debug_printf(fmt,args...) printf (fmt ,##args) +#endif +#else +static inline void debug_printf(const char *format, ...) { } +#endif +#define final_printf debug_printf + +#ifdef __U_BOOT__ +static void syntax_err(void) { + printf("syntax error\n"); +} +#else +static void __syntax(char *file, int line) { + error_msg("syntax error %s:%d", file, line); +} +#define syntax() __syntax(__FILE__, __LINE__) +#endif + +#ifdef __U_BOOT__ +static void *xmalloc(size_t size); +static void *xrealloc(void *ptr, size_t size); +#else +/* Index of subroutines: */ +/* function prototypes for builtins */ +static int builtin_cd(struct child_prog *child); +static int builtin_env(struct child_prog *child); +static int builtin_eval(struct child_prog *child); +static int builtin_exec(struct child_prog *child); +static int builtin_exit(struct child_prog *child); +static int builtin_export(struct child_prog *child); +static int builtin_fg_bg(struct child_prog *child); +static int builtin_help(struct child_prog *child); +static int builtin_jobs(struct child_prog *child); +static int builtin_pwd(struct child_prog *child); +static int builtin_read(struct child_prog *child); +static int builtin_set(struct child_prog *child); +static int builtin_shift(struct child_prog *child); +static int builtin_source(struct child_prog *child); +static int builtin_umask(struct child_prog *child); +static int builtin_unset(struct child_prog *child); +static int builtin_not_written(struct child_prog *child); +#endif +/* o_string manipulation: */ +static int b_check_space(o_string *o, int len); +static int b_addchr(o_string *o, int ch); +static void b_reset(o_string *o); +static int b_addqchr(o_string *o, int ch, int quote); +#ifndef __U_BOOT__ +static int b_adduint(o_string *o, unsigned int i); +#endif +/* in_str manipulations: */ +static int static_get(struct in_str *i); +static int static_peek(struct in_str *i); +static int file_get(struct in_str *i); +static int file_peek(struct in_str *i); +#ifndef __U_BOOT__ +static void setup_file_in_str(struct in_str *i, FILE *f); +#else +static void setup_file_in_str(struct in_str *i); +#endif +static void setup_string_in_str(struct in_str *i, const char *s); +#ifndef __U_BOOT__ +/* close_me manipulations: */ +static void mark_open(int fd); +static void mark_closed(int fd); +static void close_all(void); +#endif +/* "run" the final data structures: */ +static char *indenter(int i); +static int free_pipe_list(struct pipe *head, int indent); +static int free_pipe(struct pipe *pi, int indent); +/* really run the final data structures: */ +#ifndef __U_BOOT__ +static int setup_redirects(struct child_prog *prog, int squirrel[]); +#endif +static int run_list_real(struct pipe *pi); +#ifndef __U_BOOT__ +static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn)); +#endif +static int run_pipe_real(struct pipe *pi); +/* extended glob support: */ +#ifndef __U_BOOT__ +static int globhack(const char *src, int flags, glob_t *pglob); +static int glob_needed(const char *s); +static int xglob(o_string *dest, int flags, glob_t *pglob); +#endif +/* variable assignment: */ +static int is_assignment(const char *s); +/* data structure manipulation: */ +#ifndef __U_BOOT__ +static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input); +#endif +static void initialize_context(struct p_context *ctx); +static int done_word(o_string *dest, struct p_context *ctx); +static int done_command(struct p_context *ctx); +static int done_pipe(struct p_context *ctx, pipe_style type); +/* primary string parsing: */ +#ifndef __U_BOOT__ +static int redirect_dup_num(struct in_str *input); +static int redirect_opt_num(o_string *o); +static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end); +static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch); +#endif +static char *lookup_param(char *src); +static char *make_string(char **inp, int *nonnull); +static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input); +#ifndef __U_BOOT__ +static int parse_string(o_string *dest, struct p_context *ctx, const char *src); +#endif +static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger); +/* setup: */ +static int parse_stream_outer(struct in_str *inp, int flag); +#ifndef __U_BOOT__ +static int parse_string_outer(const char *s, int flag); +static int parse_file_outer(FILE *f); +#endif +#ifndef __U_BOOT__ +/* job management: */ +static int checkjobs(struct pipe* fg_pipe); +static void insert_bg_job(struct pipe *pi); +static void remove_bg_job(struct pipe *pi); +#endif +/* local variable support */ +static char **make_list_in(char **inp, char *name); +static char *insert_var_value(char *inp); +static char *insert_var_value_sub(char *inp, int tag_subst); + +#ifndef __U_BOOT__ +/* Table of built-in functions. They can be forked or not, depending on + * context: within pipes, they fork. As simple commands, they do not. + * When used in non-forking context, they can change global variables + * in the parent shell process. If forked, of course they can not. + * For example, 'unset foo | whatever' will parse and run, but foo will + * still be set at the end. */ +static struct built_in_command bltins[] = { + {"bg", "Resume a job in the background", builtin_fg_bg}, + {"break", "Exit for, while or until loop", builtin_not_written}, + {"cd", "Change working directory", builtin_cd}, + {"continue", "Continue for, while or until loop", builtin_not_written}, + {"env", "Print all environment variables", builtin_env}, + {"eval", "Construct and run shell command", builtin_eval}, + {"exec", "Exec command, replacing this shell with the exec'd process", + builtin_exec}, + {"exit", "Exit from shell()", builtin_exit}, + {"export", "Set environment variable", builtin_export}, + {"fg", "Bring job into the foreground", builtin_fg_bg}, + {"jobs", "Lists the active jobs", builtin_jobs}, + {"pwd", "Print current directory", builtin_pwd}, + {"read", "Input environment variable", builtin_read}, + {"return", "Return from a function", builtin_not_written}, + {"set", "Set/unset shell local variables", builtin_set}, + {"shift", "Shift positional parameters", builtin_shift}, + {"trap", "Trap signals", builtin_not_written}, + {"ulimit","Controls resource limits", builtin_not_written}, + {"umask","Sets file creation mask", builtin_umask}, + {"unset", "Unset environment variable", builtin_unset}, + {".", "Source-in and run commands in a file", builtin_source}, + {"help", "List shell built-in commands", builtin_help}, + {NULL, NULL, NULL} +}; + +static const char *set_cwd(void) +{ + if(cwd==unknown) + cwd = NULL; /* xgetcwd(arg) called free(arg) */ + cwd = xgetcwd((char *)cwd); + if (!cwd) + cwd = unknown; + return cwd; +} + +/* built-in 'eval' handler */ +static int builtin_eval(struct child_prog *child) +{ + char *str = NULL; + int rcode = EXIT_SUCCESS; + + if (child->argv[1]) { + str = make_string(child->argv + 1); + parse_string_outer(str, FLAG_EXIT_FROM_LOOP | + FLAG_PARSE_SEMICOLON); + free(str); + rcode = last_return_code; + } + return rcode; +} + +/* built-in 'cd ' handler */ +static int builtin_cd(struct child_prog *child) +{ + char *newdir; + if (child->argv[1] == NULL) + newdir = getenv("HOME"); + else + newdir = child->argv[1]; + if (chdir(newdir)) { + printf("cd: %s: %s\n", newdir, strerror(errno)); + return EXIT_FAILURE; + } + set_cwd(); + return EXIT_SUCCESS; +} + +/* built-in 'env' handler */ +static int builtin_env(struct child_prog *dummy) +{ + char **e = environ; + if (e == NULL) return EXIT_FAILURE; + for (; *e; e++) { + puts(*e); + } + return EXIT_SUCCESS; +} + +/* built-in 'exec' handler */ +static int builtin_exec(struct child_prog *child) +{ + if (child->argv[1] == NULL) + return EXIT_SUCCESS; /* Really? */ + child->argv++; + pseudo_exec(child); + /* never returns */ +} + +/* built-in 'exit' handler */ +static int builtin_exit(struct child_prog *child) +{ + if (child->argv[1] == NULL) + exit(last_return_code); + exit (atoi(child->argv[1])); +} + +/* built-in 'export VAR=value' handler */ +static int builtin_export(struct child_prog *child) +{ + int res = 0; + char *name = child->argv[1]; + + if (name == NULL) { + return (builtin_env(child)); + } + + name = strdup(name); + + if(name) { + char *value = strchr(name, '='); + + if (!value) { + char *tmp; + /* They are exporting something without an =VALUE */ + + value = get_local_var(name); + if (value) { + size_t ln = strlen(name); + + tmp = realloc(name, ln+strlen(value)+2); + if(tmp==NULL) + res = -1; + else { + sprintf(tmp+ln, "=%s", value); + name = tmp; + } + } else { + /* bash does not return an error when trying to export + * an undefined variable. Do likewise. */ + res = 1; + } + } + } + if (res<0) + perror_msg("export"); + else if(res==0) + res = set_local_var(name, 1); + else + res = 0; + free(name); + return res; +} + +/* built-in 'fg' and 'bg' handler */ +static int builtin_fg_bg(struct child_prog *child) +{ + int i, jobnum; + struct pipe *pi=NULL; + + if (!interactive) + return EXIT_FAILURE; + /* If they gave us no args, assume they want the last backgrounded task */ + if (!child->argv[1]) { + for (pi = job_list; pi; pi = pi->next) { + if (pi->jobid == last_jobid) { + break; + } + } + if (!pi) { + error_msg("%s: no current job", child->argv[0]); + return EXIT_FAILURE; + } + } else { + if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) { + error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]); + return EXIT_FAILURE; + } + for (pi = job_list; pi; pi = pi->next) { + if (pi->jobid == jobnum) { + break; + } + } + if (!pi) { + error_msg("%s: %d: no such job", child->argv[0], jobnum); + return EXIT_FAILURE; + } + } + + if (*child->argv[0] == 'f') { + /* Put the job into the foreground. */ + tcsetpgrp(shell_terminal, pi->pgrp); + } + + /* Restart the processes in the job */ + for (i = 0; i < pi->num_progs; i++) + pi->progs[i].is_stopped = 0; + + if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) { + if (i == ESRCH) { + remove_bg_job(pi); + } else { + perror_msg("kill (SIGCONT)"); + } + } + + pi->stopped_progs = 0; + return EXIT_SUCCESS; +} + +/* built-in 'help' handler */ +static int builtin_help(struct child_prog *dummy) +{ + struct built_in_command *x; + + printf("\nBuilt-in commands:\n"); + printf("-------------------\n"); + for (x = bltins; x->cmd; x++) { + if (x->descr==NULL) + continue; + printf("%s\t%s\n", x->cmd, x->descr); + } + printf("\n\n"); + return EXIT_SUCCESS; +} + +/* built-in 'jobs' handler */ +static int builtin_jobs(struct child_prog *child) +{ + struct pipe *job; + char *status_string; + + for (job = job_list; job; job = job->next) { + if (job->running_progs == job->stopped_progs) + status_string = "Stopped"; + else + status_string = "Running"; + + printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text); + } + return EXIT_SUCCESS; +} + + +/* built-in 'pwd' handler */ +static int builtin_pwd(struct child_prog *dummy) +{ + puts(set_cwd()); + return EXIT_SUCCESS; +} + +/* built-in 'read VAR' handler */ +static int builtin_read(struct child_prog *child) +{ + int res; + + if (child->argv[1]) { + char string[BUFSIZ]; + char *var = 0; + + string[0] = 0; /* In case stdin has only EOF */ + /* read string */ + fgets(string, sizeof(string), stdin); + chomp(string); + var = malloc(strlen(child->argv[1])+strlen(string)+2); + if(var) { + sprintf(var, "%s=%s", child->argv[1], string); + res = set_local_var(var, 0); + } else + res = -1; + if (res) + fprintf(stderr, "read: %m\n"); + free(var); /* So not move up to avoid breaking errno */ + return res; + } else { + do res=getchar(); while(res!='\n' && res!=EOF); + return 0; + } +} + +/* built-in 'set VAR=value' handler */ +static int builtin_set(struct child_prog *child) +{ + char *temp = child->argv[1]; + struct variables *e; + + if (temp == NULL) + for(e = top_vars; e; e=e->next) + printf("%s=%s\n", e->name, e->value); + else + set_local_var(temp, 0); + + return EXIT_SUCCESS; +} + + +/* Built-in 'shift' handler */ +static int builtin_shift(struct child_prog *child) +{ + int n=1; + if (child->argv[1]) { + n=atoi(child->argv[1]); + } + if (n>=0 && nargv[1] == NULL) + return EXIT_FAILURE; + + /* XXX search through $PATH is missing */ + input = fopen(child->argv[1], "r"); + if (!input) { + error_msg("Couldn't open file '%s'", child->argv[1]); + return EXIT_FAILURE; + } + + /* Now run the file */ + /* XXX argv and argc are broken; need to save old global_argv + * (pointer only is OK!) on this stack frame, + * set global_argv=child->argv+1, recurse, and restore. */ + mark_open(fileno(input)); + status = parse_file_outer(input); + mark_closed(fileno(input)); + fclose(input); + return (status); +} + +static int builtin_umask(struct child_prog *child) +{ + mode_t new_umask; + const char *arg = child->argv[1]; + char *end; + if (arg) { + new_umask=strtoul(arg, &end, 8); + if (*end!='\0' || end == arg) { + return EXIT_FAILURE; + } + } else { + printf("%.3o\n", (unsigned int) (new_umask=umask(0))); + } + umask(new_umask); + return EXIT_SUCCESS; +} + +/* built-in 'unset VAR' handler */ +static int builtin_unset(struct child_prog *child) +{ + /* bash returned already true */ + unset_local_var(child->argv[1]); + return EXIT_SUCCESS; +} + +static int builtin_not_written(struct child_prog *child) +{ + printf("builtin_%s not written\n",child->argv[0]); + return EXIT_FAILURE; +} +#endif + +static int b_check_space(o_string *o, int len) +{ + /* It would be easy to drop a more restrictive policy + * in here, such as setting a maximum string length */ + if (o->length + len > o->maxlen) { + char *old_data = o->data; + /* assert (data == NULL || o->maxlen != 0); */ + o->maxlen += max(2*len, B_CHUNK); + o->data = realloc(o->data, 1 + o->maxlen); + if (o->data == NULL) { + free(old_data); + } + } + return o->data == NULL; +} + +static int b_addchr(o_string *o, int ch) +{ + debug_printf("b_addchr: %c %d %p\n", ch, o->length, o); + if (b_check_space(o, 1)) return B_NOSPAC; + o->data[o->length] = ch; + o->length++; + o->data[o->length] = '\0'; + return 0; +} + +static void b_reset(o_string *o) +{ + o->length = 0; + o->nonnull = 0; + if (o->data != NULL) *o->data = '\0'; +} + +static void b_free(o_string *o) +{ + b_reset(o); + free(o->data); + o->data = NULL; + o->maxlen = 0; +} + +/* My analysis of quoting semantics tells me that state information + * is associated with a destination, not a source. + */ +static int b_addqchr(o_string *o, int ch, int quote) +{ + if (quote && strchr("*?[\\",ch)) { + int rc; + rc = b_addchr(o, '\\'); + if (rc) return rc; + } + return b_addchr(o, ch); +} + +#ifndef __U_BOOT__ +static int b_adduint(o_string *o, unsigned int i) +{ + int r; + char *p = simple_itoa(i); + /* no escape checking necessary */ + do r=b_addchr(o, *p++); while (r==0 && *p); + return r; +} +#endif + +static int static_get(struct in_str *i) +{ + int ch = *i->p++; + if (ch=='\0') return EOF; + return ch; +} + +static int static_peek(struct in_str *i) +{ + return *i->p; +} + +#ifndef __U_BOOT__ +static inline void cmdedit_set_initial_prompt(void) +{ +#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT + PS1 = NULL; +#else + PS1 = getenv("PS1"); + if(PS1==0) + PS1 = "\\w \\$ "; +#endif +} + +static inline void setup_prompt_string(int promptmode, char **prompt_str) +{ + debug_printf("setup_prompt_string %d ",promptmode); +#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT + /* Set up the prompt */ + if (promptmode == 1) { + free(PS1); + PS1=xmalloc(strlen(cwd)+4); + sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# "); + *prompt_str = PS1; + } else { + *prompt_str = PS2; + } +#else + *prompt_str = (promptmode==1)? PS1 : PS2; +#endif + debug_printf("result %s\n",*prompt_str); +} +#endif + +static void get_user_input(struct in_str *i) +{ +#ifndef __U_BOOT__ + char *prompt_str; + static char the_command[BUFSIZ]; + + setup_prompt_string(i->promptmode, &prompt_str); +#ifdef CONFIG_FEATURE_COMMAND_EDITING + /* + ** enable command line editing only while a command line + ** is actually being read; otherwise, we'll end up bequeathing + ** atexit() handlers and other unwanted stuff to our + ** child processes (rob@sysgo.de) + */ + cmdedit_read_input(prompt_str, the_command); +#else + fputs(prompt_str, stdout); + fflush(stdout); + the_command[0]=fgetc(i->file); + the_command[1]='\0'; +#endif + fflush(stdout); + i->p = the_command; +#else + int n; + static char the_command[CONFIG_SYS_CBSIZE + 1]; + +#ifdef CONFIG_BOOT_RETRY_TIME +# ifndef CONFIG_RESET_TO_RETRY +# error "This currently only works with CONFIG_RESET_TO_RETRY enabled" +# endif + reset_cmd_timeout(); +#endif + i->__promptme = 1; + if (i->promptmode == 1) { + n = readline(CONFIG_SYS_PROMPT); + } else { + n = readline(CONFIG_SYS_PROMPT_HUSH_PS2); + } +#ifdef CONFIG_BOOT_RETRY_TIME + if (n == -2) { + puts("\nTimeout waiting for command\n"); +# ifdef CONFIG_RESET_TO_RETRY + do_reset(NULL, 0, 0, NULL); +# else +# error "This currently only works with CONFIG_RESET_TO_RETRY enabled" +# endif + } +#endif + if (n == -1 ) { + flag_repeat = 0; + i->__promptme = 0; + } + n = strlen(console_buffer); + console_buffer[n] = '\n'; + console_buffer[n+1]= '\0'; + if (had_ctrlc()) flag_repeat = 0; + clear_ctrlc(); + do_repeat = 0; + if (i->promptmode == 1) { + if (console_buffer[0] == '\n'&& flag_repeat == 0) { + strcpy(the_command,console_buffer); + } + else { + if (console_buffer[0] != '\n') { + strcpy(the_command,console_buffer); + flag_repeat = 1; + } + else { + do_repeat = 1; + } + } + i->p = the_command; + } + else { + if (console_buffer[0] != '\n') { + if (strlen(the_command) + strlen(console_buffer) + < CONFIG_SYS_CBSIZE) { + n = strlen(the_command); + the_command[n-1] = ' '; + strcpy(&the_command[n],console_buffer); + } + else { + the_command[0] = '\n'; + the_command[1] = '\0'; + flag_repeat = 0; + } + } + if (i->__promptme == 0) { + the_command[0] = '\n'; + the_command[1] = '\0'; + } + i->p = console_buffer; + } +#endif +} + +/* This is the magic location that prints prompts + * and gets data back from the user */ +static int file_get(struct in_str *i) +{ + int ch; + + ch = 0; + /* If there is data waiting, eat it up */ + if (i->p && *i->p) { + ch = *i->p++; + } else { + /* need to double check i->file because we might be doing something + * more complicated by now, like sourcing or substituting. */ +#ifndef __U_BOOT__ + if (i->__promptme && interactive && i->file == stdin) { + while(! i->p || (interactive && strlen(i->p)==0) ) { +#else + while(! i->p || strlen(i->p)==0 ) { +#endif + get_user_input(i); + } + i->promptmode=2; +#ifndef __U_BOOT__ + i->__promptme = 0; +#endif + if (i->p && *i->p) { + ch = *i->p++; + } +#ifndef __U_BOOT__ + } else { + ch = fgetc(i->file); + } + +#endif + debug_printf("b_getch: got a %d\n", ch); + } +#ifndef __U_BOOT__ + if (ch == '\n') i->__promptme=1; +#endif + return ch; +} + +/* All the callers guarantee this routine will never be + * used right after a newline, so prompting is not needed. + */ +static int file_peek(struct in_str *i) +{ +#ifndef __U_BOOT__ + if (i->p && *i->p) { +#endif + return *i->p; +#ifndef __U_BOOT__ + } else { + i->peek_buf[0] = fgetc(i->file); + i->peek_buf[1] = '\0'; + i->p = i->peek_buf; + debug_printf("b_peek: got a %d\n", *i->p); + return *i->p; + } +#endif +} + +#ifndef __U_BOOT__ +static void setup_file_in_str(struct in_str *i, FILE *f) +#else +static void setup_file_in_str(struct in_str *i) +#endif +{ + i->peek = file_peek; + i->get = file_get; + i->__promptme=1; + i->promptmode=1; +#ifndef __U_BOOT__ + i->file = f; +#endif + i->p = NULL; +} + +static void setup_string_in_str(struct in_str *i, const char *s) +{ + i->peek = static_peek; + i->get = static_get; + i->__promptme=1; + i->promptmode=1; + i->p = s; +} + +#ifndef __U_BOOT__ +static void mark_open(int fd) +{ + struct close_me *new = xmalloc(sizeof(struct close_me)); + new->fd = fd; + new->next = close_me_head; + close_me_head = new; +} + +static void mark_closed(int fd) +{ + struct close_me *tmp; + if (close_me_head == NULL || close_me_head->fd != fd) + error_msg_and_die("corrupt close_me"); + tmp = close_me_head; + close_me_head = close_me_head->next; + free(tmp); +} + +static void close_all(void) +{ + struct close_me *c; + for (c=close_me_head; c; c=c->next) { + close(c->fd); + } + close_me_head = NULL; +} + +/* squirrel != NULL means we squirrel away copies of stdin, stdout, + * and stderr if they are redirected. */ +static int setup_redirects(struct child_prog *prog, int squirrel[]) +{ + int openfd, mode; + struct redir_struct *redir; + + for (redir=prog->redirects; redir; redir=redir->next) { + if (redir->dup == -1 && redir->word.gl_pathv == NULL) { + /* something went wrong in the parse. Pretend it didn't happen */ + continue; + } + if (redir->dup == -1) { + mode=redir_table[redir->type].mode; + openfd = open(redir->word.gl_pathv[0], mode, 0666); + if (openfd < 0) { + /* this could get lost if stderr has been redirected, but + bash and ash both lose it as well (though zsh doesn't!) */ + perror_msg("error opening %s", redir->word.gl_pathv[0]); + return 1; + } + } else { + openfd = redir->dup; + } + + if (openfd != redir->fd) { + if (squirrel && redir->fd < 3) { + squirrel[redir->fd] = dup(redir->fd); + } + if (openfd == -3) { + close(openfd); + } else { + dup2(openfd, redir->fd); + if (redir->dup == -1) + close (openfd); + } + } + } + return 0; +} + +static void restore_redirects(int squirrel[]) +{ + int i, fd; + for (i=0; i<3; i++) { + fd = squirrel[i]; + if (fd != -1) { + /* No error checking. I sure wouldn't know what + * to do with an error if I found one! */ + dup2(fd, i); + close(fd); + } + } +} + +/* never returns */ +/* XXX no exit() here. If you don't exec, use _exit instead. + * The at_exit handlers apparently confuse the calling process, + * in particular stdin handling. Not sure why? */ +static void pseudo_exec(struct child_prog *child) +{ + int i, rcode; + char *p; + struct built_in_command *x; + if (child->argv) { + for (i=0; is_assignment(child->argv[i]); i++) { + debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]); + p = insert_var_value(child->argv[i]); + putenv(strdup(p)); + if (p != child->argv[i]) free(p); + } + child->argv+=i; /* XXX this hack isn't so horrible, since we are about + to exit, and therefore don't need to keep data + structures consistent for free() use. */ + /* If a variable is assigned in a forest, and nobody listens, + * was it ever really set? + */ + if (child->argv[0] == NULL) { + _exit(EXIT_SUCCESS); + } + + /* + * Check if the command matches any of the builtins. + * Depending on context, this might be redundant. But it's + * easier to waste a few CPU cycles than it is to figure out + * if this is one of those cases. + */ + for (x = bltins; x->cmd; x++) { + if (strcmp(child->argv[0], x->cmd) == 0 ) { + debug_printf("builtin exec %s\n", child->argv[0]); + rcode = x->function(child); + fflush(stdout); + _exit(rcode); + } + } + + /* Check if the command matches any busybox internal commands + * ("applets") here. + * FIXME: This feature is not 100% safe, since + * BusyBox is not fully reentrant, so we have no guarantee the things + * from the .bss are still zeroed, or that things from .data are still + * at their defaults. We could exec ourself from /proc/self/exe, but I + * really dislike relying on /proc for things. We could exec ourself + * from global_argv[0], but if we are in a chroot, we may not be able + * to find ourself... */ +#ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL + { + int argc_l; + char** argv_l=child->argv; + char *name = child->argv[0]; + +#ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN + /* Following discussions from November 2000 on the busybox mailing + * list, the default configuration, (without + * get_last_path_component()) lets the user force use of an + * external command by specifying the full (with slashes) filename. + * If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets + * _aways_ override external commands, so if you want to run + * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the + * filesystem and is _not_ busybox. Some systems may want this, + * most do not. */ + name = get_last_path_component(name); +#endif + /* Count argc for use in a second... */ + for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++); + optind = 1; + debug_printf("running applet %s\n", name); + run_applet_by_name(name, argc_l, child->argv); + } +#endif + debug_printf("exec of %s\n",child->argv[0]); + execvp(child->argv[0],child->argv); + perror_msg("couldn't exec: %s",child->argv[0]); + _exit(1); + } else if (child->group) { + debug_printf("runtime nesting to group\n"); + interactive=0; /* crucial!!!! */ + rcode = run_list_real(child->group); + /* OK to leak memory by not calling free_pipe_list, + * since this process is about to exit */ + _exit(rcode); + } else { + /* Can happen. See what bash does with ">foo" by itself. */ + debug_printf("trying to pseudo_exec null command\n"); + _exit(EXIT_SUCCESS); + } +} + +static void insert_bg_job(struct pipe *pi) +{ + struct pipe *thejob; + + /* Linear search for the ID of the job to use */ + pi->jobid = 1; + for (thejob = job_list; thejob; thejob = thejob->next) + if (thejob->jobid >= pi->jobid) + pi->jobid = thejob->jobid + 1; + + /* add thejob to the list of running jobs */ + if (!job_list) { + thejob = job_list = xmalloc(sizeof(*thejob)); + } else { + for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */; + thejob->next = xmalloc(sizeof(*thejob)); + thejob = thejob->next; + } + + /* physically copy the struct job */ + memcpy(thejob, pi, sizeof(struct pipe)); + thejob->next = NULL; + thejob->running_progs = thejob->num_progs; + thejob->stopped_progs = 0; + thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */ + + /*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */ + { + char *bar=thejob->text; + char **foo=pi->progs[0].argv; + while(foo && *foo) { + bar += sprintf(bar, "%s ", *foo++); + } + } + + /* we don't wait for background thejobs to return -- append it + to the list of backgrounded thejobs and leave it alone */ + printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid); + last_bg_pid = thejob->progs[0].pid; + last_jobid = thejob->jobid; +} + +/* remove a backgrounded job */ +static void remove_bg_job(struct pipe *pi) +{ + struct pipe *prev_pipe; + + if (pi == job_list) { + job_list = pi->next; + } else { + prev_pipe = job_list; + while (prev_pipe->next != pi) + prev_pipe = prev_pipe->next; + prev_pipe->next = pi->next; + } + if (job_list) + last_jobid = job_list->jobid; + else + last_jobid = 0; + + pi->stopped_progs = 0; + free_pipe(pi, 0); + free(pi); +} + +/* Checks to see if any processes have exited -- if they + have, figure out why and see if a job has completed */ +static int checkjobs(struct pipe* fg_pipe) +{ + int attributes; + int status; + int prognum = 0; + struct pipe *pi; + pid_t childpid; + + attributes = WUNTRACED; + if (fg_pipe==NULL) { + attributes |= WNOHANG; + } + + while ((childpid = waitpid(-1, &status, attributes)) > 0) { + if (fg_pipe) { + int i, rcode = 0; + for (i=0; i < fg_pipe->num_progs; i++) { + if (fg_pipe->progs[i].pid == childpid) { + if (i==fg_pipe->num_progs-1) + rcode=WEXITSTATUS(status); + (fg_pipe->num_progs)--; + return(rcode); + } + } + } + + for (pi = job_list; pi; pi = pi->next) { + prognum = 0; + while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) { + prognum++; + } + if (prognum < pi->num_progs) + break; + } + + if(pi==NULL) { + debug_printf("checkjobs: pid %d was not in our list!\n", childpid); + continue; + } + + if (WIFEXITED(status) || WIFSIGNALED(status)) { + /* child exited */ + pi->running_progs--; + pi->progs[prognum].pid = 0; + + if (!pi->running_progs) { + printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text); + remove_bg_job(pi); + } + } else { + /* child stopped */ + pi->stopped_progs++; + pi->progs[prognum].is_stopped = 1; + +#if 0 + /* Printing this stuff is a pain, since it tends to + * overwrite the prompt an inconveinient moments. So + * don't do that. */ + if (pi->stopped_progs == pi->num_progs) { + printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text); + } +#endif + } + } + + if (childpid == -1 && errno != ECHILD) + perror_msg("waitpid"); + + /* move the shell to the foreground */ + /*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */ + /* perror_msg("tcsetpgrp-2"); */ + return -1; +} + +/* Figure out our controlling tty, checking in order stderr, + * stdin, and stdout. If check_pgrp is set, also check that + * we belong to the foreground process group associated with + * that tty. The value of shell_terminal is needed in order to call + * tcsetpgrp(shell_terminal, ...); */ +void controlling_tty(int check_pgrp) +{ + pid_t curpgrp; + + if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0 + && (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0 + && (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0) + goto shell_terminal_error; + + if (check_pgrp && curpgrp != getpgid(0)) + goto shell_terminal_error; + + return; + +shell_terminal_error: + shell_terminal = -1; + return; +} +#endif + +/* run_pipe_real() starts all the jobs, but doesn't wait for anything + * to finish. See checkjobs(). + * + * return code is normally -1, when the caller has to wait for children + * to finish to determine the exit status of the pipe. If the pipe + * is a simple builtin command, however, the action is done by the + * time run_pipe_real returns, and the exit code is provided as the + * return value. + * + * The input of the pipe is always stdin, the output is always + * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus, + * because it tries to avoid running the command substitution in + * subshell, when that is in fact necessary. The subshell process + * now has its stdout directed to the input of the appropriate pipe, + * so this routine is noticeably simpler. + */ +static int run_pipe_real(struct pipe *pi) +{ + int i; +#ifndef __U_BOOT__ + int nextin, nextout; + int pipefds[2]; /* pipefds[0] is for reading */ + struct child_prog *child; + struct built_in_command *x; + char *p; +# if __GNUC__ + /* Avoid longjmp clobbering */ + (void) &i; + (void) &nextin; + (void) &nextout; + (void) &child; +# endif +#else + int nextin; + int flag = do_repeat ? CMD_FLAG_REPEAT : 0; + struct child_prog *child; + char *p; +# if __GNUC__ + /* Avoid longjmp clobbering */ + (void) &i; + (void) &nextin; + (void) &child; +# endif +#endif /* __U_BOOT__ */ + + nextin = 0; +#ifndef __U_BOOT__ + pi->pgrp = -1; +#endif + + /* Check if this is a simple builtin (not part of a pipe). + * Builtins within pipes have to fork anyway, and are handled in + * pseudo_exec. "echo foo | read bar" doesn't work on bash, either. + */ + if (pi->num_progs == 1) child = & (pi->progs[0]); +#ifndef __U_BOOT__ + if (pi->num_progs == 1 && child->group && child->subshell == 0) { + int squirrel[] = {-1, -1, -1}; + int rcode; + debug_printf("non-subshell grouping\n"); + setup_redirects(child, squirrel); + /* XXX could we merge code with following builtin case, + * by creating a pseudo builtin that calls run_list_real? */ + rcode = run_list_real(child->group); + restore_redirects(squirrel); +#else + if (pi->num_progs == 1 && child->group) { + int rcode; + debug_printf("non-subshell grouping\n"); + rcode = run_list_real(child->group); +#endif + return rcode; + } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) { + for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ } + if (i!=0 && child->argv[i]==NULL) { + /* assignments, but no command: set the local environment */ + for (i=0; child->argv[i]!=NULL; i++) { + + /* Ok, this case is tricky. We have to decide if this is a + * local variable, or an already exported variable. If it is + * already exported, we have to export the new value. If it is + * not exported, we need only set this as a local variable. + * This junk is all to decide whether or not to export this + * variable. */ + int export_me=0; + char *name, *value; + name = xstrdup(child->argv[i]); + debug_printf("Local environment set: %s\n", name); + value = strchr(name, '='); + if (value) + *value=0; +#ifndef __U_BOOT__ + if ( get_local_var(name)) { + export_me=1; + } +#endif + free(name); + p = insert_var_value(child->argv[i]); + set_local_var(p, export_me); + if (p != child->argv[i]) free(p); + } + return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */ + } + for (i = 0; is_assignment(child->argv[i]); i++) { + p = insert_var_value(child->argv[i]); +#ifndef __U_BOOT__ + putenv(strdup(p)); +#else + set_local_var(p, 0); +#endif + if (p != child->argv[i]) { + child->sp--; + free(p); + } + } + if (child->sp) { + char * str = NULL; + + str = make_string(child->argv + i, + child->argv_nonnull + i); + parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING); + free(str); + return last_return_code; + } +#ifndef __U_BOOT__ + for (x = bltins; x->cmd; x++) { + if (strcmp(child->argv[i], x->cmd) == 0 ) { + int squirrel[] = {-1, -1, -1}; + int rcode; + if (x->function == builtin_exec && child->argv[i+1]==NULL) { + debug_printf("magic exec\n"); + setup_redirects(child,NULL); + return EXIT_SUCCESS; + } + debug_printf("builtin inline %s\n", child->argv[0]); + /* XXX setup_redirects acts on file descriptors, not FILEs. + * This is perfect for work that comes after exec(). + * Is it really safe for inline use? Experimentally, + * things seem to work with glibc. */ + setup_redirects(child, squirrel); + + child->argv += i; /* XXX horrible hack */ + rcode = x->function(child); + /* XXX restore hack so free() can work right */ + child->argv -= i; + restore_redirects(squirrel); + } + return rcode; + } +#else + /* check ";", because ,example , argv consist from + * "help;flinfo" must not execute + */ + if (strchr(child->argv[i], ';')) { + printf("Unknown command '%s' - try 'help' or use " + "'run' command\n", child->argv[i]); + return -1; + } + /* Process the command */ + return cmd_process(flag, child->argc, child->argv, + &flag_repeat, NULL); +#endif + } +#ifndef __U_BOOT__ + + for (i = 0; i < pi->num_progs; i++) { + child = & (pi->progs[i]); + + /* pipes are inserted between pairs of commands */ + if ((i + 1) < pi->num_progs) { + if (pipe(pipefds)<0) perror_msg_and_die("pipe"); + nextout = pipefds[1]; + } else { + nextout=1; + pipefds[0] = -1; + } + + /* XXX test for failed fork()? */ + if (!(child->pid = fork())) { + /* Set the handling for job control signals back to the default. */ + signal(SIGINT, SIG_DFL); + signal(SIGQUIT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + signal(SIGTSTP, SIG_DFL); + signal(SIGTTIN, SIG_DFL); + signal(SIGTTOU, SIG_DFL); + signal(SIGCHLD, SIG_DFL); + + close_all(); + + if (nextin != 0) { + dup2(nextin, 0); + close(nextin); + } + if (nextout != 1) { + dup2(nextout, 1); + close(nextout); + } + if (pipefds[0]!=-1) { + close(pipefds[0]); /* opposite end of our output pipe */ + } + + /* Like bash, explicit redirects override pipes, + * and the pipe fd is available for dup'ing. */ + setup_redirects(child,NULL); + + if (interactive && pi->followup!=PIPE_BG) { + /* If we (the child) win the race, put ourselves in the process + * group whose leader is the first process in this pipe. */ + if (pi->pgrp < 0) { + pi->pgrp = getpid(); + } + if (setpgid(0, pi->pgrp) == 0) { + tcsetpgrp(2, pi->pgrp); + } + } + + pseudo_exec(child); + } + + + /* put our child in the process group whose leader is the + first process in this pipe */ + if (pi->pgrp < 0) { + pi->pgrp = child->pid; + } + /* Don't check for errors. The child may be dead already, + * in which case setpgid returns error code EACCES. */ + setpgid(child->pid, pi->pgrp); + + if (nextin != 0) + close(nextin); + if (nextout != 1) + close(nextout); + + /* If there isn't another process, nextin is garbage + but it doesn't matter */ + nextin = pipefds[0]; + } +#endif + return -1; +} + +static int run_list_real(struct pipe *pi) +{ + char *save_name = NULL; + char **list = NULL; + char **save_list = NULL; + struct pipe *rpipe; + int flag_rep = 0; +#ifndef __U_BOOT__ + int save_num_progs; +#endif + int rcode=0, flag_skip=1; + int flag_restore = 0; + int if_code=0, next_if_code=0; /* need double-buffer to handle elif */ + reserved_style rmode, skip_more_in_this_rmode=RES_XXXX; + /* check syntax for "for" */ + for (rpipe = pi; rpipe; rpipe = rpipe->next) { + if ((rpipe->r_mode == RES_IN || + rpipe->r_mode == RES_FOR) && + (rpipe->next == NULL)) { + syntax(); +#ifdef __U_BOOT__ + flag_repeat = 0; +#endif + return 1; + } + if ((rpipe->r_mode == RES_IN && + (rpipe->next->r_mode == RES_IN && + rpipe->next->progs->argv != NULL))|| + (rpipe->r_mode == RES_FOR && + rpipe->next->r_mode != RES_IN)) { + syntax(); +#ifdef __U_BOOT__ + flag_repeat = 0; +#endif + return 1; + } + } + for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) { + if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL || + pi->r_mode == RES_FOR) { +#ifdef __U_BOOT__ + /* check Ctrl-C */ + ctrlc(); + if ((had_ctrlc())) { + return 1; + } +#endif + flag_restore = 0; + if (!rpipe) { + flag_rep = 0; + rpipe = pi; + } + } + rmode = pi->r_mode; + 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); + if (rmode == skip_more_in_this_rmode && flag_skip) { + if (pi->followup == PIPE_SEQ) flag_skip=0; + continue; + } + flag_skip = 1; + skip_more_in_this_rmode = RES_XXXX; + if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code; + if (rmode == RES_THEN && if_code) continue; + if (rmode == RES_ELSE && !if_code) continue; + if (rmode == RES_ELIF && !if_code) break; + if (rmode == RES_FOR && pi->num_progs) { + if (!list) { + /* if no variable values after "in" we skip "for" */ + if (!pi->next->progs->argv) continue; + /* create list of variable values */ + list = make_list_in(pi->next->progs->argv, + pi->progs->argv[0]); + save_list = list; + save_name = pi->progs->argv[0]; + pi->progs->argv[0] = NULL; + flag_rep = 1; + } + if (!(*list)) { + free(pi->progs->argv[0]); + free(save_list); + list = NULL; + flag_rep = 0; + pi->progs->argv[0] = save_name; +#ifndef __U_BOOT__ + pi->progs->glob_result.gl_pathv[0] = + pi->progs->argv[0]; +#endif + continue; + } else { + /* insert new value from list for variable */ + if (pi->progs->argv[0]) + free(pi->progs->argv[0]); + pi->progs->argv[0] = *list++; +#ifndef __U_BOOT__ + pi->progs->glob_result.gl_pathv[0] = + pi->progs->argv[0]; +#endif + } + } + if (rmode == RES_IN) continue; + if (rmode == RES_DO) { + if (!flag_rep) continue; + } + if ((rmode == RES_DONE)) { + if (flag_rep) { + flag_restore = 1; + } else { + rpipe = NULL; + } + } + if (pi->num_progs == 0) continue; +#ifndef __U_BOOT__ + save_num_progs = pi->num_progs; /* save number of programs */ +#endif + rcode = run_pipe_real(pi); + debug_printf("run_pipe_real returned %d\n",rcode); +#ifndef __U_BOOT__ + if (rcode!=-1) { + /* We only ran a builtin: rcode was set by the return value + * of run_pipe_real(), and we don't need to wait for anything. */ + } else if (pi->followup==PIPE_BG) { + /* XXX check bash's behavior with nontrivial pipes */ + /* XXX compute jobid */ + /* XXX what does bash do with attempts to background builtins? */ + insert_bg_job(pi); + rcode = EXIT_SUCCESS; + } else { + if (interactive) { + /* move the new process group into the foreground */ + if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY) + perror_msg("tcsetpgrp-3"); + rcode = checkjobs(pi); + /* move the shell to the foreground */ + if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY) + perror_msg("tcsetpgrp-4"); + } else { + rcode = checkjobs(pi); + } + debug_printf("checkjobs returned %d\n",rcode); + } + last_return_code=rcode; +#else + if (rcode < -1) { + last_return_code = -rcode - 2; + return -2; /* exit */ + } + last_return_code=(rcode == 0) ? 0 : 1; +#endif +#ifndef __U_BOOT__ + pi->num_progs = save_num_progs; /* restore number of programs */ +#endif + if ( rmode == RES_IF || rmode == RES_ELIF ) + next_if_code=rcode; /* can be overwritten a number of times */ + if (rmode == RES_WHILE) + flag_rep = !last_return_code; + if (rmode == RES_UNTIL) + flag_rep = last_return_code; + if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) || + (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) ) + skip_more_in_this_rmode=rmode; +#ifndef __U_BOOT__ + checkjobs(NULL); +#endif + } + return rcode; +} + +/* broken, of course, but OK for testing */ +static char *indenter(int i) +{ + static char blanks[]=" "; + return &blanks[sizeof(blanks)-i-1]; +} + +/* return code is the exit status of the pipe */ +static int free_pipe(struct pipe *pi, int indent) +{ + char **p; + struct child_prog *child; +#ifndef __U_BOOT__ + struct redir_struct *r, *rnext; +#endif + int a, i, ret_code=0; + char *ind = indenter(indent); + +#ifndef __U_BOOT__ + if (pi->stopped_progs > 0) + return ret_code; + final_printf("%s run pipe: (pid %d)\n",ind,getpid()); +#endif + for (i=0; inum_progs; i++) { + child = &pi->progs[i]; + final_printf("%s command %d:\n",ind,i); + if (child->argv) { + for (a=0,p=child->argv; *p; a++,p++) { + final_printf("%s argv[%d] = %s\n",ind,a,*p); + } +#ifndef __U_BOOT__ + globfree(&child->glob_result); +#else + for (a = 0; a < child->argc; a++) { + free(child->argv[a]); + } + free(child->argv); + free(child->argv_nonnull); + child->argc = 0; +#endif + child->argv=NULL; + } else if (child->group) { +#ifndef __U_BOOT__ + final_printf("%s begin group (subshell:%d)\n",ind, child->subshell); +#endif + ret_code = free_pipe_list(child->group,indent+3); + final_printf("%s end group\n",ind); + } else { + final_printf("%s (nil)\n",ind); + } +#ifndef __U_BOOT__ + for (r=child->redirects; r; r=rnext) { + final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip); + if (r->dup == -1) { + /* guard against the case >$FOO, where foo is unset or blank */ + if (r->word.gl_pathv) { + final_printf(" %s\n", *r->word.gl_pathv); + globfree(&r->word); + } + } else { + final_printf("&%d\n", r->dup); + } + rnext=r->next; + free(r); + } + child->redirects=NULL; +#endif + } + free(pi->progs); /* children are an array, they get freed all at once */ + pi->progs=NULL; + return ret_code; +} + +static int free_pipe_list(struct pipe *head, int indent) +{ + int rcode=0; /* if list has no members */ + struct pipe *pi, *next; + char *ind = indenter(indent); + for (pi=head; pi; pi=next) { + final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode); + rcode = free_pipe(pi, indent); + final_printf("%s pipe followup code %d\n", ind, pi->followup); + next=pi->next; + pi->next=NULL; + free(pi); + } + return rcode; +} + +/* Select which version we will use */ +static int run_list(struct pipe *pi) +{ + int rcode=0; +#ifndef __U_BOOT__ + if (fake_mode==0) { +#endif + rcode = run_list_real(pi); +#ifndef __U_BOOT__ + } +#endif + /* free_pipe_list has the side effect of clearing memory + * In the long run that function can be merged with run_list_real, + * but doing that now would hobble the debugging effort. */ + free_pipe_list(pi,0); + return rcode; +} + +/* The API for glob is arguably broken. This routine pushes a non-matching + * string into the output structure, removing non-backslashed backslashes. + * If someone can prove me wrong, by performing this function within the + * original glob(3) api, feel free to rewrite this routine into oblivion. + * Return code (0 vs. GLOB_NOSPACE) matches glob(3). + * XXX broken if the last character is '\\', check that before calling. + */ +#ifndef __U_BOOT__ +static int globhack(const char *src, int flags, glob_t *pglob) +{ + int cnt=0, pathc; + const char *s; + char *dest; + for (cnt=1, s=src; s && *s; s++) { + if (*s == '\\') s++; + cnt++; + } + dest = malloc(cnt); + if (!dest) return GLOB_NOSPACE; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathv=NULL; + pglob->gl_pathc=0; + pglob->gl_offs=0; + pglob->gl_offs=0; + } + pathc = ++pglob->gl_pathc; + pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv)); + if (pglob->gl_pathv == NULL) return GLOB_NOSPACE; + pglob->gl_pathv[pathc-1]=dest; + pglob->gl_pathv[pathc]=NULL; + for (s=src; s && *s; s++, dest++) { + if (*s == '\\') s++; + *dest = *s; + } + *dest='\0'; + return 0; +} + +/* XXX broken if the last character is '\\', check that before calling */ +static int glob_needed(const char *s) +{ + for (; *s; s++) { + if (*s == '\\') s++; + if (strchr("*[?",*s)) return 1; + } + return 0; +} + +#if 0 +static void globprint(glob_t *pglob) +{ + int i; + debug_printf("glob_t at %p:\n", pglob); + debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n", + pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags); + for (i=0; igl_pathc; i++) + debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i, + pglob->gl_pathv[i], pglob->gl_pathv[i]); +} +#endif + +static int xglob(o_string *dest, int flags, glob_t *pglob) +{ + int gr; + + /* short-circuit for null word */ + /* we can code this better when the debug_printf's are gone */ + if (dest->length == 0) { + if (dest->nonnull) { + /* bash man page calls this an "explicit" null */ + gr = globhack(dest->data, flags, pglob); + debug_printf("globhack returned %d\n",gr); + } else { + return 0; + } + } else if (glob_needed(dest->data)) { + gr = glob(dest->data, flags, NULL, pglob); + debug_printf("glob returned %d\n",gr); + if (gr == GLOB_NOMATCH) { + /* quote removal, or more accurately, backslash removal */ + gr = globhack(dest->data, flags, pglob); + debug_printf("globhack returned %d\n",gr); + } + } else { + gr = globhack(dest->data, flags, pglob); + debug_printf("globhack returned %d\n",gr); + } + if (gr == GLOB_NOSPACE) + error_msg_and_die("out of memory during glob"); + if (gr != 0) { /* GLOB_ABORTED ? */ + error_msg("glob(3) error %d",gr); + } + /* globprint(glob_target); */ + return gr; +} +#endif + +#ifdef __U_BOOT__ +static char *get_dollar_var(char ch); +#endif + +/* This is used to get/check local shell variables */ +char *get_local_var(const char *s) +{ + struct variables *cur; + + if (!s) + return NULL; + +#ifdef __U_BOOT__ + if (*s == '$') + return get_dollar_var(s[1]); +#endif + + for (cur = top_vars; cur; cur=cur->next) + if(strcmp(cur->name, s)==0) + return cur->value; + return NULL; +} + +/* This is used to set local shell variables + flg_export==0 if only local (not exporting) variable + flg_export==1 if "new" exporting environ + flg_export>1 if current startup environ (not call putenv()) */ +int set_local_var(const char *s, int flg_export) +{ + char *name, *value; + int result=0; + struct variables *cur; + +#ifdef __U_BOOT__ + /* might be possible! */ + if (!isalpha(*s)) + return -1; +#endif + + name=strdup(s); + +#ifdef __U_BOOT__ + if (getenv(name) != NULL) { + printf ("ERROR: " + "There is a global environment variable with the same name.\n"); + free(name); + return -1; + } +#endif + /* Assume when we enter this function that we are already in + * NAME=VALUE format. So the first order of business is to + * split 's' on the '=' into 'name' and 'value' */ + value = strchr(name, '='); + if (value == NULL && ++value == NULL) { + free(name); + return -1; + } + *value++ = 0; + + for(cur = top_vars; cur; cur = cur->next) { + if(strcmp(cur->name, name)==0) + break; + } + + if(cur) { + if(strcmp(cur->value, value)==0) { + if(flg_export>0 && cur->flg_export==0) + cur->flg_export=flg_export; + else + result++; + } else { + if(cur->flg_read_only) { + error_msg("%s: readonly variable", name); + result = -1; + } else { + if(flg_export>0 || cur->flg_export>1) + cur->flg_export=1; + free(cur->value); + + cur->value = strdup(value); + } + } + } else { + cur = malloc(sizeof(struct variables)); + if(!cur) { + result = -1; + } else { + cur->name = strdup(name); + if (cur->name == NULL) { + free(cur); + result = -1; + } else { + struct variables *bottom = top_vars; + cur->value = strdup(value); + cur->next = NULL; + cur->flg_export = flg_export; + cur->flg_read_only = 0; + while(bottom->next) bottom=bottom->next; + bottom->next = cur; + } + } + } + +#ifndef __U_BOOT__ + if(result==0 && cur->flg_export==1) { + *(value-1) = '='; + result = putenv(name); + } else { +#endif + free(name); +#ifndef __U_BOOT__ + if(result>0) /* equivalent to previous set */ + result = 0; + } +#endif + return result; +} + +void unset_local_var(const char *name) +{ + struct variables *cur; + + if (name) { + for (cur = top_vars; cur; cur=cur->next) { + if(strcmp(cur->name, name)==0) + break; + } + if (cur != NULL) { + struct variables *next = top_vars; + if(cur->flg_read_only) { + error_msg("%s: readonly variable", name); + return; + } else { +#ifndef __U_BOOT__ + if(cur->flg_export) + unsetenv(cur->name); +#endif + free(cur->name); + free(cur->value); + while (next->next != cur) + next = next->next; + next->next = cur->next; + } + free(cur); + } + } +} + +static int is_assignment(const char *s) +{ + if (s == NULL) + return 0; + + if (!isalpha(*s)) return 0; + ++s; + while(isalnum(*s) || *s=='_') ++s; + return *s=='='; +} + +#ifndef __U_BOOT__ +/* the src parameter allows us to peek forward to a possible &n syntax + * for file descriptor duplication, e.g., "2>&1". + * Return code is 0 normally, 1 if a syntax error is detected in src. + * Resource errors (in xmalloc) cause the process to exit */ +static int setup_redirect(struct p_context *ctx, int fd, redir_type style, + struct in_str *input) +{ + struct child_prog *child=ctx->child; + struct redir_struct *redir = child->redirects; + struct redir_struct *last_redir=NULL; + + /* Create a new redir_struct and drop it onto the end of the linked list */ + while(redir) { + last_redir=redir; + redir=redir->next; + } + redir = xmalloc(sizeof(struct redir_struct)); + redir->next=NULL; + redir->word.gl_pathv=NULL; + if (last_redir) { + last_redir->next=redir; + } else { + child->redirects=redir; + } + + redir->type=style; + redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ; + + debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip); + + /* Check for a '2>&1' type redirect */ + redir->dup = redirect_dup_num(input); + if (redir->dup == -2) return 1; /* syntax error */ + if (redir->dup != -1) { + /* Erik had a check here that the file descriptor in question + * is legit; I postpone that to "run time" + * A "-" representation of "close me" shows up as a -3 here */ + debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup); + } else { + /* We do _not_ try to open the file that src points to, + * since we need to return and let src be expanded first. + * Set ctx->pending_redirect, so we know what to do at the + * end of the next parsed word. + */ + ctx->pending_redirect = redir; + } + return 0; +} +#endif + +static struct pipe *new_pipe(void) +{ + struct pipe *pi; + pi = xmalloc(sizeof(struct pipe)); + pi->num_progs = 0; + pi->progs = NULL; + pi->next = NULL; + pi->followup = 0; /* invalid */ + pi->r_mode = RES_NONE; + return pi; +} + +static void initialize_context(struct p_context *ctx) +{ + ctx->pipe=NULL; +#ifndef __U_BOOT__ + ctx->pending_redirect=NULL; +#endif + ctx->child=NULL; + ctx->list_head=new_pipe(); + ctx->pipe=ctx->list_head; + ctx->w=RES_NONE; + ctx->stack=NULL; +#ifdef __U_BOOT__ + ctx->old_flag=0; +#endif + done_command(ctx); /* creates the memory for working child */ +} + +/* normal return is 0 + * if a reserved word is found, and processed, return 1 + * should handle if, then, elif, else, fi, for, while, until, do, done. + * case, function, and select are obnoxious, save those for later. + */ +struct reserved_combo { + char *literal; + int code; + long flag; +}; +/* Mostly a list of accepted follow-up reserved words. + * FLAG_END means we are done with the sequence, and are ready + * to turn the compound list into a command. + * FLAG_START means the word must start a new compound list. + */ +static struct reserved_combo reserved_list[] = { + { "if", RES_IF, FLAG_THEN | FLAG_START }, + { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI }, + { "elif", RES_ELIF, FLAG_THEN }, + { "else", RES_ELSE, FLAG_FI }, + { "fi", RES_FI, FLAG_END }, + { "for", RES_FOR, FLAG_IN | FLAG_START }, + { "while", RES_WHILE, FLAG_DO | FLAG_START }, + { "until", RES_UNTIL, FLAG_DO | FLAG_START }, + { "in", RES_IN, FLAG_DO }, + { "do", RES_DO, FLAG_DONE }, + { "done", RES_DONE, FLAG_END } +}; +#define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo)) + +static int reserved_word(o_string *dest, struct p_context *ctx) +{ + struct reserved_combo *r; + for (r=reserved_list; + rdata, r->literal) == 0) { + debug_printf("found reserved word %s, code %d\n",r->literal,r->code); + if (r->flag & FLAG_START) { + struct p_context *new = xmalloc(sizeof(struct p_context)); + debug_printf("push stack\n"); + if (ctx->w == RES_IN || ctx->w == RES_FOR) { + syntax(); + free(new); + ctx->w = RES_SNTX; + b_reset(dest); + return 1; + } + *new = *ctx; /* physical copy */ + initialize_context(ctx); + ctx->stack=new; + } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<code))) { + syntax(); + ctx->w = RES_SNTX; + b_reset(dest); + return 1; + } + ctx->w=r->code; + ctx->old_flag = r->flag; + if (ctx->old_flag & FLAG_END) { + struct p_context *old; + debug_printf("pop stack\n"); + done_pipe(ctx,PIPE_SEQ); + old = ctx->stack; + old->child->group = ctx->list_head; +#ifndef __U_BOOT__ + old->child->subshell = 0; +#endif + *ctx = *old; /* physical copy */ + free(old); + } + b_reset (dest); + return 1; + } + } + return 0; +} + +/* normal return is 0. + * Syntax or xglob errors return 1. */ +static int done_word(o_string *dest, struct p_context *ctx) +{ + struct child_prog *child=ctx->child; +#ifndef __U_BOOT__ + glob_t *glob_target; + int gr, flags = 0; +#else + char *str, *s; + int argc, cnt; +#endif + + debug_printf("done_word: %s %p\n", dest->data, child); + if (dest->length == 0 && !dest->nonnull) { + debug_printf(" true null, ignored\n"); + return 0; + } +#ifndef __U_BOOT__ + if (ctx->pending_redirect) { + glob_target = &ctx->pending_redirect->word; + } else { +#endif + if (child->group) { + syntax(); + return 1; /* syntax error, groups and arglists don't mix */ + } + if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) { + debug_printf("checking %s for reserved-ness\n",dest->data); + if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX; + } +#ifndef __U_BOOT__ + glob_target = &child->glob_result; + if (child->argv) flags |= GLOB_APPEND; +#else + for (cnt = 1, s = dest->data; s && *s; s++) { + if (*s == '\\') s++; + cnt++; + } + str = malloc(cnt); + if (!str) return 1; + if ( child->argv == NULL) { + child->argc=0; + } + argc = ++child->argc; + child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv)); + if (child->argv == NULL) return 1; + child->argv_nonnull = realloc(child->argv_nonnull, + (argc+1)*sizeof(*child->argv_nonnull)); + if (child->argv_nonnull == NULL) + return 1; + child->argv[argc-1]=str; + child->argv_nonnull[argc-1] = dest->nonnull; + child->argv[argc]=NULL; + child->argv_nonnull[argc] = 0; + for (s = dest->data; s && *s; s++,str++) { + if (*s == '\\') s++; + *str = *s; + } + *str = '\0'; +#endif +#ifndef __U_BOOT__ + } + gr = xglob(dest, flags, glob_target); + if (gr != 0) return 1; +#endif + + b_reset(dest); +#ifndef __U_BOOT__ + if (ctx->pending_redirect) { + ctx->pending_redirect=NULL; + if (glob_target->gl_pathc != 1) { + error_msg("ambiguous redirect"); + return 1; + } + } else { + child->argv = glob_target->gl_pathv; + } +#endif + if (ctx->w == RES_FOR) { + done_word(dest,ctx); + done_pipe(ctx,PIPE_SEQ); + } + return 0; +} + +/* The only possible error here is out of memory, in which case + * xmalloc exits. */ +static int done_command(struct p_context *ctx) +{ + /* The child is really already in the pipe structure, so + * advance the pipe counter and make a new, null child. + * Only real trickiness here is that the uncommitted + * child structure, to which ctx->child points, is not + * counted in pi->num_progs. */ + struct pipe *pi=ctx->pipe; + struct child_prog *prog=ctx->child; + + if (prog && prog->group == NULL + && prog->argv == NULL +#ifndef __U_BOOT__ + && prog->redirects == NULL) { +#else + ) { +#endif + debug_printf("done_command: skipping null command\n"); + return 0; + } else if (prog) { + pi->num_progs++; + debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs); + } else { + debug_printf("done_command: initializing\n"); + } + pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1)); + + prog = pi->progs + pi->num_progs; +#ifndef __U_BOOT__ + prog->redirects = NULL; +#endif + prog->argv = NULL; + prog->argv_nonnull = NULL; +#ifndef __U_BOOT__ + prog->is_stopped = 0; +#endif + prog->group = NULL; +#ifndef __U_BOOT__ + prog->glob_result.gl_pathv = NULL; + prog->family = pi; +#endif + prog->sp = 0; + ctx->child = prog; + prog->type = ctx->type; + + /* but ctx->pipe and ctx->list_head remain unchanged */ + return 0; +} + +static int done_pipe(struct p_context *ctx, pipe_style type) +{ + struct pipe *new_p; + done_command(ctx); /* implicit closure of previous command */ + debug_printf("done_pipe, type %d\n", type); + ctx->pipe->followup = type; + ctx->pipe->r_mode = ctx->w; + new_p=new_pipe(); + ctx->pipe->next = new_p; + ctx->pipe = new_p; + ctx->child = NULL; + done_command(ctx); /* set up new pipe to accept commands */ + return 0; +} + +#ifndef __U_BOOT__ +/* peek ahead in the in_str to find out if we have a "&n" construct, + * as in "2>&1", that represents duplicating a file descriptor. + * returns either -2 (syntax error), -1 (no &), or the number found. + */ +static int redirect_dup_num(struct in_str *input) +{ + int ch, d=0, ok=0; + ch = b_peek(input); + if (ch != '&') return -1; + + b_getch(input); /* get the & */ + ch=b_peek(input); + if (ch == '-') { + b_getch(input); + return -3; /* "-" represents "close me" */ + } + while (isdigit(ch)) { + d = d*10+(ch-'0'); + ok=1; + b_getch(input); + ch = b_peek(input); + } + if (ok) return d; + + error_msg("ambiguous redirect"); + return -2; +} + +/* If a redirect is immediately preceded by a number, that number is + * supposed to tell which file descriptor to redirect. This routine + * looks for such preceding numbers. In an ideal world this routine + * needs to handle all the following classes of redirects... + * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo + * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo + * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo + * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo + * A -1 output from this program means no valid number was found, so the + * caller should use the appropriate default for this redirection. + */ +static int redirect_opt_num(o_string *o) +{ + int num; + + if (o->length==0) return -1; + for(num=0; numlength; num++) { + if (!isdigit(*(o->data+num))) { + return -1; + } + } + /* reuse num (and save an int) */ + num=atoi(o->data); + b_reset(o); + return num; +} + +FILE *generate_stream_from_list(struct pipe *head) +{ + FILE *pf; +#if 1 + int pid, channel[2]; + if (pipe(channel)<0) perror_msg_and_die("pipe"); + pid=fork(); + if (pid<0) { + perror_msg_and_die("fork"); + } else if (pid==0) { + close(channel[0]); + if (channel[1] != 1) { + dup2(channel[1],1); + close(channel[1]); + } +#if 0 +#define SURROGATE "surrogate response" + write(1,SURROGATE,sizeof(SURROGATE)); + _exit(run_list(head)); +#else + _exit(run_list_real(head)); /* leaks memory */ +#endif + } + debug_printf("forked child %d\n",pid); + close(channel[1]); + pf = fdopen(channel[0],"r"); + debug_printf("pipe on FILE *%p\n",pf); +#else + free_pipe_list(head,0); + pf=popen("echo surrogate response","r"); + debug_printf("started fake pipe on FILE *%p\n",pf); +#endif + return pf; +} + +/* this version hacked for testing purposes */ +/* return code is exit status of the process that is run. */ +static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end) +{ + int retcode; + o_string result=NULL_O_STRING; + struct p_context inner; + FILE *p; + struct in_str pipe_str; + initialize_context(&inner); + + /* recursion to generate command */ + retcode = parse_stream(&result, &inner, input, subst_end); + if (retcode != 0) return retcode; /* syntax error or EOF */ + done_word(&result, &inner); + done_pipe(&inner, PIPE_SEQ); + b_free(&result); + + p=generate_stream_from_list(inner.list_head); + if (p==NULL) return 1; + mark_open(fileno(p)); + setup_file_in_str(&pipe_str, p); + + /* now send results of command back into original context */ + retcode = parse_stream(dest, ctx, &pipe_str, '\0'); + /* XXX In case of a syntax error, should we try to kill the child? + * That would be tough to do right, so just read until EOF. */ + if (retcode == 1) { + while (b_getch(&pipe_str)!=EOF) { /* discard */ }; + } + + debug_printf("done reading from pipe, pclose()ing\n"); + /* This is the step that wait()s for the child. Should be pretty + * safe, since we just read an EOF from its stdout. We could try + * to better, by using wait(), and keeping track of background jobs + * at the same time. That would be a lot of work, and contrary + * to the KISS philosophy of this program. */ + mark_closed(fileno(p)); + retcode=pclose(p); + free_pipe_list(inner.list_head,0); + debug_printf("pclosed, retcode=%d\n",retcode); + /* XXX this process fails to trim a single trailing newline */ + return retcode; +} + +static int parse_group(o_string *dest, struct p_context *ctx, + struct in_str *input, int ch) +{ + int rcode, endch=0; + struct p_context sub; + struct child_prog *child = ctx->child; + if (child->argv) { + syntax(); + return 1; /* syntax error, groups and arglists don't mix */ + } + initialize_context(&sub); + switch(ch) { + case '(': endch=')'; child->subshell=1; break; + case '{': endch='}'; break; + default: syntax(); /* really logic error */ + } + rcode=parse_stream(dest,&sub,input,endch); + done_word(dest,&sub); /* finish off the final word in the subcontext */ + done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */ + child->group = sub.list_head; + return rcode; + /* child remains "open", available for possible redirects */ +} +#endif + +/* basically useful version until someone wants to get fancier, + * see the bash man page under "Parameter Expansion" */ +static char *lookup_param(char *src) +{ + char *p; + char *sep; + char *default_val = NULL; + int assign = 0; + int expand_empty = 0; + + if (!src) + return NULL; + + sep = strchr(src, ':'); + + if (sep) { + *sep = '\0'; + if (*(sep + 1) == '-') + default_val = sep+2; + if (*(sep + 1) == '=') { + default_val = sep+2; + assign = 1; + } + if (*(sep + 1) == '+') { + default_val = sep+2; + expand_empty = 1; + } + } + + p = getenv(src); + if (!p) + p = get_local_var(src); + + if (!p || strlen(p) == 0) { + p = default_val; + if (assign) { + char *var = malloc(strlen(src)+strlen(default_val)+2); + if (var) { + sprintf(var, "%s=%s", src, default_val); + set_local_var(var, 0); + } + free(var); + } + } else if (expand_empty) { + p += strlen(p); + } + + if (sep) + *sep = ':'; + + return p; +} + +#ifdef __U_BOOT__ +static char *get_dollar_var(char ch) +{ + static char buf[40]; + + buf[0] = '\0'; + switch (ch) { + case '?': + sprintf(buf, "%u", (unsigned int)last_return_code); + break; + default: + return NULL; + } + return buf; +} +#endif + +/* return code: 0 for OK, 1 for syntax error */ +static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input) +{ +#ifndef __U_BOOT__ + int i, advance=0; +#else + int advance=0; +#endif +#ifndef __U_BOOT__ + char sep[]=" "; +#endif + int ch = input->peek(input); /* first character after the $ */ + debug_printf("handle_dollar: ch=%c\n",ch); + if (isalpha(ch)) { + b_addchr(dest, SPECIAL_VAR_SYMBOL); + ctx->child->sp++; + while(ch=b_peek(input),isalnum(ch) || ch=='_') { + b_getch(input); + b_addchr(dest,ch); + } + b_addchr(dest, SPECIAL_VAR_SYMBOL); +#ifndef __U_BOOT__ + } else if (isdigit(ch)) { + i = ch-'0'; /* XXX is $0 special? */ + if (i 0) b_adduint(dest, last_bg_pid); + advance = 1; + break; +#endif + case '?': +#ifndef __U_BOOT__ + b_adduint(dest,last_return_code); +#else + ctx->child->sp++; + b_addchr(dest, SPECIAL_VAR_SYMBOL); + b_addchr(dest, '$'); + b_addchr(dest, '?'); + b_addchr(dest, SPECIAL_VAR_SYMBOL); +#endif + advance = 1; + break; +#ifndef __U_BOOT__ + case '#': + b_adduint(dest,global_argc ? global_argc-1 : 0); + advance = 1; + break; +#endif + case '{': + b_addchr(dest, SPECIAL_VAR_SYMBOL); + ctx->child->sp++; + b_getch(input); + /* XXX maybe someone will try to escape the '}' */ + while(ch=b_getch(input),ch!=EOF && ch!='}') { + b_addchr(dest,ch); + } + if (ch != '}') { + syntax(); + return 1; + } + b_addchr(dest, SPECIAL_VAR_SYMBOL); + break; +#ifndef __U_BOOT__ + case '(': + b_getch(input); + process_command_subs(dest, ctx, input, ')'); + break; + case '*': + sep[0]=ifs[0]; + for (i=1; iquote); + } + /* Eat the character if the flag was set. If the compiler + * is smart enough, we could substitute "b_getch(input);" + * for all the "advance = 1;" above, and also end up with + * a nice size-optimized program. Hah! That'll be the day. + */ + if (advance) b_getch(input); + return 0; +} + +#ifndef __U_BOOT__ +int parse_string(o_string *dest, struct p_context *ctx, const char *src) +{ + struct in_str foo; + setup_string_in_str(&foo, src); + return parse_stream(dest, ctx, &foo, '\0'); +} +#endif + +/* return code is 0 for normal exit, 1 for syntax error */ +static int parse_stream(o_string *dest, struct p_context *ctx, + struct in_str *input, int end_trigger) +{ + unsigned int ch, m; +#ifndef __U_BOOT__ + int redir_fd; + redir_type redir_style; +#endif + int next; + + /* Only double-quote state is handled in the state variable dest->quote. + * A single-quote triggers a bypass of the main loop until its mate is + * found. When recursing, quote state is passed in via dest->quote. */ + + debug_printf("parse_stream, end_trigger=%d\n",end_trigger); + while ((ch=b_getch(input))!=EOF) { + m = map[ch]; +#ifdef __U_BOOT__ + if (input->__promptme == 0) return 1; +#endif + next = (ch == '\n') ? 0 : b_peek(input); + + debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n", + ch >= ' ' ? ch : '.', ch, m, + dest->quote, ctx->stack == NULL ? '*' : '.'); + + if (m==0 || ((m==1 || m==2) && dest->quote)) { + b_addqchr(dest, ch, dest->quote); + } else { + if (m==2) { /* unquoted IFS */ + if (done_word(dest, ctx)) { + return 1; + } + /* If we aren't performing a substitution, treat a newline as a + * command separator. */ + if (end_trigger != '\0' && ch=='\n') + done_pipe(ctx,PIPE_SEQ); + } + if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) { + debug_printf("leaving parse_stream (triggered)\n"); + return 0; + } +#if 0 + if (ch=='\n') { + /* Yahoo! Time to run with it! */ + done_pipe(ctx,PIPE_SEQ); + run_list(ctx->list_head); + initialize_context(ctx); + } +#endif + if (m!=2) switch (ch) { + case '#': + if (dest->length == 0 && !dest->quote) { + while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); } + } else { + b_addqchr(dest, ch, dest->quote); + } + break; + case '\\': + if (next == EOF) { + syntax(); + return 1; + } + b_addqchr(dest, '\\', dest->quote); + b_addqchr(dest, b_getch(input), dest->quote); + break; + case '$': + if (handle_dollar(dest, ctx, input)!=0) return 1; + break; + case '\'': + dest->nonnull = 1; + while(ch=b_getch(input),ch!=EOF && ch!='\'') { +#ifdef __U_BOOT__ + if(input->__promptme == 0) return 1; +#endif + b_addchr(dest,ch); + } + if (ch==EOF) { + syntax(); + return 1; + } + break; + case '"': + dest->nonnull = 1; + dest->quote = !dest->quote; + break; +#ifndef __U_BOOT__ + case '`': + process_command_subs(dest, ctx, input, '`'); + break; + case '>': + redir_fd = redirect_opt_num(dest); + done_word(dest, ctx); + redir_style=REDIRECT_OVERWRITE; + if (next == '>') { + redir_style=REDIRECT_APPEND; + b_getch(input); + } else if (next == '(') { + syntax(); /* until we support >(list) Process Substitution */ + return 1; + } + setup_redirect(ctx, redir_fd, redir_style, input); + break; + case '<': + redir_fd = redirect_opt_num(dest); + done_word(dest, ctx); + redir_style=REDIRECT_INPUT; + if (next == '<') { + redir_style=REDIRECT_HEREIS; + b_getch(input); + } else if (next == '>') { + redir_style=REDIRECT_IO; + b_getch(input); + } else if (next == '(') { + syntax(); /* until we support <(list) Process Substitution */ + return 1; + } + setup_redirect(ctx, redir_fd, redir_style, input); + break; +#endif + case ';': + done_word(dest, ctx); + done_pipe(ctx,PIPE_SEQ); + break; + case '&': + done_word(dest, ctx); + if (next=='&') { + b_getch(input); + done_pipe(ctx,PIPE_AND); + } else { +#ifndef __U_BOOT__ + done_pipe(ctx,PIPE_BG); +#else + syntax_err(); + return 1; +#endif + } + break; + case '|': + done_word(dest, ctx); + if (next=='|') { + b_getch(input); + done_pipe(ctx,PIPE_OR); + } else { + /* we could pick up a file descriptor choice here + * with redirect_opt_num(), but bash doesn't do it. + * "echo foo 2| cat" yields "foo 2". */ +#ifndef __U_BOOT__ + done_command(ctx); +#else + syntax_err(); + return 1; +#endif + } + break; +#ifndef __U_BOOT__ + case '(': + case '{': + if (parse_group(dest, ctx, input, ch)!=0) return 1; + break; + case ')': + case '}': + syntax(); /* Proper use of this character caught by end_trigger */ + return 1; + break; +#endif + case SUBSTED_VAR_SYMBOL: + dest->nonnull = 1; + while (ch = b_getch(input), ch != EOF && + ch != SUBSTED_VAR_SYMBOL) { + debug_printf("subst, pass=%d\n", ch); + if (input->__promptme == 0) + return 1; + b_addchr(dest, ch); + } + debug_printf("subst, term=%d\n", ch); + if (ch == EOF) { + syntax(); + return 1; + } + break; + default: + syntax(); /* this is really an internal logic error */ + return 1; + } + } + } + /* complain if quote? No, maybe we just finished a command substitution + * that was quoted. Example: + * $ echo "`cat foo` plus more" + * and we just got the EOF generated by the subshell that ran "cat foo" + * The only real complaint is if we got an EOF when end_trigger != '\0', + * that is, we were really supposed to get end_trigger, and never got + * one before the EOF. Can't use the standard "syntax error" return code, + * so that parse_stream_outer can distinguish the EOF and exit smoothly. */ + debug_printf("leaving parse_stream (EOF)\n"); + if (end_trigger != '\0') return -1; + return 0; +} + +static void mapset(const unsigned char *set, int code) +{ + const unsigned char *s; + for (s=set; *s; s++) map[*s] = code; +} + +static void update_ifs_map(void) +{ + /* char *ifs and char map[256] are both globals. */ + ifs = (uchar *)getenv("IFS"); + if (ifs == NULL) ifs=(uchar *)" \t\n"; + /* Precompute a list of 'flow through' behavior so it can be treated + * quickly up front. Computation is necessary because of IFS. + * Special case handling of IFS == " \t\n" is not implemented. + * The map[] array only really needs two bits each, and on most machines + * that would be faster because of the reduced L1 cache footprint. + */ + memset(map,0,sizeof(map)); /* most characters flow through always */ +#ifndef __U_BOOT__ + mapset((uchar *)"\\$'\"`", 3); /* never flow through */ + mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */ +#else + { + uchar subst[2] = {SUBSTED_VAR_SYMBOL, 0}; + mapset(subst, 3); /* never flow through */ + } + mapset((uchar *)"\\$'\"", 3); /* never flow through */ + mapset((uchar *)";&|#", 1); /* flow through if quoted */ +#endif + mapset(ifs, 2); /* also flow through if quoted */ +} + +/* most recursion does not come through here, the exeception is + * from builtin_source() */ +static int parse_stream_outer(struct in_str *inp, int flag) +{ + + struct p_context ctx; + o_string temp=NULL_O_STRING; + int rcode; +#ifdef __U_BOOT__ + int code = 0; +#endif + do { + ctx.type = flag; + initialize_context(&ctx); + update_ifs_map(); + if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0); + inp->promptmode=1; + rcode = parse_stream(&temp, &ctx, inp, '\n'); +#ifdef __U_BOOT__ + if (rcode == 1) flag_repeat = 0; +#endif + if (rcode != 1 && ctx.old_flag != 0) { + syntax(); +#ifdef __U_BOOT__ + flag_repeat = 0; +#endif + } + if (rcode != 1 && ctx.old_flag == 0) { + done_word(&temp, &ctx); + done_pipe(&ctx,PIPE_SEQ); +#ifndef __U_BOOT__ + run_list(ctx.list_head); +#else + code = run_list(ctx.list_head); + if (code == -2) { /* exit */ + b_free(&temp); + code = 0; + /* XXX hackish way to not allow exit from main loop */ + if (inp->peek == file_peek) { + printf("exit not allowed from main input shell.\n"); + continue; + } + break; + } + if (code == -1) + flag_repeat = 0; +#endif + } else { + if (ctx.old_flag != 0) { + free(ctx.stack); + b_reset(&temp); + } +#ifdef __U_BOOT__ + if (inp->__promptme == 0) printf("\n"); + inp->__promptme = 1; +#endif + temp.nonnull = 0; + temp.quote = 0; + inp->p = NULL; + free_pipe_list(ctx.list_head,0); + } + b_free(&temp); + } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */ +#ifndef __U_BOOT__ + return 0; +#else + return (code != 0) ? 1 : 0; +#endif /* __U_BOOT__ */ +} + +#ifndef __U_BOOT__ +static int parse_string_outer(const char *s, int flag) +#else +int parse_string_outer(const char *s, int flag) +#endif /* __U_BOOT__ */ +{ + struct in_str input; +#ifdef __U_BOOT__ + char *p = NULL; + int rcode; + if ( !s || !*s) + return 1; + if (!(p = strchr(s, '\n')) || *++p) { + p = xmalloc(strlen(s) + 2); + strcpy(p, s); + strcat(p, "\n"); + setup_string_in_str(&input, p); + rcode = parse_stream_outer(&input, flag); + free(p); + return rcode; + } else { +#endif + setup_string_in_str(&input, s); + return parse_stream_outer(&input, flag); +#ifdef __U_BOOT__ + } +#endif +} + +#ifndef __U_BOOT__ +static int parse_file_outer(FILE *f) +#else +int parse_file_outer(void) +#endif +{ + int rcode; + struct in_str input; +#ifndef __U_BOOT__ + setup_file_in_str(&input, f); +#else + setup_file_in_str(&input); +#endif + rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON); + return rcode; +} + +#ifdef __U_BOOT__ +#ifdef CONFIG_NEEDS_MANUAL_RELOC +static void u_boot_hush_reloc(void) +{ + unsigned long addr; + struct reserved_combo *r; + + for (r=reserved_list; rliteral) + gd->reloc_off; + r->literal = (char *)addr; + } +} +#endif + +int u_boot_hush_start(void) +{ + if (top_vars == NULL) { + top_vars = malloc(sizeof(struct variables)); + top_vars->name = "HUSH_VERSION"; + top_vars->value = "0.01"; + top_vars->next = NULL; + top_vars->flg_export = 0; + top_vars->flg_read_only = 1; +#ifdef CONFIG_NEEDS_MANUAL_RELOC + u_boot_hush_reloc(); +#endif + } + return 0; +} + +static void *xmalloc(size_t size) +{ + void *p = NULL; + + if (!(p = malloc(size))) { + printf("ERROR : memory not allocated\n"); + for(;;); + } + return p; +} + +static void *xrealloc(void *ptr, size_t size) +{ + void *p = NULL; + + if (!(p = realloc(ptr, size))) { + printf("ERROR : memory not allocated\n"); + for(;;); + } + return p; +} +#endif /* __U_BOOT__ */ + +#ifndef __U_BOOT__ +/* Make sure we have a controlling tty. If we get started under a job + * aware app (like bash for example), make sure we are now in charge so + * we don't fight over who gets the foreground */ +static void setup_job_control(void) +{ + static pid_t shell_pgrp; + /* Loop until we are in the foreground. */ + while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ())) + kill (- shell_pgrp, SIGTTIN); + + /* Ignore interactive and job-control signals. */ + signal(SIGINT, SIG_IGN); + signal(SIGQUIT, SIG_IGN); + signal(SIGTERM, SIG_IGN); + signal(SIGTSTP, SIG_IGN); + signal(SIGTTIN, SIG_IGN); + signal(SIGTTOU, SIG_IGN); + signal(SIGCHLD, SIG_IGN); + + /* Put ourselves in our own process group. */ + setsid(); + shell_pgrp = getpid (); + setpgid (shell_pgrp, shell_pgrp); + + /* Grab control of the terminal. */ + tcsetpgrp(shell_terminal, shell_pgrp); +} + +int hush_main(int argc, char * const *argv) +{ + int opt; + FILE *input; + char **e = environ; + + /* XXX what should these be while sourcing /etc/profile? */ + global_argc = argc; + global_argv = argv; + + /* (re?) initialize globals. Sometimes hush_main() ends up calling + * hush_main(), therefore we cannot rely on the BSS to zero out this + * stuff. Reset these to 0 every time. */ + ifs = NULL; + /* map[] is taken care of with call to update_ifs_map() */ + fake_mode = 0; + interactive = 0; + close_me_head = NULL; + last_bg_pid = 0; + job_list = NULL; + last_jobid = 0; + + /* Initialize some more globals to non-zero values */ + set_cwd(); +#ifdef CONFIG_FEATURE_COMMAND_EDITING + cmdedit_set_initial_prompt(); +#else + PS1 = NULL; +#endif + PS2 = "> "; + + /* initialize our shell local variables with the values + * currently living in the environment */ + if (e) { + for (; *e; e++) + set_local_var(*e, 2); /* without call putenv() */ + } + + last_return_code=EXIT_SUCCESS; + + + if (argv[0] && argv[0][0] == '-') { + debug_printf("\nsourcing /etc/profile\n"); + if ((input = fopen("/etc/profile", "r")) != NULL) { + mark_open(fileno(input)); + parse_file_outer(input); + mark_closed(fileno(input)); + fclose(input); + } + } + input=stdin; + + while ((opt = getopt(argc, argv, "c:xif")) > 0) { + switch (opt) { + case 'c': + { + global_argv = argv+optind; + global_argc = argc-optind; + opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON); + goto final_return; + } + break; + case 'i': + interactive++; + break; + case 'f': + fake_mode++; + break; + default: +#ifndef BB_VER + fprintf(stderr, "Usage: sh [FILE]...\n" + " or: sh -c command [args]...\n\n"); + exit(EXIT_FAILURE); +#else + show_usage(); +#endif + } + } + /* A shell is interactive if the `-i' flag was given, or if all of + * the following conditions are met: + * no -c command + * no arguments remaining or the -s flag given + * standard input is a terminal + * standard output is a terminal + * Refer to Posix.2, the description of the `sh' utility. */ + if (argv[optind]==NULL && input==stdin && + isatty(fileno(stdin)) && isatty(fileno(stdout))) { + interactive++; + } + + debug_printf("\ninteractive=%d\n", interactive); + if (interactive) { + /* Looks like they want an interactive shell */ +#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET + printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n"); + printf( "Enter 'help' for a list of built-in commands.\n\n"); +#endif + setup_job_control(); + } + + if (argv[optind]==NULL) { + opt=parse_file_outer(stdin); + goto final_return; + } + + debug_printf("\nrunning script '%s'\n", argv[optind]); + global_argv = argv+optind; + global_argc = argc-optind; + input = xfopen(argv[optind], "r"); + opt = parse_file_outer(input); + +#ifdef CONFIG_FEATURE_CLEAN_UP + fclose(input); + if (cwd && cwd != unknown) + free((char*)cwd); + { + struct variables *cur, *tmp; + for(cur = top_vars; cur; cur = tmp) { + tmp = cur->next; + if (!cur->flg_read_only) { + free(cur->name); + free(cur->value); + free(cur); + } + } + } +#endif + +final_return: + return(opt?opt:last_return_code); +} +#endif + +static char *insert_var_value(char *inp) +{ + return insert_var_value_sub(inp, 0); +} + +static char *insert_var_value_sub(char *inp, int tag_subst) +{ + int res_str_len = 0; + int len; + int done = 0; + char *p, *p1, *res_str = NULL; + + while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) { + /* check the beginning of the string for normal charachters */ + if (p != inp) { + /* copy any charachters to the result string */ + len = p - inp; + res_str = xrealloc(res_str, (res_str_len + len)); + strncpy((res_str + res_str_len), inp, len); + res_str_len += len; + } + inp = ++p; + /* find the ending marker */ + p = strchr(inp, SPECIAL_VAR_SYMBOL); + *p = '\0'; + /* look up the value to substitute */ + if ((p1 = lookup_param(inp))) { + if (tag_subst) + len = res_str_len + strlen(p1) + 2; + else + len = res_str_len + strlen(p1); + res_str = xrealloc(res_str, (1 + len)); + if (tag_subst) { + /* + * copy the variable value to the result + * string + */ + strcpy((res_str + res_str_len + 1), p1); + + /* + * mark the replaced text to be accepted as + * is + */ + res_str[res_str_len] = SUBSTED_VAR_SYMBOL; + res_str[res_str_len + 1 + strlen(p1)] = + SUBSTED_VAR_SYMBOL; + } else + /* + * copy the variable value to the result + * string + */ + strcpy((res_str + res_str_len), p1); + + res_str_len = len; + } + *p = SPECIAL_VAR_SYMBOL; + inp = ++p; + done = 1; + } + if (done) { + res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp))); + strcpy((res_str + res_str_len), inp); + while ((p = strchr(res_str, '\n'))) { + *p = ' '; + } + } + return (res_str == NULL) ? inp : res_str; +} + +static char **make_list_in(char **inp, char *name) +{ + int len, i; + int name_len = strlen(name); + int n = 0; + char **list; + char *p1, *p2, *p3; + + /* create list of variable values */ + list = xmalloc(sizeof(*list)); + for (i = 0; inp[i]; i++) { + p3 = insert_var_value(inp[i]); + p1 = p3; + while (*p1) { + if ((*p1 == ' ')) { + p1++; + continue; + } + if ((p2 = strchr(p1, ' '))) { + len = p2 - p1; + } else { + len = strlen(p1); + p2 = p1 + len; + } + /* we use n + 2 in realloc for list,because we add + * new element and then we will add NULL element */ + list = xrealloc(list, sizeof(*list) * (n + 2)); + list[n] = xmalloc(2 + name_len + len); + strcpy(list[n], name); + strcat(list[n], "="); + strncat(list[n], p1, len); + list[n++][name_len + len + 1] = '\0'; + p1 = p2; + } + if (p3 != inp[i]) free(p3); + } + list[n] = NULL; + return list; +} + +/* + * Make new string for parser + * inp - array of argument strings to flatten + * nonnull - indicates argument was quoted when originally parsed + */ +static char *make_string(char **inp, int *nonnull) +{ + char *p; + char *str = NULL; + int n; + int len = 2; + char *noeval_str; + int noeval = 0; + + noeval_str = get_local_var("HUSH_NO_EVAL"); + if (noeval_str != NULL && *noeval_str != '0' && *noeval_str != '\0') + noeval = 1; + for (n = 0; inp[n]; n++) { + p = insert_var_value_sub(inp[n], noeval); + str = xrealloc(str, (len + strlen(p) + (2 * nonnull[n]))); + if (n) { + strcat(str, " "); + } else { + *str = '\0'; + } + if (nonnull[n]) + strcat(str, "'"); + strcat(str, p); + if (nonnull[n]) + strcat(str, "'"); + len = strlen(str) + 3; + if (p != inp[n]) free(p); + } + len = strlen(str); + *(str + len) = '\n'; + *(str + len + 1) = '\0'; + return str; +} + +#ifdef __U_BOOT__ +static int do_showvar(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[]) +{ + int i, k; + int rcode = 0; + struct variables *cur; + + if (argc == 1) { /* Print all env variables */ + for (cur = top_vars; cur; cur = cur->next) { + printf ("%s=%s\n", cur->name, cur->value); + if (ctrlc ()) { + puts ("\n ** Abort\n"); + return 1; + } + } + return 0; + } + for (i = 1; i < argc; ++i) { /* print single env variables */ + char *name = argv[i]; + + k = -1; + for (cur = top_vars; cur; cur = cur->next) { + if(strcmp (cur->name, name) == 0) { + k = 0; + printf ("%s=%s\n", cur->name, cur->value); + } + if (ctrlc ()) { + puts ("\n ** Abort\n"); + return 1; + } + } + if (k < 0) { + printf ("## Error: \"%s\" not defined\n", name); + rcode ++; + } + } + return rcode; +} + +U_BOOT_CMD( + showvar, CONFIG_SYS_MAXARGS, 1, do_showvar, + "print local hushshell variables", + "\n - print values of all hushshell variables\n" + "showvar name ...\n" + " - print value of hushshell variable 'name'" +); + +#endif +/****************************************************************************/ diff --git a/common/hush.c b/common/hush.c deleted file mode 100644 index 5b43224..0000000 --- a/common/hush.c +++ /dev/null @@ -1,3687 +0,0 @@ -/* - * sh.c -- a prototype Bourne shell grammar parser - * Intended to follow the original Thompson and Ritchie - * "small and simple is beautiful" philosophy, which - * incidentally is a good match to today's BusyBox. - * - * Copyright (C) 2000,2001 Larry Doolittle - * - * Credits: - * The parser routines proper are all original material, first - * written Dec 2000 and Jan 2001 by Larry Doolittle. - * The execution engine, the builtins, and much of the underlying - * support has been adapted from busybox-0.49pre's lash, - * which is Copyright (C) 2000 by Lineo, Inc., and - * written by Erik Andersen , . - * That, in turn, is based in part on ladsh.c, by Michael K. Johnson and - * Erik W. Troan, which they placed in the public domain. I don't know - * how much of the Johnson/Troan code has survived the repeated rewrites. - * Other credits: - * b_addchr() derived from similar w_addchar function in glibc-2.2 - * setup_redirect(), redirect_opt_num(), and big chunks of main() - * and many builtins derived from contributions by Erik Andersen - * miscellaneous bugfixes from Matt Kraai - * - * There are two big (and related) architecture differences between - * this parser and the lash parser. One is that this version is - * actually designed from the ground up to understand nearly all - * of the Bourne grammar. The second, consequential change is that - * the parser and input reader have been turned inside out. Now, - * the parser is in control, and asks for input as needed. The old - * way had the input reader in control, and it asked for parsing to - * take place as needed. The new way makes it much easier to properly - * handle the recursion implicit in the various substitutions, especially - * across continuation lines. - * - * Bash grammar not implemented: (how many of these were in original sh?) - * $@ (those sure look like weird quoting rules) - * $_ - * ! negation operator for pipes - * &> and >& redirection of stdout+stderr - * Brace Expansion - * Tilde Expansion - * fancy forms of Parameter Expansion - * aliases - * Arithmetic Expansion - * <(list) and >(list) Process Substitution - * reserved words: case, esac, select, function - * Here Documents ( << word ) - * Functions - * Major bugs: - * job handling woefully incomplete and buggy - * reserved word execution woefully incomplete and buggy - * to-do: - * port selected bugfixes from post-0.49 busybox lash - done? - * finish implementing reserved words: for, while, until, do, done - * change { and } from special chars to reserved words - * builtins: break, continue, eval, return, set, trap, ulimit - * test magic exec - * handle children going into background - * clean up recognition of null pipes - * check setting of global_argc and global_argv - * control-C handling, probably with longjmp - * follow IFS rules more precisely, including update semantics - * figure out what to do with backslash-newline - * explain why we use signal instead of sigaction - * propagate syntax errors, die on resource errors? - * continuation lines, both explicit and implicit - done? - * memory leak finding and plugging - done? - * more testing, especially quoting rules and redirection - * document how quoting rules not precisely followed for variable assignments - * maybe change map[] to use 2-bit entries - * (eventually) remove all the printf's - * - * SPDX-License-Identifier: GPL-2.0+ - */ - -#define __U_BOOT__ -#ifdef __U_BOOT__ -#include /* malloc, free, realloc*/ -#include /* isalpha, isdigit */ -#include /* readline */ -#include -#include /* find_cmd */ -#ifndef CONFIG_SYS_PROMPT_HUSH_PS2 -#define CONFIG_SYS_PROMPT_HUSH_PS2 "> " -#endif -#endif -#ifndef __U_BOOT__ -#include /* isalpha, isdigit */ -#include /* getpid */ -#include /* getenv, atoi */ -#include /* strchr */ -#include /* popen etc. */ -#include /* glob, of course */ -#include /* va_list */ -#include -#include -#include /* should be pretty obvious */ - -#include /* ulimit */ -#include -#include -#include - -/* #include */ - -#if 1 -#include "busybox.h" -#include "cmdedit.h" -#else -#define applet_name "hush" -#include "standalone.h" -#define hush_main main -#undef CONFIG_FEATURE_SH_FANCY_PROMPT -#define BB_BANNER -#endif -#endif -#define SPECIAL_VAR_SYMBOL 03 -#define SUBSTED_VAR_SYMBOL 04 -#ifndef __U_BOOT__ -#define FLAG_EXIT_FROM_LOOP 1 -#define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */ -#define FLAG_REPARSING (1 << 2) /* >= 2nd pass */ - -#endif - -#ifdef __U_BOOT__ -DECLARE_GLOBAL_DATA_PTR; - -#define EXIT_SUCCESS 0 -#define EOF -1 -#define syntax() syntax_err() -#define xstrdup strdup -#define error_msg printf -#else -typedef enum { - REDIRECT_INPUT = 1, - REDIRECT_OVERWRITE = 2, - REDIRECT_APPEND = 3, - REDIRECT_HEREIS = 4, - REDIRECT_IO = 5 -} redir_type; - -/* The descrip member of this structure is only used to make debugging - * output pretty */ -struct {int mode; int default_fd; char *descrip;} redir_table[] = { - { 0, 0, "()" }, - { O_RDONLY, 0, "<" }, - { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" }, - { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" }, - { O_RDONLY, -1, "<<" }, - { O_RDWR, 1, "<>" } -}; -#endif - -typedef enum { - PIPE_SEQ = 1, - PIPE_AND = 2, - PIPE_OR = 3, - PIPE_BG = 4, -} pipe_style; - -/* might eventually control execution */ -typedef enum { - RES_NONE = 0, - RES_IF = 1, - RES_THEN = 2, - RES_ELIF = 3, - RES_ELSE = 4, - RES_FI = 5, - RES_FOR = 6, - RES_WHILE = 7, - RES_UNTIL = 8, - RES_DO = 9, - RES_DONE = 10, - RES_XXXX = 11, - RES_IN = 12, - RES_SNTX = 13 -} reserved_style; -#define FLAG_END (1<, but protected with __USE_GNU */ -#endif - -/* "globals" within this file */ -static uchar *ifs; -static char map[256]; -#ifndef __U_BOOT__ -static int fake_mode; -static int interactive; -static struct close_me *close_me_head; -static const char *cwd; -static struct pipe *job_list; -static unsigned int last_bg_pid; -static unsigned int last_jobid; -static unsigned int shell_terminal; -static char *PS1; -static char *PS2; -struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 }; -struct variables *top_vars = &shell_ver; -#else -static int flag_repeat = 0; -static int do_repeat = 0; -static struct variables *top_vars = NULL ; -#endif /*__U_BOOT__ */ - -#define B_CHUNK (100) -#define B_NOSPAC 1 - -typedef struct { - char *data; - int length; - int maxlen; - int quote; - int nonnull; -} o_string; -#define NULL_O_STRING {NULL,0,0,0,0} -/* used for initialization: - o_string foo = NULL_O_STRING; */ - -/* I can almost use ordinary FILE *. Is open_memstream() universally - * available? Where is it documented? */ -struct in_str { - const char *p; -#ifndef __U_BOOT__ - char peek_buf[2]; -#endif - int __promptme; - int promptmode; -#ifndef __U_BOOT__ - FILE *file; -#endif - int (*get) (struct in_str *); - int (*peek) (struct in_str *); -}; -#define b_getch(input) ((input)->get(input)) -#define b_peek(input) ((input)->peek(input)) - -#ifndef __U_BOOT__ -#define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n" - -struct built_in_command { - char *cmd; /* name */ - char *descr; /* description */ - int (*function) (struct child_prog *); /* function ptr */ -}; -#endif - -/* define DEBUG_SHELL for debugging output (obviously ;-)) */ -#if 0 -#define DEBUG_SHELL -#endif - -/* This should be in utility.c */ -#ifdef DEBUG_SHELL -#ifndef __U_BOOT__ -static void debug_printf(const char *format, ...) -{ - va_list args; - va_start(args, format); - vfprintf(stderr, format, args); - va_end(args); -} -#else -#define debug_printf(fmt,args...) printf (fmt ,##args) -#endif -#else -static inline void debug_printf(const char *format, ...) { } -#endif -#define final_printf debug_printf - -#ifdef __U_BOOT__ -static void syntax_err(void) { - printf("syntax error\n"); -} -#else -static void __syntax(char *file, int line) { - error_msg("syntax error %s:%d", file, line); -} -#define syntax() __syntax(__FILE__, __LINE__) -#endif - -#ifdef __U_BOOT__ -static void *xmalloc(size_t size); -static void *xrealloc(void *ptr, size_t size); -#else -/* Index of subroutines: */ -/* function prototypes for builtins */ -static int builtin_cd(struct child_prog *child); -static int builtin_env(struct child_prog *child); -static int builtin_eval(struct child_prog *child); -static int builtin_exec(struct child_prog *child); -static int builtin_exit(struct child_prog *child); -static int builtin_export(struct child_prog *child); -static int builtin_fg_bg(struct child_prog *child); -static int builtin_help(struct child_prog *child); -static int builtin_jobs(struct child_prog *child); -static int builtin_pwd(struct child_prog *child); -static int builtin_read(struct child_prog *child); -static int builtin_set(struct child_prog *child); -static int builtin_shift(struct child_prog *child); -static int builtin_source(struct child_prog *child); -static int builtin_umask(struct child_prog *child); -static int builtin_unset(struct child_prog *child); -static int builtin_not_written(struct child_prog *child); -#endif -/* o_string manipulation: */ -static int b_check_space(o_string *o, int len); -static int b_addchr(o_string *o, int ch); -static void b_reset(o_string *o); -static int b_addqchr(o_string *o, int ch, int quote); -#ifndef __U_BOOT__ -static int b_adduint(o_string *o, unsigned int i); -#endif -/* in_str manipulations: */ -static int static_get(struct in_str *i); -static int static_peek(struct in_str *i); -static int file_get(struct in_str *i); -static int file_peek(struct in_str *i); -#ifndef __U_BOOT__ -static void setup_file_in_str(struct in_str *i, FILE *f); -#else -static void setup_file_in_str(struct in_str *i); -#endif -static void setup_string_in_str(struct in_str *i, const char *s); -#ifndef __U_BOOT__ -/* close_me manipulations: */ -static void mark_open(int fd); -static void mark_closed(int fd); -static void close_all(void); -#endif -/* "run" the final data structures: */ -static char *indenter(int i); -static int free_pipe_list(struct pipe *head, int indent); -static int free_pipe(struct pipe *pi, int indent); -/* really run the final data structures: */ -#ifndef __U_BOOT__ -static int setup_redirects(struct child_prog *prog, int squirrel[]); -#endif -static int run_list_real(struct pipe *pi); -#ifndef __U_BOOT__ -static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn)); -#endif -static int run_pipe_real(struct pipe *pi); -/* extended glob support: */ -#ifndef __U_BOOT__ -static int globhack(const char *src, int flags, glob_t *pglob); -static int glob_needed(const char *s); -static int xglob(o_string *dest, int flags, glob_t *pglob); -#endif -/* variable assignment: */ -static int is_assignment(const char *s); -/* data structure manipulation: */ -#ifndef __U_BOOT__ -static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input); -#endif -static void initialize_context(struct p_context *ctx); -static int done_word(o_string *dest, struct p_context *ctx); -static int done_command(struct p_context *ctx); -static int done_pipe(struct p_context *ctx, pipe_style type); -/* primary string parsing: */ -#ifndef __U_BOOT__ -static int redirect_dup_num(struct in_str *input); -static int redirect_opt_num(o_string *o); -static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end); -static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch); -#endif -static char *lookup_param(char *src); -static char *make_string(char **inp, int *nonnull); -static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input); -#ifndef __U_BOOT__ -static int parse_string(o_string *dest, struct p_context *ctx, const char *src); -#endif -static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger); -/* setup: */ -static int parse_stream_outer(struct in_str *inp, int flag); -#ifndef __U_BOOT__ -static int parse_string_outer(const char *s, int flag); -static int parse_file_outer(FILE *f); -#endif -#ifndef __U_BOOT__ -/* job management: */ -static int checkjobs(struct pipe* fg_pipe); -static void insert_bg_job(struct pipe *pi); -static void remove_bg_job(struct pipe *pi); -#endif -/* local variable support */ -static char **make_list_in(char **inp, char *name); -static char *insert_var_value(char *inp); -static char *insert_var_value_sub(char *inp, int tag_subst); - -#ifndef __U_BOOT__ -/* Table of built-in functions. They can be forked or not, depending on - * context: within pipes, they fork. As simple commands, they do not. - * When used in non-forking context, they can change global variables - * in the parent shell process. If forked, of course they can not. - * For example, 'unset foo | whatever' will parse and run, but foo will - * still be set at the end. */ -static struct built_in_command bltins[] = { - {"bg", "Resume a job in the background", builtin_fg_bg}, - {"break", "Exit for, while or until loop", builtin_not_written}, - {"cd", "Change working directory", builtin_cd}, - {"continue", "Continue for, while or until loop", builtin_not_written}, - {"env", "Print all environment variables", builtin_env}, - {"eval", "Construct and run shell command", builtin_eval}, - {"exec", "Exec command, replacing this shell with the exec'd process", - builtin_exec}, - {"exit", "Exit from shell()", builtin_exit}, - {"export", "Set environment variable", builtin_export}, - {"fg", "Bring job into the foreground", builtin_fg_bg}, - {"jobs", "Lists the active jobs", builtin_jobs}, - {"pwd", "Print current directory", builtin_pwd}, - {"read", "Input environment variable", builtin_read}, - {"return", "Return from a function", builtin_not_written}, - {"set", "Set/unset shell local variables", builtin_set}, - {"shift", "Shift positional parameters", builtin_shift}, - {"trap", "Trap signals", builtin_not_written}, - {"ulimit","Controls resource limits", builtin_not_written}, - {"umask","Sets file creation mask", builtin_umask}, - {"unset", "Unset environment variable", builtin_unset}, - {".", "Source-in and run commands in a file", builtin_source}, - {"help", "List shell built-in commands", builtin_help}, - {NULL, NULL, NULL} -}; - -static const char *set_cwd(void) -{ - if(cwd==unknown) - cwd = NULL; /* xgetcwd(arg) called free(arg) */ - cwd = xgetcwd((char *)cwd); - if (!cwd) - cwd = unknown; - return cwd; -} - -/* built-in 'eval' handler */ -static int builtin_eval(struct child_prog *child) -{ - char *str = NULL; - int rcode = EXIT_SUCCESS; - - if (child->argv[1]) { - str = make_string(child->argv + 1); - parse_string_outer(str, FLAG_EXIT_FROM_LOOP | - FLAG_PARSE_SEMICOLON); - free(str); - rcode = last_return_code; - } - return rcode; -} - -/* built-in 'cd ' handler */ -static int builtin_cd(struct child_prog *child) -{ - char *newdir; - if (child->argv[1] == NULL) - newdir = getenv("HOME"); - else - newdir = child->argv[1]; - if (chdir(newdir)) { - printf("cd: %s: %s\n", newdir, strerror(errno)); - return EXIT_FAILURE; - } - set_cwd(); - return EXIT_SUCCESS; -} - -/* built-in 'env' handler */ -static int builtin_env(struct child_prog *dummy) -{ - char **e = environ; - if (e == NULL) return EXIT_FAILURE; - for (; *e; e++) { - puts(*e); - } - return EXIT_SUCCESS; -} - -/* built-in 'exec' handler */ -static int builtin_exec(struct child_prog *child) -{ - if (child->argv[1] == NULL) - return EXIT_SUCCESS; /* Really? */ - child->argv++; - pseudo_exec(child); - /* never returns */ -} - -/* built-in 'exit' handler */ -static int builtin_exit(struct child_prog *child) -{ - if (child->argv[1] == NULL) - exit(last_return_code); - exit (atoi(child->argv[1])); -} - -/* built-in 'export VAR=value' handler */ -static int builtin_export(struct child_prog *child) -{ - int res = 0; - char *name = child->argv[1]; - - if (name == NULL) { - return (builtin_env(child)); - } - - name = strdup(name); - - if(name) { - char *value = strchr(name, '='); - - if (!value) { - char *tmp; - /* They are exporting something without an =VALUE */ - - value = get_local_var(name); - if (value) { - size_t ln = strlen(name); - - tmp = realloc(name, ln+strlen(value)+2); - if(tmp==NULL) - res = -1; - else { - sprintf(tmp+ln, "=%s", value); - name = tmp; - } - } else { - /* bash does not return an error when trying to export - * an undefined variable. Do likewise. */ - res = 1; - } - } - } - if (res<0) - perror_msg("export"); - else if(res==0) - res = set_local_var(name, 1); - else - res = 0; - free(name); - return res; -} - -/* built-in 'fg' and 'bg' handler */ -static int builtin_fg_bg(struct child_prog *child) -{ - int i, jobnum; - struct pipe *pi=NULL; - - if (!interactive) - return EXIT_FAILURE; - /* If they gave us no args, assume they want the last backgrounded task */ - if (!child->argv[1]) { - for (pi = job_list; pi; pi = pi->next) { - if (pi->jobid == last_jobid) { - break; - } - } - if (!pi) { - error_msg("%s: no current job", child->argv[0]); - return EXIT_FAILURE; - } - } else { - if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) { - error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]); - return EXIT_FAILURE; - } - for (pi = job_list; pi; pi = pi->next) { - if (pi->jobid == jobnum) { - break; - } - } - if (!pi) { - error_msg("%s: %d: no such job", child->argv[0], jobnum); - return EXIT_FAILURE; - } - } - - if (*child->argv[0] == 'f') { - /* Put the job into the foreground. */ - tcsetpgrp(shell_terminal, pi->pgrp); - } - - /* Restart the processes in the job */ - for (i = 0; i < pi->num_progs; i++) - pi->progs[i].is_stopped = 0; - - if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) { - if (i == ESRCH) { - remove_bg_job(pi); - } else { - perror_msg("kill (SIGCONT)"); - } - } - - pi->stopped_progs = 0; - return EXIT_SUCCESS; -} - -/* built-in 'help' handler */ -static int builtin_help(struct child_prog *dummy) -{ - struct built_in_command *x; - - printf("\nBuilt-in commands:\n"); - printf("-------------------\n"); - for (x = bltins; x->cmd; x++) { - if (x->descr==NULL) - continue; - printf("%s\t%s\n", x->cmd, x->descr); - } - printf("\n\n"); - return EXIT_SUCCESS; -} - -/* built-in 'jobs' handler */ -static int builtin_jobs(struct child_prog *child) -{ - struct pipe *job; - char *status_string; - - for (job = job_list; job; job = job->next) { - if (job->running_progs == job->stopped_progs) - status_string = "Stopped"; - else - status_string = "Running"; - - printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text); - } - return EXIT_SUCCESS; -} - - -/* built-in 'pwd' handler */ -static int builtin_pwd(struct child_prog *dummy) -{ - puts(set_cwd()); - return EXIT_SUCCESS; -} - -/* built-in 'read VAR' handler */ -static int builtin_read(struct child_prog *child) -{ - int res; - - if (child->argv[1]) { - char string[BUFSIZ]; - char *var = 0; - - string[0] = 0; /* In case stdin has only EOF */ - /* read string */ - fgets(string, sizeof(string), stdin); - chomp(string); - var = malloc(strlen(child->argv[1])+strlen(string)+2); - if(var) { - sprintf(var, "%s=%s", child->argv[1], string); - res = set_local_var(var, 0); - } else - res = -1; - if (res) - fprintf(stderr, "read: %m\n"); - free(var); /* So not move up to avoid breaking errno */ - return res; - } else { - do res=getchar(); while(res!='\n' && res!=EOF); - return 0; - } -} - -/* built-in 'set VAR=value' handler */ -static int builtin_set(struct child_prog *child) -{ - char *temp = child->argv[1]; - struct variables *e; - - if (temp == NULL) - for(e = top_vars; e; e=e->next) - printf("%s=%s\n", e->name, e->value); - else - set_local_var(temp, 0); - - return EXIT_SUCCESS; -} - - -/* Built-in 'shift' handler */ -static int builtin_shift(struct child_prog *child) -{ - int n=1; - if (child->argv[1]) { - n=atoi(child->argv[1]); - } - if (n>=0 && nargv[1] == NULL) - return EXIT_FAILURE; - - /* XXX search through $PATH is missing */ - input = fopen(child->argv[1], "r"); - if (!input) { - error_msg("Couldn't open file '%s'", child->argv[1]); - return EXIT_FAILURE; - } - - /* Now run the file */ - /* XXX argv and argc are broken; need to save old global_argv - * (pointer only is OK!) on this stack frame, - * set global_argv=child->argv+1, recurse, and restore. */ - mark_open(fileno(input)); - status = parse_file_outer(input); - mark_closed(fileno(input)); - fclose(input); - return (status); -} - -static int builtin_umask(struct child_prog *child) -{ - mode_t new_umask; - const char *arg = child->argv[1]; - char *end; - if (arg) { - new_umask=strtoul(arg, &end, 8); - if (*end!='\0' || end == arg) { - return EXIT_FAILURE; - } - } else { - printf("%.3o\n", (unsigned int) (new_umask=umask(0))); - } - umask(new_umask); - return EXIT_SUCCESS; -} - -/* built-in 'unset VAR' handler */ -static int builtin_unset(struct child_prog *child) -{ - /* bash returned already true */ - unset_local_var(child->argv[1]); - return EXIT_SUCCESS; -} - -static int builtin_not_written(struct child_prog *child) -{ - printf("builtin_%s not written\n",child->argv[0]); - return EXIT_FAILURE; -} -#endif - -static int b_check_space(o_string *o, int len) -{ - /* It would be easy to drop a more restrictive policy - * in here, such as setting a maximum string length */ - if (o->length + len > o->maxlen) { - char *old_data = o->data; - /* assert (data == NULL || o->maxlen != 0); */ - o->maxlen += max(2*len, B_CHUNK); - o->data = realloc(o->data, 1 + o->maxlen); - if (o->data == NULL) { - free(old_data); - } - } - return o->data == NULL; -} - -static int b_addchr(o_string *o, int ch) -{ - debug_printf("b_addchr: %c %d %p\n", ch, o->length, o); - if (b_check_space(o, 1)) return B_NOSPAC; - o->data[o->length] = ch; - o->length++; - o->data[o->length] = '\0'; - return 0; -} - -static void b_reset(o_string *o) -{ - o->length = 0; - o->nonnull = 0; - if (o->data != NULL) *o->data = '\0'; -} - -static void b_free(o_string *o) -{ - b_reset(o); - free(o->data); - o->data = NULL; - o->maxlen = 0; -} - -/* My analysis of quoting semantics tells me that state information - * is associated with a destination, not a source. - */ -static int b_addqchr(o_string *o, int ch, int quote) -{ - if (quote && strchr("*?[\\",ch)) { - int rc; - rc = b_addchr(o, '\\'); - if (rc) return rc; - } - return b_addchr(o, ch); -} - -#ifndef __U_BOOT__ -static int b_adduint(o_string *o, unsigned int i) -{ - int r; - char *p = simple_itoa(i); - /* no escape checking necessary */ - do r=b_addchr(o, *p++); while (r==0 && *p); - return r; -} -#endif - -static int static_get(struct in_str *i) -{ - int ch = *i->p++; - if (ch=='\0') return EOF; - return ch; -} - -static int static_peek(struct in_str *i) -{ - return *i->p; -} - -#ifndef __U_BOOT__ -static inline void cmdedit_set_initial_prompt(void) -{ -#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT - PS1 = NULL; -#else - PS1 = getenv("PS1"); - if(PS1==0) - PS1 = "\\w \\$ "; -#endif -} - -static inline void setup_prompt_string(int promptmode, char **prompt_str) -{ - debug_printf("setup_prompt_string %d ",promptmode); -#ifndef CONFIG_FEATURE_SH_FANCY_PROMPT - /* Set up the prompt */ - if (promptmode == 1) { - free(PS1); - PS1=xmalloc(strlen(cwd)+4); - sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# "); - *prompt_str = PS1; - } else { - *prompt_str = PS2; - } -#else - *prompt_str = (promptmode==1)? PS1 : PS2; -#endif - debug_printf("result %s\n",*prompt_str); -} -#endif - -static void get_user_input(struct in_str *i) -{ -#ifndef __U_BOOT__ - char *prompt_str; - static char the_command[BUFSIZ]; - - setup_prompt_string(i->promptmode, &prompt_str); -#ifdef CONFIG_FEATURE_COMMAND_EDITING - /* - ** enable command line editing only while a command line - ** is actually being read; otherwise, we'll end up bequeathing - ** atexit() handlers and other unwanted stuff to our - ** child processes (rob@sysgo.de) - */ - cmdedit_read_input(prompt_str, the_command); -#else - fputs(prompt_str, stdout); - fflush(stdout); - the_command[0]=fgetc(i->file); - the_command[1]='\0'; -#endif - fflush(stdout); - i->p = the_command; -#else - int n; - static char the_command[CONFIG_SYS_CBSIZE + 1]; - -#ifdef CONFIG_BOOT_RETRY_TIME -# ifndef CONFIG_RESET_TO_RETRY -# error "This currently only works with CONFIG_RESET_TO_RETRY enabled" -# endif - reset_cmd_timeout(); -#endif - i->__promptme = 1; - if (i->promptmode == 1) { - n = readline(CONFIG_SYS_PROMPT); - } else { - n = readline(CONFIG_SYS_PROMPT_HUSH_PS2); - } -#ifdef CONFIG_BOOT_RETRY_TIME - if (n == -2) { - puts("\nTimeout waiting for command\n"); -# ifdef CONFIG_RESET_TO_RETRY - do_reset(NULL, 0, 0, NULL); -# else -# error "This currently only works with CONFIG_RESET_TO_RETRY enabled" -# endif - } -#endif - if (n == -1 ) { - flag_repeat = 0; - i->__promptme = 0; - } - n = strlen(console_buffer); - console_buffer[n] = '\n'; - console_buffer[n+1]= '\0'; - if (had_ctrlc()) flag_repeat = 0; - clear_ctrlc(); - do_repeat = 0; - if (i->promptmode == 1) { - if (console_buffer[0] == '\n'&& flag_repeat == 0) { - strcpy(the_command,console_buffer); - } - else { - if (console_buffer[0] != '\n') { - strcpy(the_command,console_buffer); - flag_repeat = 1; - } - else { - do_repeat = 1; - } - } - i->p = the_command; - } - else { - if (console_buffer[0] != '\n') { - if (strlen(the_command) + strlen(console_buffer) - < CONFIG_SYS_CBSIZE) { - n = strlen(the_command); - the_command[n-1] = ' '; - strcpy(&the_command[n],console_buffer); - } - else { - the_command[0] = '\n'; - the_command[1] = '\0'; - flag_repeat = 0; - } - } - if (i->__promptme == 0) { - the_command[0] = '\n'; - the_command[1] = '\0'; - } - i->p = console_buffer; - } -#endif -} - -/* This is the magic location that prints prompts - * and gets data back from the user */ -static int file_get(struct in_str *i) -{ - int ch; - - ch = 0; - /* If there is data waiting, eat it up */ - if (i->p && *i->p) { - ch = *i->p++; - } else { - /* need to double check i->file because we might be doing something - * more complicated by now, like sourcing or substituting. */ -#ifndef __U_BOOT__ - if (i->__promptme && interactive && i->file == stdin) { - while(! i->p || (interactive && strlen(i->p)==0) ) { -#else - while(! i->p || strlen(i->p)==0 ) { -#endif - get_user_input(i); - } - i->promptmode=2; -#ifndef __U_BOOT__ - i->__promptme = 0; -#endif - if (i->p && *i->p) { - ch = *i->p++; - } -#ifndef __U_BOOT__ - } else { - ch = fgetc(i->file); - } - -#endif - debug_printf("b_getch: got a %d\n", ch); - } -#ifndef __U_BOOT__ - if (ch == '\n') i->__promptme=1; -#endif - return ch; -} - -/* All the callers guarantee this routine will never be - * used right after a newline, so prompting is not needed. - */ -static int file_peek(struct in_str *i) -{ -#ifndef __U_BOOT__ - if (i->p && *i->p) { -#endif - return *i->p; -#ifndef __U_BOOT__ - } else { - i->peek_buf[0] = fgetc(i->file); - i->peek_buf[1] = '\0'; - i->p = i->peek_buf; - debug_printf("b_peek: got a %d\n", *i->p); - return *i->p; - } -#endif -} - -#ifndef __U_BOOT__ -static void setup_file_in_str(struct in_str *i, FILE *f) -#else -static void setup_file_in_str(struct in_str *i) -#endif -{ - i->peek = file_peek; - i->get = file_get; - i->__promptme=1; - i->promptmode=1; -#ifndef __U_BOOT__ - i->file = f; -#endif - i->p = NULL; -} - -static void setup_string_in_str(struct in_str *i, const char *s) -{ - i->peek = static_peek; - i->get = static_get; - i->__promptme=1; - i->promptmode=1; - i->p = s; -} - -#ifndef __U_BOOT__ -static void mark_open(int fd) -{ - struct close_me *new = xmalloc(sizeof(struct close_me)); - new->fd = fd; - new->next = close_me_head; - close_me_head = new; -} - -static void mark_closed(int fd) -{ - struct close_me *tmp; - if (close_me_head == NULL || close_me_head->fd != fd) - error_msg_and_die("corrupt close_me"); - tmp = close_me_head; - close_me_head = close_me_head->next; - free(tmp); -} - -static void close_all(void) -{ - struct close_me *c; - for (c=close_me_head; c; c=c->next) { - close(c->fd); - } - close_me_head = NULL; -} - -/* squirrel != NULL means we squirrel away copies of stdin, stdout, - * and stderr if they are redirected. */ -static int setup_redirects(struct child_prog *prog, int squirrel[]) -{ - int openfd, mode; - struct redir_struct *redir; - - for (redir=prog->redirects; redir; redir=redir->next) { - if (redir->dup == -1 && redir->word.gl_pathv == NULL) { - /* something went wrong in the parse. Pretend it didn't happen */ - continue; - } - if (redir->dup == -1) { - mode=redir_table[redir->type].mode; - openfd = open(redir->word.gl_pathv[0], mode, 0666); - if (openfd < 0) { - /* this could get lost if stderr has been redirected, but - bash and ash both lose it as well (though zsh doesn't!) */ - perror_msg("error opening %s", redir->word.gl_pathv[0]); - return 1; - } - } else { - openfd = redir->dup; - } - - if (openfd != redir->fd) { - if (squirrel && redir->fd < 3) { - squirrel[redir->fd] = dup(redir->fd); - } - if (openfd == -3) { - close(openfd); - } else { - dup2(openfd, redir->fd); - if (redir->dup == -1) - close (openfd); - } - } - } - return 0; -} - -static void restore_redirects(int squirrel[]) -{ - int i, fd; - for (i=0; i<3; i++) { - fd = squirrel[i]; - if (fd != -1) { - /* No error checking. I sure wouldn't know what - * to do with an error if I found one! */ - dup2(fd, i); - close(fd); - } - } -} - -/* never returns */ -/* XXX no exit() here. If you don't exec, use _exit instead. - * The at_exit handlers apparently confuse the calling process, - * in particular stdin handling. Not sure why? */ -static void pseudo_exec(struct child_prog *child) -{ - int i, rcode; - char *p; - struct built_in_command *x; - if (child->argv) { - for (i=0; is_assignment(child->argv[i]); i++) { - debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]); - p = insert_var_value(child->argv[i]); - putenv(strdup(p)); - if (p != child->argv[i]) free(p); - } - child->argv+=i; /* XXX this hack isn't so horrible, since we are about - to exit, and therefore don't need to keep data - structures consistent for free() use. */ - /* If a variable is assigned in a forest, and nobody listens, - * was it ever really set? - */ - if (child->argv[0] == NULL) { - _exit(EXIT_SUCCESS); - } - - /* - * Check if the command matches any of the builtins. - * Depending on context, this might be redundant. But it's - * easier to waste a few CPU cycles than it is to figure out - * if this is one of those cases. - */ - for (x = bltins; x->cmd; x++) { - if (strcmp(child->argv[0], x->cmd) == 0 ) { - debug_printf("builtin exec %s\n", child->argv[0]); - rcode = x->function(child); - fflush(stdout); - _exit(rcode); - } - } - - /* Check if the command matches any busybox internal commands - * ("applets") here. - * FIXME: This feature is not 100% safe, since - * BusyBox is not fully reentrant, so we have no guarantee the things - * from the .bss are still zeroed, or that things from .data are still - * at their defaults. We could exec ourself from /proc/self/exe, but I - * really dislike relying on /proc for things. We could exec ourself - * from global_argv[0], but if we are in a chroot, we may not be able - * to find ourself... */ -#ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL - { - int argc_l; - char** argv_l=child->argv; - char *name = child->argv[0]; - -#ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN - /* Following discussions from November 2000 on the busybox mailing - * list, the default configuration, (without - * get_last_path_component()) lets the user force use of an - * external command by specifying the full (with slashes) filename. - * If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets - * _aways_ override external commands, so if you want to run - * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the - * filesystem and is _not_ busybox. Some systems may want this, - * most do not. */ - name = get_last_path_component(name); -#endif - /* Count argc for use in a second... */ - for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++); - optind = 1; - debug_printf("running applet %s\n", name); - run_applet_by_name(name, argc_l, child->argv); - } -#endif - debug_printf("exec of %s\n",child->argv[0]); - execvp(child->argv[0],child->argv); - perror_msg("couldn't exec: %s",child->argv[0]); - _exit(1); - } else if (child->group) { - debug_printf("runtime nesting to group\n"); - interactive=0; /* crucial!!!! */ - rcode = run_list_real(child->group); - /* OK to leak memory by not calling free_pipe_list, - * since this process is about to exit */ - _exit(rcode); - } else { - /* Can happen. See what bash does with ">foo" by itself. */ - debug_printf("trying to pseudo_exec null command\n"); - _exit(EXIT_SUCCESS); - } -} - -static void insert_bg_job(struct pipe *pi) -{ - struct pipe *thejob; - - /* Linear search for the ID of the job to use */ - pi->jobid = 1; - for (thejob = job_list; thejob; thejob = thejob->next) - if (thejob->jobid >= pi->jobid) - pi->jobid = thejob->jobid + 1; - - /* add thejob to the list of running jobs */ - if (!job_list) { - thejob = job_list = xmalloc(sizeof(*thejob)); - } else { - for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */; - thejob->next = xmalloc(sizeof(*thejob)); - thejob = thejob->next; - } - - /* physically copy the struct job */ - memcpy(thejob, pi, sizeof(struct pipe)); - thejob->next = NULL; - thejob->running_progs = thejob->num_progs; - thejob->stopped_progs = 0; - thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */ - - /*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */ - { - char *bar=thejob->text; - char **foo=pi->progs[0].argv; - while(foo && *foo) { - bar += sprintf(bar, "%s ", *foo++); - } - } - - /* we don't wait for background thejobs to return -- append it - to the list of backgrounded thejobs and leave it alone */ - printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid); - last_bg_pid = thejob->progs[0].pid; - last_jobid = thejob->jobid; -} - -/* remove a backgrounded job */ -static void remove_bg_job(struct pipe *pi) -{ - struct pipe *prev_pipe; - - if (pi == job_list) { - job_list = pi->next; - } else { - prev_pipe = job_list; - while (prev_pipe->next != pi) - prev_pipe = prev_pipe->next; - prev_pipe->next = pi->next; - } - if (job_list) - last_jobid = job_list->jobid; - else - last_jobid = 0; - - pi->stopped_progs = 0; - free_pipe(pi, 0); - free(pi); -} - -/* Checks to see if any processes have exited -- if they - have, figure out why and see if a job has completed */ -static int checkjobs(struct pipe* fg_pipe) -{ - int attributes; - int status; - int prognum = 0; - struct pipe *pi; - pid_t childpid; - - attributes = WUNTRACED; - if (fg_pipe==NULL) { - attributes |= WNOHANG; - } - - while ((childpid = waitpid(-1, &status, attributes)) > 0) { - if (fg_pipe) { - int i, rcode = 0; - for (i=0; i < fg_pipe->num_progs; i++) { - if (fg_pipe->progs[i].pid == childpid) { - if (i==fg_pipe->num_progs-1) - rcode=WEXITSTATUS(status); - (fg_pipe->num_progs)--; - return(rcode); - } - } - } - - for (pi = job_list; pi; pi = pi->next) { - prognum = 0; - while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) { - prognum++; - } - if (prognum < pi->num_progs) - break; - } - - if(pi==NULL) { - debug_printf("checkjobs: pid %d was not in our list!\n", childpid); - continue; - } - - if (WIFEXITED(status) || WIFSIGNALED(status)) { - /* child exited */ - pi->running_progs--; - pi->progs[prognum].pid = 0; - - if (!pi->running_progs) { - printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text); - remove_bg_job(pi); - } - } else { - /* child stopped */ - pi->stopped_progs++; - pi->progs[prognum].is_stopped = 1; - -#if 0 - /* Printing this stuff is a pain, since it tends to - * overwrite the prompt an inconveinient moments. So - * don't do that. */ - if (pi->stopped_progs == pi->num_progs) { - printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text); - } -#endif - } - } - - if (childpid == -1 && errno != ECHILD) - perror_msg("waitpid"); - - /* move the shell to the foreground */ - /*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */ - /* perror_msg("tcsetpgrp-2"); */ - return -1; -} - -/* Figure out our controlling tty, checking in order stderr, - * stdin, and stdout. If check_pgrp is set, also check that - * we belong to the foreground process group associated with - * that tty. The value of shell_terminal is needed in order to call - * tcsetpgrp(shell_terminal, ...); */ -void controlling_tty(int check_pgrp) -{ - pid_t curpgrp; - - if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0 - && (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0 - && (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0) - goto shell_terminal_error; - - if (check_pgrp && curpgrp != getpgid(0)) - goto shell_terminal_error; - - return; - -shell_terminal_error: - shell_terminal = -1; - return; -} -#endif - -/* run_pipe_real() starts all the jobs, but doesn't wait for anything - * to finish. See checkjobs(). - * - * return code is normally -1, when the caller has to wait for children - * to finish to determine the exit status of the pipe. If the pipe - * is a simple builtin command, however, the action is done by the - * time run_pipe_real returns, and the exit code is provided as the - * return value. - * - * The input of the pipe is always stdin, the output is always - * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus, - * because it tries to avoid running the command substitution in - * subshell, when that is in fact necessary. The subshell process - * now has its stdout directed to the input of the appropriate pipe, - * so this routine is noticeably simpler. - */ -static int run_pipe_real(struct pipe *pi) -{ - int i; -#ifndef __U_BOOT__ - int nextin, nextout; - int pipefds[2]; /* pipefds[0] is for reading */ - struct child_prog *child; - struct built_in_command *x; - char *p; -# if __GNUC__ - /* Avoid longjmp clobbering */ - (void) &i; - (void) &nextin; - (void) &nextout; - (void) &child; -# endif -#else - int nextin; - int flag = do_repeat ? CMD_FLAG_REPEAT : 0; - struct child_prog *child; - char *p; -# if __GNUC__ - /* Avoid longjmp clobbering */ - (void) &i; - (void) &nextin; - (void) &child; -# endif -#endif /* __U_BOOT__ */ - - nextin = 0; -#ifndef __U_BOOT__ - pi->pgrp = -1; -#endif - - /* Check if this is a simple builtin (not part of a pipe). - * Builtins within pipes have to fork anyway, and are handled in - * pseudo_exec. "echo foo | read bar" doesn't work on bash, either. - */ - if (pi->num_progs == 1) child = & (pi->progs[0]); -#ifndef __U_BOOT__ - if (pi->num_progs == 1 && child->group && child->subshell == 0) { - int squirrel[] = {-1, -1, -1}; - int rcode; - debug_printf("non-subshell grouping\n"); - setup_redirects(child, squirrel); - /* XXX could we merge code with following builtin case, - * by creating a pseudo builtin that calls run_list_real? */ - rcode = run_list_real(child->group); - restore_redirects(squirrel); -#else - if (pi->num_progs == 1 && child->group) { - int rcode; - debug_printf("non-subshell grouping\n"); - rcode = run_list_real(child->group); -#endif - return rcode; - } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) { - for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ } - if (i!=0 && child->argv[i]==NULL) { - /* assignments, but no command: set the local environment */ - for (i=0; child->argv[i]!=NULL; i++) { - - /* Ok, this case is tricky. We have to decide if this is a - * local variable, or an already exported variable. If it is - * already exported, we have to export the new value. If it is - * not exported, we need only set this as a local variable. - * This junk is all to decide whether or not to export this - * variable. */ - int export_me=0; - char *name, *value; - name = xstrdup(child->argv[i]); - debug_printf("Local environment set: %s\n", name); - value = strchr(name, '='); - if (value) - *value=0; -#ifndef __U_BOOT__ - if ( get_local_var(name)) { - export_me=1; - } -#endif - free(name); - p = insert_var_value(child->argv[i]); - set_local_var(p, export_me); - if (p != child->argv[i]) free(p); - } - return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */ - } - for (i = 0; is_assignment(child->argv[i]); i++) { - p = insert_var_value(child->argv[i]); -#ifndef __U_BOOT__ - putenv(strdup(p)); -#else - set_local_var(p, 0); -#endif - if (p != child->argv[i]) { - child->sp--; - free(p); - } - } - if (child->sp) { - char * str = NULL; - - str = make_string(child->argv + i, - child->argv_nonnull + i); - parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING); - free(str); - return last_return_code; - } -#ifndef __U_BOOT__ - for (x = bltins; x->cmd; x++) { - if (strcmp(child->argv[i], x->cmd) == 0 ) { - int squirrel[] = {-1, -1, -1}; - int rcode; - if (x->function == builtin_exec && child->argv[i+1]==NULL) { - debug_printf("magic exec\n"); - setup_redirects(child,NULL); - return EXIT_SUCCESS; - } - debug_printf("builtin inline %s\n", child->argv[0]); - /* XXX setup_redirects acts on file descriptors, not FILEs. - * This is perfect for work that comes after exec(). - * Is it really safe for inline use? Experimentally, - * things seem to work with glibc. */ - setup_redirects(child, squirrel); - - child->argv += i; /* XXX horrible hack */ - rcode = x->function(child); - /* XXX restore hack so free() can work right */ - child->argv -= i; - restore_redirects(squirrel); - } - return rcode; - } -#else - /* check ";", because ,example , argv consist from - * "help;flinfo" must not execute - */ - if (strchr(child->argv[i], ';')) { - printf("Unknown command '%s' - try 'help' or use " - "'run' command\n", child->argv[i]); - return -1; - } - /* Process the command */ - return cmd_process(flag, child->argc, child->argv, - &flag_repeat, NULL); -#endif - } -#ifndef __U_BOOT__ - - for (i = 0; i < pi->num_progs; i++) { - child = & (pi->progs[i]); - - /* pipes are inserted between pairs of commands */ - if ((i + 1) < pi->num_progs) { - if (pipe(pipefds)<0) perror_msg_and_die("pipe"); - nextout = pipefds[1]; - } else { - nextout=1; - pipefds[0] = -1; - } - - /* XXX test for failed fork()? */ - if (!(child->pid = fork())) { - /* Set the handling for job control signals back to the default. */ - signal(SIGINT, SIG_DFL); - signal(SIGQUIT, SIG_DFL); - signal(SIGTERM, SIG_DFL); - signal(SIGTSTP, SIG_DFL); - signal(SIGTTIN, SIG_DFL); - signal(SIGTTOU, SIG_DFL); - signal(SIGCHLD, SIG_DFL); - - close_all(); - - if (nextin != 0) { - dup2(nextin, 0); - close(nextin); - } - if (nextout != 1) { - dup2(nextout, 1); - close(nextout); - } - if (pipefds[0]!=-1) { - close(pipefds[0]); /* opposite end of our output pipe */ - } - - /* Like bash, explicit redirects override pipes, - * and the pipe fd is available for dup'ing. */ - setup_redirects(child,NULL); - - if (interactive && pi->followup!=PIPE_BG) { - /* If we (the child) win the race, put ourselves in the process - * group whose leader is the first process in this pipe. */ - if (pi->pgrp < 0) { - pi->pgrp = getpid(); - } - if (setpgid(0, pi->pgrp) == 0) { - tcsetpgrp(2, pi->pgrp); - } - } - - pseudo_exec(child); - } - - - /* put our child in the process group whose leader is the - first process in this pipe */ - if (pi->pgrp < 0) { - pi->pgrp = child->pid; - } - /* Don't check for errors. The child may be dead already, - * in which case setpgid returns error code EACCES. */ - setpgid(child->pid, pi->pgrp); - - if (nextin != 0) - close(nextin); - if (nextout != 1) - close(nextout); - - /* If there isn't another process, nextin is garbage - but it doesn't matter */ - nextin = pipefds[0]; - } -#endif - return -1; -} - -static int run_list_real(struct pipe *pi) -{ - char *save_name = NULL; - char **list = NULL; - char **save_list = NULL; - struct pipe *rpipe; - int flag_rep = 0; -#ifndef __U_BOOT__ - int save_num_progs; -#endif - int rcode=0, flag_skip=1; - int flag_restore = 0; - int if_code=0, next_if_code=0; /* need double-buffer to handle elif */ - reserved_style rmode, skip_more_in_this_rmode=RES_XXXX; - /* check syntax for "for" */ - for (rpipe = pi; rpipe; rpipe = rpipe->next) { - if ((rpipe->r_mode == RES_IN || - rpipe->r_mode == RES_FOR) && - (rpipe->next == NULL)) { - syntax(); -#ifdef __U_BOOT__ - flag_repeat = 0; -#endif - return 1; - } - if ((rpipe->r_mode == RES_IN && - (rpipe->next->r_mode == RES_IN && - rpipe->next->progs->argv != NULL))|| - (rpipe->r_mode == RES_FOR && - rpipe->next->r_mode != RES_IN)) { - syntax(); -#ifdef __U_BOOT__ - flag_repeat = 0; -#endif - return 1; - } - } - for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) { - if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL || - pi->r_mode == RES_FOR) { -#ifdef __U_BOOT__ - /* check Ctrl-C */ - ctrlc(); - if ((had_ctrlc())) { - return 1; - } -#endif - flag_restore = 0; - if (!rpipe) { - flag_rep = 0; - rpipe = pi; - } - } - rmode = pi->r_mode; - 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); - if (rmode == skip_more_in_this_rmode && flag_skip) { - if (pi->followup == PIPE_SEQ) flag_skip=0; - continue; - } - flag_skip = 1; - skip_more_in_this_rmode = RES_XXXX; - if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code; - if (rmode == RES_THEN && if_code) continue; - if (rmode == RES_ELSE && !if_code) continue; - if (rmode == RES_ELIF && !if_code) break; - if (rmode == RES_FOR && pi->num_progs) { - if (!list) { - /* if no variable values after "in" we skip "for" */ - if (!pi->next->progs->argv) continue; - /* create list of variable values */ - list = make_list_in(pi->next->progs->argv, - pi->progs->argv[0]); - save_list = list; - save_name = pi->progs->argv[0]; - pi->progs->argv[0] = NULL; - flag_rep = 1; - } - if (!(*list)) { - free(pi->progs->argv[0]); - free(save_list); - list = NULL; - flag_rep = 0; - pi->progs->argv[0] = save_name; -#ifndef __U_BOOT__ - pi->progs->glob_result.gl_pathv[0] = - pi->progs->argv[0]; -#endif - continue; - } else { - /* insert new value from list for variable */ - if (pi->progs->argv[0]) - free(pi->progs->argv[0]); - pi->progs->argv[0] = *list++; -#ifndef __U_BOOT__ - pi->progs->glob_result.gl_pathv[0] = - pi->progs->argv[0]; -#endif - } - } - if (rmode == RES_IN) continue; - if (rmode == RES_DO) { - if (!flag_rep) continue; - } - if ((rmode == RES_DONE)) { - if (flag_rep) { - flag_restore = 1; - } else { - rpipe = NULL; - } - } - if (pi->num_progs == 0) continue; -#ifndef __U_BOOT__ - save_num_progs = pi->num_progs; /* save number of programs */ -#endif - rcode = run_pipe_real(pi); - debug_printf("run_pipe_real returned %d\n",rcode); -#ifndef __U_BOOT__ - if (rcode!=-1) { - /* We only ran a builtin: rcode was set by the return value - * of run_pipe_real(), and we don't need to wait for anything. */ - } else if (pi->followup==PIPE_BG) { - /* XXX check bash's behavior with nontrivial pipes */ - /* XXX compute jobid */ - /* XXX what does bash do with attempts to background builtins? */ - insert_bg_job(pi); - rcode = EXIT_SUCCESS; - } else { - if (interactive) { - /* move the new process group into the foreground */ - if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY) - perror_msg("tcsetpgrp-3"); - rcode = checkjobs(pi); - /* move the shell to the foreground */ - if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY) - perror_msg("tcsetpgrp-4"); - } else { - rcode = checkjobs(pi); - } - debug_printf("checkjobs returned %d\n",rcode); - } - last_return_code=rcode; -#else - if (rcode < -1) { - last_return_code = -rcode - 2; - return -2; /* exit */ - } - last_return_code=(rcode == 0) ? 0 : 1; -#endif -#ifndef __U_BOOT__ - pi->num_progs = save_num_progs; /* restore number of programs */ -#endif - if ( rmode == RES_IF || rmode == RES_ELIF ) - next_if_code=rcode; /* can be overwritten a number of times */ - if (rmode == RES_WHILE) - flag_rep = !last_return_code; - if (rmode == RES_UNTIL) - flag_rep = last_return_code; - if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) || - (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) ) - skip_more_in_this_rmode=rmode; -#ifndef __U_BOOT__ - checkjobs(NULL); -#endif - } - return rcode; -} - -/* broken, of course, but OK for testing */ -static char *indenter(int i) -{ - static char blanks[]=" "; - return &blanks[sizeof(blanks)-i-1]; -} - -/* return code is the exit status of the pipe */ -static int free_pipe(struct pipe *pi, int indent) -{ - char **p; - struct child_prog *child; -#ifndef __U_BOOT__ - struct redir_struct *r, *rnext; -#endif - int a, i, ret_code=0; - char *ind = indenter(indent); - -#ifndef __U_BOOT__ - if (pi->stopped_progs > 0) - return ret_code; - final_printf("%s run pipe: (pid %d)\n",ind,getpid()); -#endif - for (i=0; inum_progs; i++) { - child = &pi->progs[i]; - final_printf("%s command %d:\n",ind,i); - if (child->argv) { - for (a=0,p=child->argv; *p; a++,p++) { - final_printf("%s argv[%d] = %s\n",ind,a,*p); - } -#ifndef __U_BOOT__ - globfree(&child->glob_result); -#else - for (a = 0; a < child->argc; a++) { - free(child->argv[a]); - } - free(child->argv); - free(child->argv_nonnull); - child->argc = 0; -#endif - child->argv=NULL; - } else if (child->group) { -#ifndef __U_BOOT__ - final_printf("%s begin group (subshell:%d)\n",ind, child->subshell); -#endif - ret_code = free_pipe_list(child->group,indent+3); - final_printf("%s end group\n",ind); - } else { - final_printf("%s (nil)\n",ind); - } -#ifndef __U_BOOT__ - for (r=child->redirects; r; r=rnext) { - final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip); - if (r->dup == -1) { - /* guard against the case >$FOO, where foo is unset or blank */ - if (r->word.gl_pathv) { - final_printf(" %s\n", *r->word.gl_pathv); - globfree(&r->word); - } - } else { - final_printf("&%d\n", r->dup); - } - rnext=r->next; - free(r); - } - child->redirects=NULL; -#endif - } - free(pi->progs); /* children are an array, they get freed all at once */ - pi->progs=NULL; - return ret_code; -} - -static int free_pipe_list(struct pipe *head, int indent) -{ - int rcode=0; /* if list has no members */ - struct pipe *pi, *next; - char *ind = indenter(indent); - for (pi=head; pi; pi=next) { - final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode); - rcode = free_pipe(pi, indent); - final_printf("%s pipe followup code %d\n", ind, pi->followup); - next=pi->next; - pi->next=NULL; - free(pi); - } - return rcode; -} - -/* Select which version we will use */ -static int run_list(struct pipe *pi) -{ - int rcode=0; -#ifndef __U_BOOT__ - if (fake_mode==0) { -#endif - rcode = run_list_real(pi); -#ifndef __U_BOOT__ - } -#endif - /* free_pipe_list has the side effect of clearing memory - * In the long run that function can be merged with run_list_real, - * but doing that now would hobble the debugging effort. */ - free_pipe_list(pi,0); - return rcode; -} - -/* The API for glob is arguably broken. This routine pushes a non-matching - * string into the output structure, removing non-backslashed backslashes. - * If someone can prove me wrong, by performing this function within the - * original glob(3) api, feel free to rewrite this routine into oblivion. - * Return code (0 vs. GLOB_NOSPACE) matches glob(3). - * XXX broken if the last character is '\\', check that before calling. - */ -#ifndef __U_BOOT__ -static int globhack(const char *src, int flags, glob_t *pglob) -{ - int cnt=0, pathc; - const char *s; - char *dest; - for (cnt=1, s=src; s && *s; s++) { - if (*s == '\\') s++; - cnt++; - } - dest = malloc(cnt); - if (!dest) return GLOB_NOSPACE; - if (!(flags & GLOB_APPEND)) { - pglob->gl_pathv=NULL; - pglob->gl_pathc=0; - pglob->gl_offs=0; - pglob->gl_offs=0; - } - pathc = ++pglob->gl_pathc; - pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv)); - if (pglob->gl_pathv == NULL) return GLOB_NOSPACE; - pglob->gl_pathv[pathc-1]=dest; - pglob->gl_pathv[pathc]=NULL; - for (s=src; s && *s; s++, dest++) { - if (*s == '\\') s++; - *dest = *s; - } - *dest='\0'; - return 0; -} - -/* XXX broken if the last character is '\\', check that before calling */ -static int glob_needed(const char *s) -{ - for (; *s; s++) { - if (*s == '\\') s++; - if (strchr("*[?",*s)) return 1; - } - return 0; -} - -#if 0 -static void globprint(glob_t *pglob) -{ - int i; - debug_printf("glob_t at %p:\n", pglob); - debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n", - pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags); - for (i=0; igl_pathc; i++) - debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i, - pglob->gl_pathv[i], pglob->gl_pathv[i]); -} -#endif - -static int xglob(o_string *dest, int flags, glob_t *pglob) -{ - int gr; - - /* short-circuit for null word */ - /* we can code this better when the debug_printf's are gone */ - if (dest->length == 0) { - if (dest->nonnull) { - /* bash man page calls this an "explicit" null */ - gr = globhack(dest->data, flags, pglob); - debug_printf("globhack returned %d\n",gr); - } else { - return 0; - } - } else if (glob_needed(dest->data)) { - gr = glob(dest->data, flags, NULL, pglob); - debug_printf("glob returned %d\n",gr); - if (gr == GLOB_NOMATCH) { - /* quote removal, or more accurately, backslash removal */ - gr = globhack(dest->data, flags, pglob); - debug_printf("globhack returned %d\n",gr); - } - } else { - gr = globhack(dest->data, flags, pglob); - debug_printf("globhack returned %d\n",gr); - } - if (gr == GLOB_NOSPACE) - error_msg_and_die("out of memory during glob"); - if (gr != 0) { /* GLOB_ABORTED ? */ - error_msg("glob(3) error %d",gr); - } - /* globprint(glob_target); */ - return gr; -} -#endif - -#ifdef __U_BOOT__ -static char *get_dollar_var(char ch); -#endif - -/* This is used to get/check local shell variables */ -char *get_local_var(const char *s) -{ - struct variables *cur; - - if (!s) - return NULL; - -#ifdef __U_BOOT__ - if (*s == '$') - return get_dollar_var(s[1]); -#endif - - for (cur = top_vars; cur; cur=cur->next) - if(strcmp(cur->name, s)==0) - return cur->value; - return NULL; -} - -/* This is used to set local shell variables - flg_export==0 if only local (not exporting) variable - flg_export==1 if "new" exporting environ - flg_export>1 if current startup environ (not call putenv()) */ -int set_local_var(const char *s, int flg_export) -{ - char *name, *value; - int result=0; - struct variables *cur; - -#ifdef __U_BOOT__ - /* might be possible! */ - if (!isalpha(*s)) - return -1; -#endif - - name=strdup(s); - -#ifdef __U_BOOT__ - if (getenv(name) != NULL) { - printf ("ERROR: " - "There is a global environment variable with the same name.\n"); - free(name); - return -1; - } -#endif - /* Assume when we enter this function that we are already in - * NAME=VALUE format. So the first order of business is to - * split 's' on the '=' into 'name' and 'value' */ - value = strchr(name, '='); - if (value == NULL && ++value == NULL) { - free(name); - return -1; - } - *value++ = 0; - - for(cur = top_vars; cur; cur = cur->next) { - if(strcmp(cur->name, name)==0) - break; - } - - if(cur) { - if(strcmp(cur->value, value)==0) { - if(flg_export>0 && cur->flg_export==0) - cur->flg_export=flg_export; - else - result++; - } else { - if(cur->flg_read_only) { - error_msg("%s: readonly variable", name); - result = -1; - } else { - if(flg_export>0 || cur->flg_export>1) - cur->flg_export=1; - free(cur->value); - - cur->value = strdup(value); - } - } - } else { - cur = malloc(sizeof(struct variables)); - if(!cur) { - result = -1; - } else { - cur->name = strdup(name); - if (cur->name == NULL) { - free(cur); - result = -1; - } else { - struct variables *bottom = top_vars; - cur->value = strdup(value); - cur->next = NULL; - cur->flg_export = flg_export; - cur->flg_read_only = 0; - while(bottom->next) bottom=bottom->next; - bottom->next = cur; - } - } - } - -#ifndef __U_BOOT__ - if(result==0 && cur->flg_export==1) { - *(value-1) = '='; - result = putenv(name); - } else { -#endif - free(name); -#ifndef __U_BOOT__ - if(result>0) /* equivalent to previous set */ - result = 0; - } -#endif - return result; -} - -void unset_local_var(const char *name) -{ - struct variables *cur; - - if (name) { - for (cur = top_vars; cur; cur=cur->next) { - if(strcmp(cur->name, name)==0) - break; - } - if (cur != NULL) { - struct variables *next = top_vars; - if(cur->flg_read_only) { - error_msg("%s: readonly variable", name); - return; - } else { -#ifndef __U_BOOT__ - if(cur->flg_export) - unsetenv(cur->name); -#endif - free(cur->name); - free(cur->value); - while (next->next != cur) - next = next->next; - next->next = cur->next; - } - free(cur); - } - } -} - -static int is_assignment(const char *s) -{ - if (s == NULL) - return 0; - - if (!isalpha(*s)) return 0; - ++s; - while(isalnum(*s) || *s=='_') ++s; - return *s=='='; -} - -#ifndef __U_BOOT__ -/* the src parameter allows us to peek forward to a possible &n syntax - * for file descriptor duplication, e.g., "2>&1". - * Return code is 0 normally, 1 if a syntax error is detected in src. - * Resource errors (in xmalloc) cause the process to exit */ -static int setup_redirect(struct p_context *ctx, int fd, redir_type style, - struct in_str *input) -{ - struct child_prog *child=ctx->child; - struct redir_struct *redir = child->redirects; - struct redir_struct *last_redir=NULL; - - /* Create a new redir_struct and drop it onto the end of the linked list */ - while(redir) { - last_redir=redir; - redir=redir->next; - } - redir = xmalloc(sizeof(struct redir_struct)); - redir->next=NULL; - redir->word.gl_pathv=NULL; - if (last_redir) { - last_redir->next=redir; - } else { - child->redirects=redir; - } - - redir->type=style; - redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ; - - debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip); - - /* Check for a '2>&1' type redirect */ - redir->dup = redirect_dup_num(input); - if (redir->dup == -2) return 1; /* syntax error */ - if (redir->dup != -1) { - /* Erik had a check here that the file descriptor in question - * is legit; I postpone that to "run time" - * A "-" representation of "close me" shows up as a -3 here */ - debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup); - } else { - /* We do _not_ try to open the file that src points to, - * since we need to return and let src be expanded first. - * Set ctx->pending_redirect, so we know what to do at the - * end of the next parsed word. - */ - ctx->pending_redirect = redir; - } - return 0; -} -#endif - -static struct pipe *new_pipe(void) -{ - struct pipe *pi; - pi = xmalloc(sizeof(struct pipe)); - pi->num_progs = 0; - pi->progs = NULL; - pi->next = NULL; - pi->followup = 0; /* invalid */ - pi->r_mode = RES_NONE; - return pi; -} - -static void initialize_context(struct p_context *ctx) -{ - ctx->pipe=NULL; -#ifndef __U_BOOT__ - ctx->pending_redirect=NULL; -#endif - ctx->child=NULL; - ctx->list_head=new_pipe(); - ctx->pipe=ctx->list_head; - ctx->w=RES_NONE; - ctx->stack=NULL; -#ifdef __U_BOOT__ - ctx->old_flag=0; -#endif - done_command(ctx); /* creates the memory for working child */ -} - -/* normal return is 0 - * if a reserved word is found, and processed, return 1 - * should handle if, then, elif, else, fi, for, while, until, do, done. - * case, function, and select are obnoxious, save those for later. - */ -struct reserved_combo { - char *literal; - int code; - long flag; -}; -/* Mostly a list of accepted follow-up reserved words. - * FLAG_END means we are done with the sequence, and are ready - * to turn the compound list into a command. - * FLAG_START means the word must start a new compound list. - */ -static struct reserved_combo reserved_list[] = { - { "if", RES_IF, FLAG_THEN | FLAG_START }, - { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI }, - { "elif", RES_ELIF, FLAG_THEN }, - { "else", RES_ELSE, FLAG_FI }, - { "fi", RES_FI, FLAG_END }, - { "for", RES_FOR, FLAG_IN | FLAG_START }, - { "while", RES_WHILE, FLAG_DO | FLAG_START }, - { "until", RES_UNTIL, FLAG_DO | FLAG_START }, - { "in", RES_IN, FLAG_DO }, - { "do", RES_DO, FLAG_DONE }, - { "done", RES_DONE, FLAG_END } -}; -#define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo)) - -static int reserved_word(o_string *dest, struct p_context *ctx) -{ - struct reserved_combo *r; - for (r=reserved_list; - rdata, r->literal) == 0) { - debug_printf("found reserved word %s, code %d\n",r->literal,r->code); - if (r->flag & FLAG_START) { - struct p_context *new = xmalloc(sizeof(struct p_context)); - debug_printf("push stack\n"); - if (ctx->w == RES_IN || ctx->w == RES_FOR) { - syntax(); - free(new); - ctx->w = RES_SNTX; - b_reset(dest); - return 1; - } - *new = *ctx; /* physical copy */ - initialize_context(ctx); - ctx->stack=new; - } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<code))) { - syntax(); - ctx->w = RES_SNTX; - b_reset(dest); - return 1; - } - ctx->w=r->code; - ctx->old_flag = r->flag; - if (ctx->old_flag & FLAG_END) { - struct p_context *old; - debug_printf("pop stack\n"); - done_pipe(ctx,PIPE_SEQ); - old = ctx->stack; - old->child->group = ctx->list_head; -#ifndef __U_BOOT__ - old->child->subshell = 0; -#endif - *ctx = *old; /* physical copy */ - free(old); - } - b_reset (dest); - return 1; - } - } - return 0; -} - -/* normal return is 0. - * Syntax or xglob errors return 1. */ -static int done_word(o_string *dest, struct p_context *ctx) -{ - struct child_prog *child=ctx->child; -#ifndef __U_BOOT__ - glob_t *glob_target; - int gr, flags = 0; -#else - char *str, *s; - int argc, cnt; -#endif - - debug_printf("done_word: %s %p\n", dest->data, child); - if (dest->length == 0 && !dest->nonnull) { - debug_printf(" true null, ignored\n"); - return 0; - } -#ifndef __U_BOOT__ - if (ctx->pending_redirect) { - glob_target = &ctx->pending_redirect->word; - } else { -#endif - if (child->group) { - syntax(); - return 1; /* syntax error, groups and arglists don't mix */ - } - if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) { - debug_printf("checking %s for reserved-ness\n",dest->data); - if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX; - } -#ifndef __U_BOOT__ - glob_target = &child->glob_result; - if (child->argv) flags |= GLOB_APPEND; -#else - for (cnt = 1, s = dest->data; s && *s; s++) { - if (*s == '\\') s++; - cnt++; - } - str = malloc(cnt); - if (!str) return 1; - if ( child->argv == NULL) { - child->argc=0; - } - argc = ++child->argc; - child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv)); - if (child->argv == NULL) return 1; - child->argv_nonnull = realloc(child->argv_nonnull, - (argc+1)*sizeof(*child->argv_nonnull)); - if (child->argv_nonnull == NULL) - return 1; - child->argv[argc-1]=str; - child->argv_nonnull[argc-1] = dest->nonnull; - child->argv[argc]=NULL; - child->argv_nonnull[argc] = 0; - for (s = dest->data; s && *s; s++,str++) { - if (*s == '\\') s++; - *str = *s; - } - *str = '\0'; -#endif -#ifndef __U_BOOT__ - } - gr = xglob(dest, flags, glob_target); - if (gr != 0) return 1; -#endif - - b_reset(dest); -#ifndef __U_BOOT__ - if (ctx->pending_redirect) { - ctx->pending_redirect=NULL; - if (glob_target->gl_pathc != 1) { - error_msg("ambiguous redirect"); - return 1; - } - } else { - child->argv = glob_target->gl_pathv; - } -#endif - if (ctx->w == RES_FOR) { - done_word(dest,ctx); - done_pipe(ctx,PIPE_SEQ); - } - return 0; -} - -/* The only possible error here is out of memory, in which case - * xmalloc exits. */ -static int done_command(struct p_context *ctx) -{ - /* The child is really already in the pipe structure, so - * advance the pipe counter and make a new, null child. - * Only real trickiness here is that the uncommitted - * child structure, to which ctx->child points, is not - * counted in pi->num_progs. */ - struct pipe *pi=ctx->pipe; - struct child_prog *prog=ctx->child; - - if (prog && prog->group == NULL - && prog->argv == NULL -#ifndef __U_BOOT__ - && prog->redirects == NULL) { -#else - ) { -#endif - debug_printf("done_command: skipping null command\n"); - return 0; - } else if (prog) { - pi->num_progs++; - debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs); - } else { - debug_printf("done_command: initializing\n"); - } - pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1)); - - prog = pi->progs + pi->num_progs; -#ifndef __U_BOOT__ - prog->redirects = NULL; -#endif - prog->argv = NULL; - prog->argv_nonnull = NULL; -#ifndef __U_BOOT__ - prog->is_stopped = 0; -#endif - prog->group = NULL; -#ifndef __U_BOOT__ - prog->glob_result.gl_pathv = NULL; - prog->family = pi; -#endif - prog->sp = 0; - ctx->child = prog; - prog->type = ctx->type; - - /* but ctx->pipe and ctx->list_head remain unchanged */ - return 0; -} - -static int done_pipe(struct p_context *ctx, pipe_style type) -{ - struct pipe *new_p; - done_command(ctx); /* implicit closure of previous command */ - debug_printf("done_pipe, type %d\n", type); - ctx->pipe->followup = type; - ctx->pipe->r_mode = ctx->w; - new_p=new_pipe(); - ctx->pipe->next = new_p; - ctx->pipe = new_p; - ctx->child = NULL; - done_command(ctx); /* set up new pipe to accept commands */ - return 0; -} - -#ifndef __U_BOOT__ -/* peek ahead in the in_str to find out if we have a "&n" construct, - * as in "2>&1", that represents duplicating a file descriptor. - * returns either -2 (syntax error), -1 (no &), or the number found. - */ -static int redirect_dup_num(struct in_str *input) -{ - int ch, d=0, ok=0; - ch = b_peek(input); - if (ch != '&') return -1; - - b_getch(input); /* get the & */ - ch=b_peek(input); - if (ch == '-') { - b_getch(input); - return -3; /* "-" represents "close me" */ - } - while (isdigit(ch)) { - d = d*10+(ch-'0'); - ok=1; - b_getch(input); - ch = b_peek(input); - } - if (ok) return d; - - error_msg("ambiguous redirect"); - return -2; -} - -/* If a redirect is immediately preceded by a number, that number is - * supposed to tell which file descriptor to redirect. This routine - * looks for such preceding numbers. In an ideal world this routine - * needs to handle all the following classes of redirects... - * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo - * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo - * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo - * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo - * A -1 output from this program means no valid number was found, so the - * caller should use the appropriate default for this redirection. - */ -static int redirect_opt_num(o_string *o) -{ - int num; - - if (o->length==0) return -1; - for(num=0; numlength; num++) { - if (!isdigit(*(o->data+num))) { - return -1; - } - } - /* reuse num (and save an int) */ - num=atoi(o->data); - b_reset(o); - return num; -} - -FILE *generate_stream_from_list(struct pipe *head) -{ - FILE *pf; -#if 1 - int pid, channel[2]; - if (pipe(channel)<0) perror_msg_and_die("pipe"); - pid=fork(); - if (pid<0) { - perror_msg_and_die("fork"); - } else if (pid==0) { - close(channel[0]); - if (channel[1] != 1) { - dup2(channel[1],1); - close(channel[1]); - } -#if 0 -#define SURROGATE "surrogate response" - write(1,SURROGATE,sizeof(SURROGATE)); - _exit(run_list(head)); -#else - _exit(run_list_real(head)); /* leaks memory */ -#endif - } - debug_printf("forked child %d\n",pid); - close(channel[1]); - pf = fdopen(channel[0],"r"); - debug_printf("pipe on FILE *%p\n",pf); -#else - free_pipe_list(head,0); - pf=popen("echo surrogate response","r"); - debug_printf("started fake pipe on FILE *%p\n",pf); -#endif - return pf; -} - -/* this version hacked for testing purposes */ -/* return code is exit status of the process that is run. */ -static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end) -{ - int retcode; - o_string result=NULL_O_STRING; - struct p_context inner; - FILE *p; - struct in_str pipe_str; - initialize_context(&inner); - - /* recursion to generate command */ - retcode = parse_stream(&result, &inner, input, subst_end); - if (retcode != 0) return retcode; /* syntax error or EOF */ - done_word(&result, &inner); - done_pipe(&inner, PIPE_SEQ); - b_free(&result); - - p=generate_stream_from_list(inner.list_head); - if (p==NULL) return 1; - mark_open(fileno(p)); - setup_file_in_str(&pipe_str, p); - - /* now send results of command back into original context */ - retcode = parse_stream(dest, ctx, &pipe_str, '\0'); - /* XXX In case of a syntax error, should we try to kill the child? - * That would be tough to do right, so just read until EOF. */ - if (retcode == 1) { - while (b_getch(&pipe_str)!=EOF) { /* discard */ }; - } - - debug_printf("done reading from pipe, pclose()ing\n"); - /* This is the step that wait()s for the child. Should be pretty - * safe, since we just read an EOF from its stdout. We could try - * to better, by using wait(), and keeping track of background jobs - * at the same time. That would be a lot of work, and contrary - * to the KISS philosophy of this program. */ - mark_closed(fileno(p)); - retcode=pclose(p); - free_pipe_list(inner.list_head,0); - debug_printf("pclosed, retcode=%d\n",retcode); - /* XXX this process fails to trim a single trailing newline */ - return retcode; -} - -static int parse_group(o_string *dest, struct p_context *ctx, - struct in_str *input, int ch) -{ - int rcode, endch=0; - struct p_context sub; - struct child_prog *child = ctx->child; - if (child->argv) { - syntax(); - return 1; /* syntax error, groups and arglists don't mix */ - } - initialize_context(&sub); - switch(ch) { - case '(': endch=')'; child->subshell=1; break; - case '{': endch='}'; break; - default: syntax(); /* really logic error */ - } - rcode=parse_stream(dest,&sub,input,endch); - done_word(dest,&sub); /* finish off the final word in the subcontext */ - done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */ - child->group = sub.list_head; - return rcode; - /* child remains "open", available for possible redirects */ -} -#endif - -/* basically useful version until someone wants to get fancier, - * see the bash man page under "Parameter Expansion" */ -static char *lookup_param(char *src) -{ - char *p; - char *sep; - char *default_val = NULL; - int assign = 0; - int expand_empty = 0; - - if (!src) - return NULL; - - sep = strchr(src, ':'); - - if (sep) { - *sep = '\0'; - if (*(sep + 1) == '-') - default_val = sep+2; - if (*(sep + 1) == '=') { - default_val = sep+2; - assign = 1; - } - if (*(sep + 1) == '+') { - default_val = sep+2; - expand_empty = 1; - } - } - - p = getenv(src); - if (!p) - p = get_local_var(src); - - if (!p || strlen(p) == 0) { - p = default_val; - if (assign) { - char *var = malloc(strlen(src)+strlen(default_val)+2); - if (var) { - sprintf(var, "%s=%s", src, default_val); - set_local_var(var, 0); - } - free(var); - } - } else if (expand_empty) { - p += strlen(p); - } - - if (sep) - *sep = ':'; - - return p; -} - -#ifdef __U_BOOT__ -static char *get_dollar_var(char ch) -{ - static char buf[40]; - - buf[0] = '\0'; - switch (ch) { - case '?': - sprintf(buf, "%u", (unsigned int)last_return_code); - break; - default: - return NULL; - } - return buf; -} -#endif - -/* return code: 0 for OK, 1 for syntax error */ -static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input) -{ -#ifndef __U_BOOT__ - int i, advance=0; -#else - int advance=0; -#endif -#ifndef __U_BOOT__ - char sep[]=" "; -#endif - int ch = input->peek(input); /* first character after the $ */ - debug_printf("handle_dollar: ch=%c\n",ch); - if (isalpha(ch)) { - b_addchr(dest, SPECIAL_VAR_SYMBOL); - ctx->child->sp++; - while(ch=b_peek(input),isalnum(ch) || ch=='_') { - b_getch(input); - b_addchr(dest,ch); - } - b_addchr(dest, SPECIAL_VAR_SYMBOL); -#ifndef __U_BOOT__ - } else if (isdigit(ch)) { - i = ch-'0'; /* XXX is $0 special? */ - if (i 0) b_adduint(dest, last_bg_pid); - advance = 1; - break; -#endif - case '?': -#ifndef __U_BOOT__ - b_adduint(dest,last_return_code); -#else - ctx->child->sp++; - b_addchr(dest, SPECIAL_VAR_SYMBOL); - b_addchr(dest, '$'); - b_addchr(dest, '?'); - b_addchr(dest, SPECIAL_VAR_SYMBOL); -#endif - advance = 1; - break; -#ifndef __U_BOOT__ - case '#': - b_adduint(dest,global_argc ? global_argc-1 : 0); - advance = 1; - break; -#endif - case '{': - b_addchr(dest, SPECIAL_VAR_SYMBOL); - ctx->child->sp++; - b_getch(input); - /* XXX maybe someone will try to escape the '}' */ - while(ch=b_getch(input),ch!=EOF && ch!='}') { - b_addchr(dest,ch); - } - if (ch != '}') { - syntax(); - return 1; - } - b_addchr(dest, SPECIAL_VAR_SYMBOL); - break; -#ifndef __U_BOOT__ - case '(': - b_getch(input); - process_command_subs(dest, ctx, input, ')'); - break; - case '*': - sep[0]=ifs[0]; - for (i=1; iquote); - } - /* Eat the character if the flag was set. If the compiler - * is smart enough, we could substitute "b_getch(input);" - * for all the "advance = 1;" above, and also end up with - * a nice size-optimized program. Hah! That'll be the day. - */ - if (advance) b_getch(input); - return 0; -} - -#ifndef __U_BOOT__ -int parse_string(o_string *dest, struct p_context *ctx, const char *src) -{ - struct in_str foo; - setup_string_in_str(&foo, src); - return parse_stream(dest, ctx, &foo, '\0'); -} -#endif - -/* return code is 0 for normal exit, 1 for syntax error */ -static int parse_stream(o_string *dest, struct p_context *ctx, - struct in_str *input, int end_trigger) -{ - unsigned int ch, m; -#ifndef __U_BOOT__ - int redir_fd; - redir_type redir_style; -#endif - int next; - - /* Only double-quote state is handled in the state variable dest->quote. - * A single-quote triggers a bypass of the main loop until its mate is - * found. When recursing, quote state is passed in via dest->quote. */ - - debug_printf("parse_stream, end_trigger=%d\n",end_trigger); - while ((ch=b_getch(input))!=EOF) { - m = map[ch]; -#ifdef __U_BOOT__ - if (input->__promptme == 0) return 1; -#endif - next = (ch == '\n') ? 0 : b_peek(input); - - debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n", - ch >= ' ' ? ch : '.', ch, m, - dest->quote, ctx->stack == NULL ? '*' : '.'); - - if (m==0 || ((m==1 || m==2) && dest->quote)) { - b_addqchr(dest, ch, dest->quote); - } else { - if (m==2) { /* unquoted IFS */ - if (done_word(dest, ctx)) { - return 1; - } - /* If we aren't performing a substitution, treat a newline as a - * command separator. */ - if (end_trigger != '\0' && ch=='\n') - done_pipe(ctx,PIPE_SEQ); - } - if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) { - debug_printf("leaving parse_stream (triggered)\n"); - return 0; - } -#if 0 - if (ch=='\n') { - /* Yahoo! Time to run with it! */ - done_pipe(ctx,PIPE_SEQ); - run_list(ctx->list_head); - initialize_context(ctx); - } -#endif - if (m!=2) switch (ch) { - case '#': - if (dest->length == 0 && !dest->quote) { - while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); } - } else { - b_addqchr(dest, ch, dest->quote); - } - break; - case '\\': - if (next == EOF) { - syntax(); - return 1; - } - b_addqchr(dest, '\\', dest->quote); - b_addqchr(dest, b_getch(input), dest->quote); - break; - case '$': - if (handle_dollar(dest, ctx, input)!=0) return 1; - break; - case '\'': - dest->nonnull = 1; - while(ch=b_getch(input),ch!=EOF && ch!='\'') { -#ifdef __U_BOOT__ - if(input->__promptme == 0) return 1; -#endif - b_addchr(dest,ch); - } - if (ch==EOF) { - syntax(); - return 1; - } - break; - case '"': - dest->nonnull = 1; - dest->quote = !dest->quote; - break; -#ifndef __U_BOOT__ - case '`': - process_command_subs(dest, ctx, input, '`'); - break; - case '>': - redir_fd = redirect_opt_num(dest); - done_word(dest, ctx); - redir_style=REDIRECT_OVERWRITE; - if (next == '>') { - redir_style=REDIRECT_APPEND; - b_getch(input); - } else if (next == '(') { - syntax(); /* until we support >(list) Process Substitution */ - return 1; - } - setup_redirect(ctx, redir_fd, redir_style, input); - break; - case '<': - redir_fd = redirect_opt_num(dest); - done_word(dest, ctx); - redir_style=REDIRECT_INPUT; - if (next == '<') { - redir_style=REDIRECT_HEREIS; - b_getch(input); - } else if (next == '>') { - redir_style=REDIRECT_IO; - b_getch(input); - } else if (next == '(') { - syntax(); /* until we support <(list) Process Substitution */ - return 1; - } - setup_redirect(ctx, redir_fd, redir_style, input); - break; -#endif - case ';': - done_word(dest, ctx); - done_pipe(ctx,PIPE_SEQ); - break; - case '&': - done_word(dest, ctx); - if (next=='&') { - b_getch(input); - done_pipe(ctx,PIPE_AND); - } else { -#ifndef __U_BOOT__ - done_pipe(ctx,PIPE_BG); -#else - syntax_err(); - return 1; -#endif - } - break; - case '|': - done_word(dest, ctx); - if (next=='|') { - b_getch(input); - done_pipe(ctx,PIPE_OR); - } else { - /* we could pick up a file descriptor choice here - * with redirect_opt_num(), but bash doesn't do it. - * "echo foo 2| cat" yields "foo 2". */ -#ifndef __U_BOOT__ - done_command(ctx); -#else - syntax_err(); - return 1; -#endif - } - break; -#ifndef __U_BOOT__ - case '(': - case '{': - if (parse_group(dest, ctx, input, ch)!=0) return 1; - break; - case ')': - case '}': - syntax(); /* Proper use of this character caught by end_trigger */ - return 1; - break; -#endif - case SUBSTED_VAR_SYMBOL: - dest->nonnull = 1; - while (ch = b_getch(input), ch != EOF && - ch != SUBSTED_VAR_SYMBOL) { - debug_printf("subst, pass=%d\n", ch); - if (input->__promptme == 0) - return 1; - b_addchr(dest, ch); - } - debug_printf("subst, term=%d\n", ch); - if (ch == EOF) { - syntax(); - return 1; - } - break; - default: - syntax(); /* this is really an internal logic error */ - return 1; - } - } - } - /* complain if quote? No, maybe we just finished a command substitution - * that was quoted. Example: - * $ echo "`cat foo` plus more" - * and we just got the EOF generated by the subshell that ran "cat foo" - * The only real complaint is if we got an EOF when end_trigger != '\0', - * that is, we were really supposed to get end_trigger, and never got - * one before the EOF. Can't use the standard "syntax error" return code, - * so that parse_stream_outer can distinguish the EOF and exit smoothly. */ - debug_printf("leaving parse_stream (EOF)\n"); - if (end_trigger != '\0') return -1; - return 0; -} - -static void mapset(const unsigned char *set, int code) -{ - const unsigned char *s; - for (s=set; *s; s++) map[*s] = code; -} - -static void update_ifs_map(void) -{ - /* char *ifs and char map[256] are both globals. */ - ifs = (uchar *)getenv("IFS"); - if (ifs == NULL) ifs=(uchar *)" \t\n"; - /* Precompute a list of 'flow through' behavior so it can be treated - * quickly up front. Computation is necessary because of IFS. - * Special case handling of IFS == " \t\n" is not implemented. - * The map[] array only really needs two bits each, and on most machines - * that would be faster because of the reduced L1 cache footprint. - */ - memset(map,0,sizeof(map)); /* most characters flow through always */ -#ifndef __U_BOOT__ - mapset((uchar *)"\\$'\"`", 3); /* never flow through */ - mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */ -#else - { - uchar subst[2] = {SUBSTED_VAR_SYMBOL, 0}; - mapset(subst, 3); /* never flow through */ - } - mapset((uchar *)"\\$'\"", 3); /* never flow through */ - mapset((uchar *)";&|#", 1); /* flow through if quoted */ -#endif - mapset(ifs, 2); /* also flow through if quoted */ -} - -/* most recursion does not come through here, the exeception is - * from builtin_source() */ -static int parse_stream_outer(struct in_str *inp, int flag) -{ - - struct p_context ctx; - o_string temp=NULL_O_STRING; - int rcode; -#ifdef __U_BOOT__ - int code = 0; -#endif - do { - ctx.type = flag; - initialize_context(&ctx); - update_ifs_map(); - if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0); - inp->promptmode=1; - rcode = parse_stream(&temp, &ctx, inp, '\n'); -#ifdef __U_BOOT__ - if (rcode == 1) flag_repeat = 0; -#endif - if (rcode != 1 && ctx.old_flag != 0) { - syntax(); -#ifdef __U_BOOT__ - flag_repeat = 0; -#endif - } - if (rcode != 1 && ctx.old_flag == 0) { - done_word(&temp, &ctx); - done_pipe(&ctx,PIPE_SEQ); -#ifndef __U_BOOT__ - run_list(ctx.list_head); -#else - code = run_list(ctx.list_head); - if (code == -2) { /* exit */ - b_free(&temp); - code = 0; - /* XXX hackish way to not allow exit from main loop */ - if (inp->peek == file_peek) { - printf("exit not allowed from main input shell.\n"); - continue; - } - break; - } - if (code == -1) - flag_repeat = 0; -#endif - } else { - if (ctx.old_flag != 0) { - free(ctx.stack); - b_reset(&temp); - } -#ifdef __U_BOOT__ - if (inp->__promptme == 0) printf("\n"); - inp->__promptme = 1; -#endif - temp.nonnull = 0; - temp.quote = 0; - inp->p = NULL; - free_pipe_list(ctx.list_head,0); - } - b_free(&temp); - } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */ -#ifndef __U_BOOT__ - return 0; -#else - return (code != 0) ? 1 : 0; -#endif /* __U_BOOT__ */ -} - -#ifndef __U_BOOT__ -static int parse_string_outer(const char *s, int flag) -#else -int parse_string_outer(const char *s, int flag) -#endif /* __U_BOOT__ */ -{ - struct in_str input; -#ifdef __U_BOOT__ - char *p = NULL; - int rcode; - if ( !s || !*s) - return 1; - if (!(p = strchr(s, '\n')) || *++p) { - p = xmalloc(strlen(s) + 2); - strcpy(p, s); - strcat(p, "\n"); - setup_string_in_str(&input, p); - rcode = parse_stream_outer(&input, flag); - free(p); - return rcode; - } else { -#endif - setup_string_in_str(&input, s); - return parse_stream_outer(&input, flag); -#ifdef __U_BOOT__ - } -#endif -} - -#ifndef __U_BOOT__ -static int parse_file_outer(FILE *f) -#else -int parse_file_outer(void) -#endif -{ - int rcode; - struct in_str input; -#ifndef __U_BOOT__ - setup_file_in_str(&input, f); -#else - setup_file_in_str(&input); -#endif - rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON); - return rcode; -} - -#ifdef __U_BOOT__ -#ifdef CONFIG_NEEDS_MANUAL_RELOC -static void u_boot_hush_reloc(void) -{ - unsigned long addr; - struct reserved_combo *r; - - for (r=reserved_list; rliteral) + gd->reloc_off; - r->literal = (char *)addr; - } -} -#endif - -int u_boot_hush_start(void) -{ - if (top_vars == NULL) { - top_vars = malloc(sizeof(struct variables)); - top_vars->name = "HUSH_VERSION"; - top_vars->value = "0.01"; - top_vars->next = NULL; - top_vars->flg_export = 0; - top_vars->flg_read_only = 1; -#ifdef CONFIG_NEEDS_MANUAL_RELOC - u_boot_hush_reloc(); -#endif - } - return 0; -} - -static void *xmalloc(size_t size) -{ - void *p = NULL; - - if (!(p = malloc(size))) { - printf("ERROR : memory not allocated\n"); - for(;;); - } - return p; -} - -static void *xrealloc(void *ptr, size_t size) -{ - void *p = NULL; - - if (!(p = realloc(ptr, size))) { - printf("ERROR : memory not allocated\n"); - for(;;); - } - return p; -} -#endif /* __U_BOOT__ */ - -#ifndef __U_BOOT__ -/* Make sure we have a controlling tty. If we get started under a job - * aware app (like bash for example), make sure we are now in charge so - * we don't fight over who gets the foreground */ -static void setup_job_control(void) -{ - static pid_t shell_pgrp; - /* Loop until we are in the foreground. */ - while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ())) - kill (- shell_pgrp, SIGTTIN); - - /* Ignore interactive and job-control signals. */ - signal(SIGINT, SIG_IGN); - signal(SIGQUIT, SIG_IGN); - signal(SIGTERM, SIG_IGN); - signal(SIGTSTP, SIG_IGN); - signal(SIGTTIN, SIG_IGN); - signal(SIGTTOU, SIG_IGN); - signal(SIGCHLD, SIG_IGN); - - /* Put ourselves in our own process group. */ - setsid(); - shell_pgrp = getpid (); - setpgid (shell_pgrp, shell_pgrp); - - /* Grab control of the terminal. */ - tcsetpgrp(shell_terminal, shell_pgrp); -} - -int hush_main(int argc, char * const *argv) -{ - int opt; - FILE *input; - char **e = environ; - - /* XXX what should these be while sourcing /etc/profile? */ - global_argc = argc; - global_argv = argv; - - /* (re?) initialize globals. Sometimes hush_main() ends up calling - * hush_main(), therefore we cannot rely on the BSS to zero out this - * stuff. Reset these to 0 every time. */ - ifs = NULL; - /* map[] is taken care of with call to update_ifs_map() */ - fake_mode = 0; - interactive = 0; - close_me_head = NULL; - last_bg_pid = 0; - job_list = NULL; - last_jobid = 0; - - /* Initialize some more globals to non-zero values */ - set_cwd(); -#ifdef CONFIG_FEATURE_COMMAND_EDITING - cmdedit_set_initial_prompt(); -#else - PS1 = NULL; -#endif - PS2 = "> "; - - /* initialize our shell local variables with the values - * currently living in the environment */ - if (e) { - for (; *e; e++) - set_local_var(*e, 2); /* without call putenv() */ - } - - last_return_code=EXIT_SUCCESS; - - - if (argv[0] && argv[0][0] == '-') { - debug_printf("\nsourcing /etc/profile\n"); - if ((input = fopen("/etc/profile", "r")) != NULL) { - mark_open(fileno(input)); - parse_file_outer(input); - mark_closed(fileno(input)); - fclose(input); - } - } - input=stdin; - - while ((opt = getopt(argc, argv, "c:xif")) > 0) { - switch (opt) { - case 'c': - { - global_argv = argv+optind; - global_argc = argc-optind; - opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON); - goto final_return; - } - break; - case 'i': - interactive++; - break; - case 'f': - fake_mode++; - break; - default: -#ifndef BB_VER - fprintf(stderr, "Usage: sh [FILE]...\n" - " or: sh -c command [args]...\n\n"); - exit(EXIT_FAILURE); -#else - show_usage(); -#endif - } - } - /* A shell is interactive if the `-i' flag was given, or if all of - * the following conditions are met: - * no -c command - * no arguments remaining or the -s flag given - * standard input is a terminal - * standard output is a terminal - * Refer to Posix.2, the description of the `sh' utility. */ - if (argv[optind]==NULL && input==stdin && - isatty(fileno(stdin)) && isatty(fileno(stdout))) { - interactive++; - } - - debug_printf("\ninteractive=%d\n", interactive); - if (interactive) { - /* Looks like they want an interactive shell */ -#ifndef CONFIG_FEATURE_SH_EXTRA_QUIET - printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n"); - printf( "Enter 'help' for a list of built-in commands.\n\n"); -#endif - setup_job_control(); - } - - if (argv[optind]==NULL) { - opt=parse_file_outer(stdin); - goto final_return; - } - - debug_printf("\nrunning script '%s'\n", argv[optind]); - global_argv = argv+optind; - global_argc = argc-optind; - input = xfopen(argv[optind], "r"); - opt = parse_file_outer(input); - -#ifdef CONFIG_FEATURE_CLEAN_UP - fclose(input); - if (cwd && cwd != unknown) - free((char*)cwd); - { - struct variables *cur, *tmp; - for(cur = top_vars; cur; cur = tmp) { - tmp = cur->next; - if (!cur->flg_read_only) { - free(cur->name); - free(cur->value); - free(cur); - } - } - } -#endif - -final_return: - return(opt?opt:last_return_code); -} -#endif - -static char *insert_var_value(char *inp) -{ - return insert_var_value_sub(inp, 0); -} - -static char *insert_var_value_sub(char *inp, int tag_subst) -{ - int res_str_len = 0; - int len; - int done = 0; - char *p, *p1, *res_str = NULL; - - while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) { - /* check the beginning of the string for normal charachters */ - if (p != inp) { - /* copy any charachters to the result string */ - len = p - inp; - res_str = xrealloc(res_str, (res_str_len + len)); - strncpy((res_str + res_str_len), inp, len); - res_str_len += len; - } - inp = ++p; - /* find the ending marker */ - p = strchr(inp, SPECIAL_VAR_SYMBOL); - *p = '\0'; - /* look up the value to substitute */ - if ((p1 = lookup_param(inp))) { - if (tag_subst) - len = res_str_len + strlen(p1) + 2; - else - len = res_str_len + strlen(p1); - res_str = xrealloc(res_str, (1 + len)); - if (tag_subst) { - /* - * copy the variable value to the result - * string - */ - strcpy((res_str + res_str_len + 1), p1); - - /* - * mark the replaced text to be accepted as - * is - */ - res_str[res_str_len] = SUBSTED_VAR_SYMBOL; - res_str[res_str_len + 1 + strlen(p1)] = - SUBSTED_VAR_SYMBOL; - } else - /* - * copy the variable value to the result - * string - */ - strcpy((res_str + res_str_len), p1); - - res_str_len = len; - } - *p = SPECIAL_VAR_SYMBOL; - inp = ++p; - done = 1; - } - if (done) { - res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp))); - strcpy((res_str + res_str_len), inp); - while ((p = strchr(res_str, '\n'))) { - *p = ' '; - } - } - return (res_str == NULL) ? inp : res_str; -} - -static char **make_list_in(char **inp, char *name) -{ - int len, i; - int name_len = strlen(name); - int n = 0; - char **list; - char *p1, *p2, *p3; - - /* create list of variable values */ - list = xmalloc(sizeof(*list)); - for (i = 0; inp[i]; i++) { - p3 = insert_var_value(inp[i]); - p1 = p3; - while (*p1) { - if ((*p1 == ' ')) { - p1++; - continue; - } - if ((p2 = strchr(p1, ' '))) { - len = p2 - p1; - } else { - len = strlen(p1); - p2 = p1 + len; - } - /* we use n + 2 in realloc for list,because we add - * new element and then we will add NULL element */ - list = xrealloc(list, sizeof(*list) * (n + 2)); - list[n] = xmalloc(2 + name_len + len); - strcpy(list[n], name); - strcat(list[n], "="); - strncat(list[n], p1, len); - list[n++][name_len + len + 1] = '\0'; - p1 = p2; - } - if (p3 != inp[i]) free(p3); - } - list[n] = NULL; - return list; -} - -/* - * Make new string for parser - * inp - array of argument strings to flatten - * nonnull - indicates argument was quoted when originally parsed - */ -static char *make_string(char **inp, int *nonnull) -{ - char *p; - char *str = NULL; - int n; - int len = 2; - char *noeval_str; - int noeval = 0; - - noeval_str = get_local_var("HUSH_NO_EVAL"); - if (noeval_str != NULL && *noeval_str != '0' && *noeval_str != '\0') - noeval = 1; - for (n = 0; inp[n]; n++) { - p = insert_var_value_sub(inp[n], noeval); - str = xrealloc(str, (len + strlen(p) + (2 * nonnull[n]))); - if (n) { - strcat(str, " "); - } else { - *str = '\0'; - } - if (nonnull[n]) - strcat(str, "'"); - strcat(str, p); - if (nonnull[n]) - strcat(str, "'"); - len = strlen(str) + 3; - if (p != inp[n]) free(p); - } - len = strlen(str); - *(str + len) = '\n'; - *(str + len + 1) = '\0'; - return str; -} - -#ifdef __U_BOOT__ -static int do_showvar(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[]) -{ - int i, k; - int rcode = 0; - struct variables *cur; - - if (argc == 1) { /* Print all env variables */ - for (cur = top_vars; cur; cur = cur->next) { - printf ("%s=%s\n", cur->name, cur->value); - if (ctrlc ()) { - puts ("\n ** Abort\n"); - return 1; - } - } - return 0; - } - for (i = 1; i < argc; ++i) { /* print single env variables */ - char *name = argv[i]; - - k = -1; - for (cur = top_vars; cur; cur = cur->next) { - if(strcmp (cur->name, name) == 0) { - k = 0; - printf ("%s=%s\n", cur->name, cur->value); - } - if (ctrlc ()) { - puts ("\n ** Abort\n"); - return 1; - } - } - if (k < 0) { - printf ("## Error: \"%s\" not defined\n", name); - rcode ++; - } - } - return rcode; -} - -U_BOOT_CMD( - showvar, CONFIG_SYS_MAXARGS, 1, do_showvar, - "print local hushshell variables", - "\n - print values of all hushshell variables\n" - "showvar name ...\n" - " - print value of hushshell variable 'name'" -); - -#endif -/****************************************************************************/ diff --git a/common/main.c b/common/main.c index 9bee7bd..a80fb7c 100644 --- a/common/main.c +++ b/common/main.c @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include #include -- cgit v1.1 From 18d66533ac773f59efc93e5c19971fad5e6af82f Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:25 -0600 Subject: move CLI prototypes to cli.h and add comments Move the CLI prototypes from common.h to cli.h as part of an effort to reduce the size of common.h. Signed-off-by: Simon Glass --- common/cli_hush.c | 1 + common/cmd_bedbug.c | 1 + common/cmd_dcr.c | 1 + common/cmd_i2c.c | 1 + common/cmd_mem.c | 1 + common/cmd_nvedit.c | 1 + common/cmd_pci.c | 1 + common/main.c | 1 + common/menu.c | 1 + 9 files changed, 9 insertions(+) (limited to 'common') diff --git a/common/cli_hush.c b/common/cli_hush.c index 012004a..91e4956 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -79,6 +79,7 @@ #include /* malloc, free, realloc*/ #include /* isalpha, isdigit */ #include /* readline */ +#include #include #include /* find_cmd */ #ifndef CONFIG_SYS_PROMPT_HUSH_PS2 diff --git a/common/cmd_bedbug.c b/common/cmd_bedbug.c index 77b6e3e..f1a70ef 100644 --- a/common/cmd_bedbug.c +++ b/common/cmd_bedbug.c @@ -3,6 +3,7 @@ */ #include +#include #include #include #include diff --git a/common/cmd_dcr.c b/common/cmd_dcr.c index 896f79f..c5bcb8b 100644 --- a/common/cmd_dcr.c +++ b/common/cmd_dcr.c @@ -10,6 +10,7 @@ */ #include +#include #include #include diff --git a/common/cmd_i2c.c b/common/cmd_i2c.c index ebce7d4..8ccde68 100644 --- a/common/cmd_i2c.c +++ b/common/cmd_i2c.c @@ -66,6 +66,7 @@ */ #include +#include #include #include #include diff --git a/common/cmd_mem.c b/common/cmd_mem.c index 5b03c2d..4b8738b 100644 --- a/common/cmd_mem.c +++ b/common/cmd_mem.c @@ -12,6 +12,7 @@ */ #include +#include #include #ifdef CONFIG_HAS_DATAFLASH #include diff --git a/common/cmd_nvedit.c b/common/cmd_nvedit.c index f4e306c..a1e98c6 100644 --- a/common/cmd_nvedit.c +++ b/common/cmd_nvedit.c @@ -25,6 +25,7 @@ */ #include +#include #include #include #include diff --git a/common/cmd_pci.c b/common/cmd_pci.c index d3e7c08..ddda207 100644 --- a/common/cmd_pci.c +++ b/common/cmd_pci.c @@ -14,6 +14,7 @@ */ #include +#include #include #include #include diff --git a/common/main.c b/common/main.c index a80fb7c..6d1c3a9 100644 --- a/common/main.c +++ b/common/main.c @@ -12,6 +12,7 @@ /* #define DEBUG */ #include +#include #include #include #include diff --git a/common/menu.c b/common/menu.c index ba393ad..88d4697 100644 --- a/common/menu.c +++ b/common/menu.c @@ -5,6 +5,7 @@ */ #include +#include #include #include #include -- cgit v1.1 From 6493ccc7cf2357081267effffa7d345e50d68d00 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:26 -0600 Subject: Split out simple parser and readline into separate files It doesn't make sense to have the simple parser and the readline code all in main. Split them out into separate files. Signed-off-by: Simon Glass --- common/Makefile | 9 +- common/cli_readline.c | 670 ++++++++++++++++++++++++++++++++ common/cli_simple.c | 338 ++++++++++++++++ common/main.c | 1017 +------------------------------------------------ 4 files changed, 1021 insertions(+), 1013 deletions(-) create mode 100644 common/cli_readline.c create mode 100644 common/cli_simple.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index da184a8..7998325 100644 --- a/common/Makefile +++ b/common/Makefile @@ -11,7 +11,14 @@ obj-y += main.o obj-y += command.o obj-y += exports.o obj-y += hash.o -obj-$(CONFIG_SYS_HUSH_PARSER) += cli_hush.o +ifdef CONFIG_SYS_HUSH_PARSER +obj-y += cli_hush.o +endif + +# We always have this since drivers/ddr/fs/interactive.c needs it +obj-y += cli_simple.o + +obj-y += cli_readline.o obj-y += s_record.o obj-y += xyzModem.o obj-y += cmd_disk.o diff --git a/common/cli_readline.c b/common/cli_readline.c new file mode 100644 index 0000000..cea0b7c --- /dev/null +++ b/common/cli_readline.c @@ -0,0 +1,670 @@ +/* + * (C) Copyright 2000 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * Add to readline cmdline-editing by + * (C) Copyright 2005 + * JinHua Luo, GuangDong Linux Center, + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +static const char erase_seq[] = "\b \b"; /* erase sequence */ +static const char tab_seq[] = " "; /* used to expand TABs */ + +#ifdef CONFIG_BOOT_RETRY_TIME +static uint64_t endtime; /* must be set, default is instant timeout */ +static int retry_time = -1; /* -1 so can call readline before main_loop */ +#endif + +char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */ + +#ifndef CONFIG_BOOT_RETRY_MIN +#define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME +#endif + +static char *delete_char (char *buffer, char *p, int *colp, int *np, int plen) +{ + char *s; + + if (*np == 0) + return p; + + if (*(--p) == '\t') { /* will retype the whole line */ + while (*colp > plen) { + puts(erase_seq); + (*colp)--; + } + for (s = buffer; s < p; ++s) { + if (*s == '\t') { + puts(tab_seq + ((*colp) & 07)); + *colp += 8 - ((*colp) & 07); + } else { + ++(*colp); + putc(*s); + } + } + } else { + puts(erase_seq); + (*colp)--; + } + (*np)--; + + return p; +} + +#ifdef CONFIG_CMDLINE_EDITING + +/* + * cmdline-editing related codes from vivi. + * Author: Janghoon Lyu + */ + +#define putnstr(str, n) printf("%.*s", (int)n, str) + +#define CTL_CH(c) ((c) - 'a' + 1) +#define CTL_BACKSPACE ('\b') +#define DEL ((char)255) +#define DEL7 ((char)127) +#define CREAD_HIST_CHAR ('!') + +#define getcmd_putch(ch) putc(ch) +#define getcmd_getch() getc() +#define getcmd_cbeep() getcmd_putch('\a') + +#define HIST_MAX 20 +#define HIST_SIZE CONFIG_SYS_CBSIZE + +static int hist_max; +static int hist_add_idx; +static int hist_cur = -1; +static unsigned hist_num; + +static char *hist_list[HIST_MAX]; +static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */ + +#define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1) + +static void hist_init(void) +{ + int i; + + hist_max = 0; + hist_add_idx = 0; + hist_cur = -1; + hist_num = 0; + + for (i = 0; i < HIST_MAX; i++) { + hist_list[i] = hist_lines[i]; + hist_list[i][0] = '\0'; + } +} + +static void cread_add_to_hist(char *line) +{ + strcpy(hist_list[hist_add_idx], line); + + if (++hist_add_idx >= HIST_MAX) + hist_add_idx = 0; + + if (hist_add_idx > hist_max) + hist_max = hist_add_idx; + + hist_num++; +} + +static char *hist_prev(void) +{ + char *ret; + int old_cur; + + if (hist_cur < 0) + return NULL; + + old_cur = hist_cur; + if (--hist_cur < 0) + hist_cur = hist_max; + + if (hist_cur == hist_add_idx) { + hist_cur = old_cur; + ret = NULL; + } else { + ret = hist_list[hist_cur]; + } + + return ret; +} + +static char *hist_next(void) +{ + char *ret; + + if (hist_cur < 0) + return NULL; + + if (hist_cur == hist_add_idx) + return NULL; + + if (++hist_cur > hist_max) + hist_cur = 0; + + if (hist_cur == hist_add_idx) + ret = ""; + else + ret = hist_list[hist_cur]; + + return ret; +} + +#ifndef CONFIG_CMDLINE_EDITING +static void cread_print_hist_list(void) +{ + int i; + unsigned long n; + + n = hist_num - hist_max; + + i = hist_add_idx + 1; + while (1) { + if (i > hist_max) + i = 0; + if (i == hist_add_idx) + break; + printf("%s\n", hist_list[i]); + n++; + i++; + } +} +#endif /* CONFIG_CMDLINE_EDITING */ + +#define BEGINNING_OF_LINE() { \ + while (num) { \ + getcmd_putch(CTL_BACKSPACE); \ + num--; \ + } \ +} + +#define ERASE_TO_EOL() { \ + if (num < eol_num) { \ + printf("%*s", (int)(eol_num - num), ""); \ + do { \ + getcmd_putch(CTL_BACKSPACE); \ + } while (--eol_num > num); \ + } \ +} + +#define REFRESH_TO_EOL() { \ + if (num < eol_num) { \ + wlen = eol_num - num; \ + putnstr(buf + num, wlen); \ + num = eol_num; \ + } \ +} + +static void cread_add_char(char ichar, int insert, unsigned long *num, + unsigned long *eol_num, char *buf, unsigned long len) +{ + unsigned long wlen; + + /* room ??? */ + if (insert || *num == *eol_num) { + if (*eol_num > len - 1) { + getcmd_cbeep(); + return; + } + (*eol_num)++; + } + + if (insert) { + wlen = *eol_num - *num; + if (wlen > 1) + memmove(&buf[*num+1], &buf[*num], wlen-1); + + buf[*num] = ichar; + putnstr(buf + *num, wlen); + (*num)++; + while (--wlen) + getcmd_putch(CTL_BACKSPACE); + } else { + /* echo the character */ + wlen = 1; + buf[*num] = ichar; + putnstr(buf + *num, wlen); + (*num)++; + } +} + +static void cread_add_str(char *str, int strsize, int insert, + unsigned long *num, unsigned long *eol_num, + char *buf, unsigned long len) +{ + while (strsize--) { + cread_add_char(*str, insert, num, eol_num, buf, len); + str++; + } +} + +static int cread_line(const char *const prompt, char *buf, unsigned int *len, + int timeout) +{ + unsigned long num = 0; + unsigned long eol_num = 0; + unsigned long wlen; + char ichar; + int insert = 1; + int esc_len = 0; + char esc_save[8]; + int init_len = strlen(buf); + int first = 1; + + if (init_len) + cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len); + + while (1) { +#ifdef CONFIG_BOOT_RETRY_TIME + while (!tstc()) { /* while no incoming data */ + if (retry_time >= 0 && get_ticks() > endtime) + return -2; /* timed out */ + WATCHDOG_RESET(); + } +#endif + if (first && timeout) { + uint64_t etime = endtick(timeout); + + while (!tstc()) { /* while no incoming data */ + if (get_ticks() >= etime) + return -2; /* timed out */ + WATCHDOG_RESET(); + } + first = 0; + } + + ichar = getcmd_getch(); + + if ((ichar == '\n') || (ichar == '\r')) { + putc('\n'); + break; + } + + /* + * handle standard linux xterm esc sequences for arrow key, etc. + */ + if (esc_len != 0) { + if (esc_len == 1) { + if (ichar == '[') { + esc_save[esc_len] = ichar; + esc_len = 2; + } else { + cread_add_str(esc_save, esc_len, + insert, &num, &eol_num, + buf, *len); + esc_len = 0; + } + continue; + } + + switch (ichar) { + case 'D': /* <- key */ + ichar = CTL_CH('b'); + esc_len = 0; + break; + case 'C': /* -> key */ + ichar = CTL_CH('f'); + esc_len = 0; + break; /* pass off to ^F handler */ + case 'H': /* Home key */ + ichar = CTL_CH('a'); + esc_len = 0; + break; /* pass off to ^A handler */ + case 'A': /* up arrow */ + ichar = CTL_CH('p'); + esc_len = 0; + break; /* pass off to ^P handler */ + case 'B': /* down arrow */ + ichar = CTL_CH('n'); + esc_len = 0; + break; /* pass off to ^N handler */ + default: + esc_save[esc_len++] = ichar; + cread_add_str(esc_save, esc_len, insert, + &num, &eol_num, buf, *len); + esc_len = 0; + continue; + } + } + + switch (ichar) { + case 0x1b: + if (esc_len == 0) { + esc_save[esc_len] = ichar; + esc_len = 1; + } else { + puts("impossible condition #876\n"); + esc_len = 0; + } + break; + + case CTL_CH('a'): + BEGINNING_OF_LINE(); + break; + case CTL_CH('c'): /* ^C - break */ + *buf = '\0'; /* discard input */ + return -1; + case CTL_CH('f'): + if (num < eol_num) { + getcmd_putch(buf[num]); + num++; + } + break; + case CTL_CH('b'): + if (num) { + getcmd_putch(CTL_BACKSPACE); + num--; + } + break; + case CTL_CH('d'): + if (num < eol_num) { + wlen = eol_num - num - 1; + if (wlen) { + memmove(&buf[num], &buf[num+1], wlen); + putnstr(buf + num, wlen); + } + + getcmd_putch(' '); + do { + getcmd_putch(CTL_BACKSPACE); + } while (wlen--); + eol_num--; + } + break; + case CTL_CH('k'): + ERASE_TO_EOL(); + break; + case CTL_CH('e'): + REFRESH_TO_EOL(); + break; + case CTL_CH('o'): + insert = !insert; + break; + case CTL_CH('x'): + case CTL_CH('u'): + BEGINNING_OF_LINE(); + ERASE_TO_EOL(); + break; + case DEL: + case DEL7: + case 8: + if (num) { + wlen = eol_num - num; + num--; + memmove(&buf[num], &buf[num+1], wlen); + getcmd_putch(CTL_BACKSPACE); + putnstr(buf + num, wlen); + getcmd_putch(' '); + do { + getcmd_putch(CTL_BACKSPACE); + } while (wlen--); + eol_num--; + } + break; + case CTL_CH('p'): + case CTL_CH('n'): + { + char *hline; + + esc_len = 0; + + if (ichar == CTL_CH('p')) + hline = hist_prev(); + else + hline = hist_next(); + + if (!hline) { + getcmd_cbeep(); + continue; + } + + /* nuke the current line */ + /* first, go home */ + BEGINNING_OF_LINE(); + + /* erase to end of line */ + ERASE_TO_EOL(); + + /* copy new line into place and display */ + strcpy(buf, hline); + eol_num = strlen(buf); + REFRESH_TO_EOL(); + continue; + } +#ifdef CONFIG_AUTO_COMPLETE + case '\t': { + int num2, col; + + /* do not autocomplete when in the middle */ + if (num < eol_num) { + getcmd_cbeep(); + break; + } + + buf[num] = '\0'; + col = strlen(prompt) + eol_num; + num2 = num; + if (cmd_auto_complete(prompt, buf, &num2, &col)) { + col = num2 - num; + num += col; + eol_num += col; + } + break; + } +#endif + default: + cread_add_char(ichar, insert, &num, &eol_num, buf, + *len); + break; + } + } + *len = eol_num; + buf[eol_num] = '\0'; /* lose the newline */ + + if (buf[0] && buf[0] != CREAD_HIST_CHAR) + cread_add_to_hist(buf); + hist_cur = hist_add_idx; + + return 0; +} + +#endif /* CONFIG_CMDLINE_EDITING */ + +/****************************************************************************/ + +int readline(const char *const prompt) +{ + /* + * If console_buffer isn't 0-length the user will be prompted to modify + * it instead of entering it from scratch as desired. + */ + console_buffer[0] = '\0'; + + return readline_into_buffer(prompt, console_buffer, 0); +} + + +int readline_into_buffer(const char *const prompt, char *buffer, int timeout) +{ + char *p = buffer; +#ifdef CONFIG_CMDLINE_EDITING + unsigned int len = CONFIG_SYS_CBSIZE; + int rc; + static int initted; + + /* + * History uses a global array which is not + * writable until after relocation to RAM. + * Revert to non-history version if still + * running from flash. + */ + if (gd->flags & GD_FLG_RELOC) { + if (!initted) { + hist_init(); + initted = 1; + } + + if (prompt) + puts(prompt); + + rc = cread_line(prompt, p, &len, timeout); + return rc < 0 ? rc : len; + + } else { +#endif /* CONFIG_CMDLINE_EDITING */ + char *p_buf = p; + int n = 0; /* buffer index */ + int plen = 0; /* prompt length */ + int col; /* output column cnt */ + char c; + + /* print prompt */ + if (prompt) { + plen = strlen(prompt); + puts(prompt); + } + col = plen; + + for (;;) { +#ifdef CONFIG_BOOT_RETRY_TIME + while (!tstc()) { /* while no incoming data */ + if (retry_time >= 0 && get_ticks() > endtime) + return -2; /* timed out */ + WATCHDOG_RESET(); + } +#endif + WATCHDOG_RESET(); /* Trigger watchdog, if needed */ + +#ifdef CONFIG_SHOW_ACTIVITY + while (!tstc()) { + show_activity(0); + WATCHDOG_RESET(); + } +#endif + c = getc(); + + /* + * Special character handling + */ + switch (c) { + case '\r': /* Enter */ + case '\n': + *p = '\0'; + puts("\r\n"); + return p - p_buf; + + case '\0': /* nul */ + continue; + + case 0x03: /* ^C - break */ + p_buf[0] = '\0'; /* discard input */ + return -1; + + case 0x15: /* ^U - erase line */ + while (col > plen) { + puts(erase_seq); + --col; + } + p = p_buf; + n = 0; + continue; + + case 0x17: /* ^W - erase word */ + p = delete_char(p_buf, p, &col, &n, plen); + while ((n > 0) && (*p != ' ')) + p = delete_char(p_buf, p, &col, &n, plen); + continue; + + case 0x08: /* ^H - backspace */ + case 0x7F: /* DEL - backspace */ + p = delete_char(p_buf, p, &col, &n, plen); + continue; + + default: + /* + * Must be a normal character then + */ + if (n < CONFIG_SYS_CBSIZE-2) { + if (c == '\t') { /* expand TABs */ +#ifdef CONFIG_AUTO_COMPLETE + /* + * if auto completion triggered just + * continue + */ + *p = '\0'; + if (cmd_auto_complete(prompt, + console_buffer, + &n, &col)) { + p = p_buf + n; /* reset */ + continue; + } +#endif + puts(tab_seq + (col & 07)); + col += 8 - (col & 07); + } else { + char buf[2]; + + /* + * Echo input using puts() to force an + * LCD flush if we are using an LCD + */ + ++col; + buf[0] = c; + buf[1] = '\0'; + puts(buf); + } + *p++ = c; + ++n; + } else { /* Buffer full */ + putc('\a'); + } + } + } +#ifdef CONFIG_CMDLINE_EDITING + } +#endif +} + +#ifdef CONFIG_BOOT_RETRY_TIME +/*************************************************************************** + * initialize command line timeout + */ +void init_cmd_timeout(void) +{ + char *s = getenv("bootretry"); + + if (s != NULL) + retry_time = (int)simple_strtol(s, NULL, 10); + else + retry_time = CONFIG_BOOT_RETRY_TIME; + + if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN) + retry_time = CONFIG_BOOT_RETRY_MIN; +} + +/*************************************************************************** + * reset command line timeout to retry_time seconds + */ +void reset_cmd_timeout(void) +{ + endtime = endtick(retry_time); +} + +void bootretry_dont_retry(void) +{ + retry_time = -1; +} + +#endif diff --git a/common/cli_simple.c b/common/cli_simple.c new file mode 100644 index 0000000..0610615 --- /dev/null +++ b/common/cli_simple.c @@ -0,0 +1,338 @@ +/* + * (C) Copyright 2000 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * Add to readline cmdline-editing by + * (C) Copyright 2005 + * JinHua Luo, GuangDong Linux Center, + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +#define DEBUG_PARSER 0 /* set to 1 to debug */ + +#define debug_parser(fmt, args...) \ + debug_cond(DEBUG_PARSER, fmt, ##args) + + +int parse_line(char *line, char *argv[]) +{ + int nargs = 0; + + debug_parser("%s: \"%s\"\n", __func__, line); + while (nargs < CONFIG_SYS_MAXARGS) { + /* skip any white space */ + while (isblank(*line)) + ++line; + + if (*line == '\0') { /* end of line, no more args */ + argv[nargs] = NULL; + debug_parser("%s: nargs=%d\n", __func__, nargs); + return nargs; + } + + argv[nargs++] = line; /* begin of argument string */ + + /* find end of string */ + while (*line && !isblank(*line)) + ++line; + + if (*line == '\0') { /* end of line, no more args */ + argv[nargs] = NULL; + debug_parser("parse_line: nargs=%d\n", nargs); + return nargs; + } + + *line++ = '\0'; /* terminate current arg */ + } + + printf("** Too many args (max. %d) **\n", CONFIG_SYS_MAXARGS); + + debug_parser("%s: nargs=%d\n", __func__, nargs); + return nargs; +} + +static void process_macros(const char *input, char *output) +{ + char c, prev; + const char *varname_start = NULL; + int inputcnt = strlen(input); + int outputcnt = CONFIG_SYS_CBSIZE; + int state = 0; /* 0 = waiting for '$' */ + + /* 1 = waiting for '(' or '{' */ + /* 2 = waiting for ')' or '}' */ + /* 3 = waiting for ''' */ + char *output_start = output; + + debug_parser("[PROCESS_MACROS] INPUT len %zd: \"%s\"\n", strlen(input), + input); + + prev = '\0'; /* previous character */ + + while (inputcnt && outputcnt) { + c = *input++; + inputcnt--; + + if (state != 3) { + /* remove one level of escape characters */ + if ((c == '\\') && (prev != '\\')) { + if (inputcnt-- == 0) + break; + prev = c; + c = *input++; + } + } + + switch (state) { + case 0: /* Waiting for (unescaped) $ */ + if ((c == '\'') && (prev != '\\')) { + state = 3; + break; + } + if ((c == '$') && (prev != '\\')) { + state++; + } else { + *(output++) = c; + outputcnt--; + } + break; + case 1: /* Waiting for ( */ + if (c == '(' || c == '{') { + state++; + varname_start = input; + } else { + state = 0; + *(output++) = '$'; + outputcnt--; + + if (outputcnt) { + *(output++) = c; + outputcnt--; + } + } + break; + case 2: /* Waiting for ) */ + if (c == ')' || c == '}') { + int i; + char envname[CONFIG_SYS_CBSIZE], *envval; + /* Varname # of chars */ + int envcnt = input - varname_start - 1; + + /* Get the varname */ + for (i = 0; i < envcnt; i++) + envname[i] = varname_start[i]; + envname[i] = 0; + + /* Get its value */ + envval = getenv(envname); + + /* Copy into the line if it exists */ + if (envval != NULL) + while ((*envval) && outputcnt) { + *(output++) = *(envval++); + outputcnt--; + } + /* Look for another '$' */ + state = 0; + } + break; + case 3: /* Waiting for ' */ + if ((c == '\'') && (prev != '\\')) { + state = 0; + } else { + *(output++) = c; + outputcnt--; + } + break; + } + prev = c; + } + + if (outputcnt) + *output = 0; + else + *(output - 1) = 0; + + debug_parser("[PROCESS_MACROS] OUTPUT len %zd: \"%s\"\n", + strlen(output_start), output_start); +} + + /* + * WARNING: + * + * We must create a temporary copy of the command since the command we get + * may be the result from getenv(), which returns a pointer directly to + * the environment data, which may change magicly when the command we run + * creates or modifies environment variables (like "bootp" does). + */ +int cli_simple_run_command(const char *cmd, int flag) +{ + char cmdbuf[CONFIG_SYS_CBSIZE]; /* working copy of cmd */ + char *token; /* start of token in cmdbuf */ + char *sep; /* end of token (separator) in cmdbuf */ + char finaltoken[CONFIG_SYS_CBSIZE]; + char *str = cmdbuf; + char *argv[CONFIG_SYS_MAXARGS + 1]; /* NULL terminated */ + int argc, inquotes; + int repeatable = 1; + int rc = 0; + + debug_parser("[RUN_COMMAND] cmd[%p]=\"", cmd); + if (DEBUG_PARSER) { + /* use puts - string may be loooong */ + puts(cmd ? cmd : "NULL"); + puts("\"\n"); + } + clear_ctrlc(); /* forget any previous Control C */ + + if (!cmd || !*cmd) + return -1; /* empty command */ + + if (strlen(cmd) >= CONFIG_SYS_CBSIZE) { + puts("## Command too long!\n"); + return -1; + } + + strcpy(cmdbuf, cmd); + + /* Process separators and check for invalid + * repeatable commands + */ + + debug_parser("[PROCESS_SEPARATORS] %s\n", cmd); + while (*str) { + /* + * Find separator, or string end + * Allow simple escape of ';' by writing "\;" + */ + for (inquotes = 0, sep = str; *sep; sep++) { + if ((*sep == '\'') && + (*(sep - 1) != '\\')) + inquotes = !inquotes; + + if (!inquotes && + (*sep == ';') && /* separator */ + (sep != str) && /* past string start */ + (*(sep - 1) != '\\')) /* and NOT escaped */ + break; + } + + /* + * Limit the token to data between separators + */ + token = str; + if (*sep) { + str = sep + 1; /* start of command for next pass */ + *sep = '\0'; + } else { + str = sep; /* no more commands for next pass */ + } + debug_parser("token: \"%s\"\n", token); + + /* find macros in this token and replace them */ + process_macros(token, finaltoken); + + /* Extract arguments */ + argc = parse_line(finaltoken, argv); + if (argc == 0) { + rc = -1; /* no command at all */ + continue; + } + + if (cmd_process(flag, argc, argv, &repeatable, NULL)) + rc = -1; + + /* Did the user stop this? */ + if (had_ctrlc()) + return -1; /* if stopped then not repeatable */ + } + + return rc ? rc : repeatable; +} + +void cli_loop(void) +{ + static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, }; + + int len; + int flag; + int rc = 1; + + for (;;) { +#ifdef CONFIG_BOOT_RETRY_TIME + if (rc >= 0) { + /* Saw enough of a valid command to + * restart the timeout. + */ + reset_cmd_timeout(); + } +#endif + len = readline(CONFIG_SYS_PROMPT); + + flag = 0; /* assume no special flags for now */ + if (len > 0) + strcpy(lastcommand, console_buffer); + else if (len == 0) + flag |= CMD_FLAG_REPEAT; +#ifdef CONFIG_BOOT_RETRY_TIME + else if (len == -2) { + /* -2 means timed out, retry autoboot + */ + puts("\nTimed out waiting for command\n"); +# ifdef CONFIG_RESET_TO_RETRY + /* Reinit board to run initialization code again */ + do_reset(NULL, 0, 0, NULL); +# else + return; /* retry autoboot */ +# endif + } +#endif + + if (len == -1) + puts("\n"); + else + rc = run_command(lastcommand, flag); + + if (rc <= 0) { + /* invalid command or not repeatable, forget it */ + lastcommand[0] = 0; + } + } +} + +int cli_simple_run_command_list(char *cmd, int flag) +{ + char *line, *next; + int rcode = 0; + + /* + * Break into individual lines, and execute each line; terminate on + * error. + */ + next = cmd; + line = cmd; + while (*next) { + if (*next == '\n') { + *next = '\0'; + /* run only non-empty commands */ + if (*line) { + debug("** exec: \"%s\"\n", line); + if (cli_simple_run_command(line, 0) < 0) { + rcode = 1; + break; + } + } + line = next + 1; + } + ++next; + } + if (rcode == 0 && *line) + rcode = (cli_simple_run_command(line, 0) >= 0); + + return rcode; +} diff --git a/common/main.c b/common/main.c index 6d1c3a9..88b0adb 100644 --- a/common/main.c +++ b/common/main.c @@ -2,10 +2,6 @@ * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * - * Add to readline cmdline-editing by - * (C) Copyright 2005 - * JinHua Luo, GuangDong Linux Center, - * * SPDX-License-Identifier: GPL-2.0+ */ @@ -20,8 +16,6 @@ #include #include #include -#include -#include DECLARE_GLOBAL_DATA_PTR; @@ -33,34 +27,12 @@ void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progre #define MAX_DELAY_STOP_STR 32 -#define DEBUG_PARSER 0 /* set to 1 to debug */ - -#define debug_parser(fmt, args...) \ - debug_cond(DEBUG_PARSER, fmt, ##args) - #ifndef DEBUG_BOOTKEYS #define DEBUG_BOOTKEYS 0 #endif #define debug_bootkeys(fmt, args...) \ debug_cond(DEBUG_BOOTKEYS, fmt, ##args) -char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */ - -static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen); -static const char erase_seq[] = "\b \b"; /* erase sequence */ -static const char tab_seq[] = " "; /* used to expand TABs */ - -#ifdef CONFIG_BOOT_RETRY_TIME -static uint64_t endtime = 0; /* must be set, default is instant timeout */ -static int retry_time = -1; /* -1 so can call readline before main_loop */ -#endif - -#define endtick(seconds) (get_ticks() + (uint64_t)(seconds) * get_tbclk()) - -#ifndef CONFIG_BOOT_RETRY_MIN -#define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME -#endif - #ifdef CONFIG_MODEM_SUPPORT int do_mdm_init = 0; extern void mdm_init(void); /* defined in board.c */ @@ -162,7 +134,7 @@ static int abortboot_keyed(int bootdelay) # ifdef CONFIG_BOOT_RETRY_TIME /* don't retry auto boot */ if (! delaykey[i].retry) - retry_time = -1; + bootretry_dont_retry(); # endif abort = 1; } @@ -416,12 +388,6 @@ static void process_boot_delay(void) void main_loop(void) { -#ifndef CONFIG_SYS_HUSH_PARSER - static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, }; - int len; - int rc = 1; - int flag; -#endif #ifdef CONFIG_PREBOOT char *p; #endif @@ -489,943 +455,13 @@ void main_loop(void) /* This point is never reached */ for (;;); #else - for (;;) { -#ifdef CONFIG_BOOT_RETRY_TIME - if (rc >= 0) { - /* Saw enough of a valid command to - * restart the timeout. - */ - reset_cmd_timeout(); - } -#endif - len = readline (CONFIG_SYS_PROMPT); - - flag = 0; /* assume no special flags for now */ - if (len > 0) - strcpy (lastcommand, console_buffer); - else if (len == 0) - flag |= CMD_FLAG_REPEAT; -#ifdef CONFIG_BOOT_RETRY_TIME - else if (len == -2) { - /* -2 means timed out, retry autoboot - */ - puts ("\nTimed out waiting for command\n"); -# ifdef CONFIG_RESET_TO_RETRY - /* Reinit board to run initialization code again */ - do_reset (NULL, 0, 0, NULL); -# else - return; /* retry autoboot */ -# endif - } -#endif - - if (len == -1) - puts ("\n"); - else - rc = run_command(lastcommand, flag); - - if (rc <= 0) { - /* invalid command or not repeatable, forget it */ - lastcommand[0] = 0; - } - } + cli_loop(); #endif /*CONFIG_SYS_HUSH_PARSER*/ } -#ifdef CONFIG_BOOT_RETRY_TIME -/*************************************************************************** - * initialize command line timeout - */ -void init_cmd_timeout(void) -{ - char *s = getenv ("bootretry"); - - if (s != NULL) - retry_time = (int)simple_strtol(s, NULL, 10); - else - retry_time = CONFIG_BOOT_RETRY_TIME; - - if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN) - retry_time = CONFIG_BOOT_RETRY_MIN; -} - -/*************************************************************************** - * reset command line timeout to retry_time seconds - */ -void reset_cmd_timeout(void) -{ - endtime = endtick(retry_time); -} -#endif - -#ifdef CONFIG_CMDLINE_EDITING - -/* - * cmdline-editing related codes from vivi. - * Author: Janghoon Lyu - */ - -#define putnstr(str,n) do { \ - printf ("%.*s", (int)n, str); \ - } while (0) - -#define CTL_CH(c) ((c) - 'a' + 1) -#define CTL_BACKSPACE ('\b') -#define DEL ((char)255) -#define DEL7 ((char)127) -#define CREAD_HIST_CHAR ('!') - -#define getcmd_putch(ch) putc(ch) -#define getcmd_getch() getc() -#define getcmd_cbeep() getcmd_putch('\a') - -#define HIST_MAX 20 -#define HIST_SIZE CONFIG_SYS_CBSIZE - -static int hist_max; -static int hist_add_idx; -static int hist_cur = -1; -static unsigned hist_num; - -static char *hist_list[HIST_MAX]; -static char hist_lines[HIST_MAX][HIST_SIZE + 1]; /* Save room for NULL */ - -#define add_idx_minus_one() ((hist_add_idx == 0) ? hist_max : hist_add_idx-1) - -static void hist_init(void) -{ - int i; - - hist_max = 0; - hist_add_idx = 0; - hist_cur = -1; - hist_num = 0; - - for (i = 0; i < HIST_MAX; i++) { - hist_list[i] = hist_lines[i]; - hist_list[i][0] = '\0'; - } -} - -static void cread_add_to_hist(char *line) -{ - strcpy(hist_list[hist_add_idx], line); - - if (++hist_add_idx >= HIST_MAX) - hist_add_idx = 0; - - if (hist_add_idx > hist_max) - hist_max = hist_add_idx; - - hist_num++; -} - -static char* hist_prev(void) -{ - char *ret; - int old_cur; - - if (hist_cur < 0) - return NULL; - - old_cur = hist_cur; - if (--hist_cur < 0) - hist_cur = hist_max; - - if (hist_cur == hist_add_idx) { - hist_cur = old_cur; - ret = NULL; - } else - ret = hist_list[hist_cur]; - - return (ret); -} - -static char* hist_next(void) -{ - char *ret; - - if (hist_cur < 0) - return NULL; - - if (hist_cur == hist_add_idx) - return NULL; - - if (++hist_cur > hist_max) - hist_cur = 0; - - if (hist_cur == hist_add_idx) { - ret = ""; - } else - ret = hist_list[hist_cur]; - - return (ret); -} - -#ifndef CONFIG_CMDLINE_EDITING -static void cread_print_hist_list(void) -{ - int i; - unsigned long n; - - n = hist_num - hist_max; - - i = hist_add_idx + 1; - while (1) { - if (i > hist_max) - i = 0; - if (i == hist_add_idx) - break; - printf("%s\n", hist_list[i]); - n++; - i++; - } -} -#endif /* CONFIG_CMDLINE_EDITING */ - -#define BEGINNING_OF_LINE() { \ - while (num) { \ - getcmd_putch(CTL_BACKSPACE); \ - num--; \ - } \ -} - -#define ERASE_TO_EOL() { \ - if (num < eol_num) { \ - printf("%*s", (int)(eol_num - num), ""); \ - do { \ - getcmd_putch(CTL_BACKSPACE); \ - } while (--eol_num > num); \ - } \ -} - -#define REFRESH_TO_EOL() { \ - if (num < eol_num) { \ - wlen = eol_num - num; \ - putnstr(buf + num, wlen); \ - num = eol_num; \ - } \ -} - -static void cread_add_char(char ichar, int insert, unsigned long *num, - unsigned long *eol_num, char *buf, unsigned long len) -{ - unsigned long wlen; - - /* room ??? */ - if (insert || *num == *eol_num) { - if (*eol_num > len - 1) { - getcmd_cbeep(); - return; - } - (*eol_num)++; - } - - if (insert) { - wlen = *eol_num - *num; - if (wlen > 1) { - memmove(&buf[*num+1], &buf[*num], wlen-1); - } - - buf[*num] = ichar; - putnstr(buf + *num, wlen); - (*num)++; - while (--wlen) { - getcmd_putch(CTL_BACKSPACE); - } - } else { - /* echo the character */ - wlen = 1; - buf[*num] = ichar; - putnstr(buf + *num, wlen); - (*num)++; - } -} - -static void cread_add_str(char *str, int strsize, int insert, unsigned long *num, - unsigned long *eol_num, char *buf, unsigned long len) -{ - while (strsize--) { - cread_add_char(*str, insert, num, eol_num, buf, len); - str++; - } -} - -static int cread_line(const char *const prompt, char *buf, unsigned int *len, - int timeout) -{ - unsigned long num = 0; - unsigned long eol_num = 0; - unsigned long wlen; - char ichar; - int insert = 1; - int esc_len = 0; - char esc_save[8]; - int init_len = strlen(buf); - int first = 1; - - if (init_len) - cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len); - - while (1) { -#ifdef CONFIG_BOOT_RETRY_TIME - while (!tstc()) { /* while no incoming data */ - if (retry_time >= 0 && get_ticks() > endtime) - return (-2); /* timed out */ - WATCHDOG_RESET(); - } -#endif - if (first && timeout) { - uint64_t etime = endtick(timeout); - - while (!tstc()) { /* while no incoming data */ - if (get_ticks() >= etime) - return -2; /* timed out */ - WATCHDOG_RESET(); - } - first = 0; - } - - ichar = getcmd_getch(); - - if ((ichar == '\n') || (ichar == '\r')) { - putc('\n'); - break; - } - - /* - * handle standard linux xterm esc sequences for arrow key, etc. - */ - if (esc_len != 0) { - if (esc_len == 1) { - if (ichar == '[') { - esc_save[esc_len] = ichar; - esc_len = 2; - } else { - cread_add_str(esc_save, esc_len, insert, - &num, &eol_num, buf, *len); - esc_len = 0; - } - continue; - } - - switch (ichar) { - - case 'D': /* <- key */ - ichar = CTL_CH('b'); - esc_len = 0; - break; - case 'C': /* -> key */ - ichar = CTL_CH('f'); - esc_len = 0; - break; /* pass off to ^F handler */ - case 'H': /* Home key */ - ichar = CTL_CH('a'); - esc_len = 0; - break; /* pass off to ^A handler */ - case 'A': /* up arrow */ - ichar = CTL_CH('p'); - esc_len = 0; - break; /* pass off to ^P handler */ - case 'B': /* down arrow */ - ichar = CTL_CH('n'); - esc_len = 0; - break; /* pass off to ^N handler */ - default: - esc_save[esc_len++] = ichar; - cread_add_str(esc_save, esc_len, insert, - &num, &eol_num, buf, *len); - esc_len = 0; - continue; - } - } - - switch (ichar) { - case 0x1b: - if (esc_len == 0) { - esc_save[esc_len] = ichar; - esc_len = 1; - } else { - puts("impossible condition #876\n"); - esc_len = 0; - } - break; - - case CTL_CH('a'): - BEGINNING_OF_LINE(); - break; - case CTL_CH('c'): /* ^C - break */ - *buf = '\0'; /* discard input */ - return (-1); - case CTL_CH('f'): - if (num < eol_num) { - getcmd_putch(buf[num]); - num++; - } - break; - case CTL_CH('b'): - if (num) { - getcmd_putch(CTL_BACKSPACE); - num--; - } - break; - case CTL_CH('d'): - if (num < eol_num) { - wlen = eol_num - num - 1; - if (wlen) { - memmove(&buf[num], &buf[num+1], wlen); - putnstr(buf + num, wlen); - } - - getcmd_putch(' '); - do { - getcmd_putch(CTL_BACKSPACE); - } while (wlen--); - eol_num--; - } - break; - case CTL_CH('k'): - ERASE_TO_EOL(); - break; - case CTL_CH('e'): - REFRESH_TO_EOL(); - break; - case CTL_CH('o'): - insert = !insert; - break; - case CTL_CH('x'): - case CTL_CH('u'): - BEGINNING_OF_LINE(); - ERASE_TO_EOL(); - break; - case DEL: - case DEL7: - case 8: - if (num) { - wlen = eol_num - num; - num--; - memmove(&buf[num], &buf[num+1], wlen); - getcmd_putch(CTL_BACKSPACE); - putnstr(buf + num, wlen); - getcmd_putch(' '); - do { - getcmd_putch(CTL_BACKSPACE); - } while (wlen--); - eol_num--; - } - break; - case CTL_CH('p'): - case CTL_CH('n'): - { - char * hline; - - esc_len = 0; - - if (ichar == CTL_CH('p')) - hline = hist_prev(); - else - hline = hist_next(); - - if (!hline) { - getcmd_cbeep(); - continue; - } - - /* nuke the current line */ - /* first, go home */ - BEGINNING_OF_LINE(); - - /* erase to end of line */ - ERASE_TO_EOL(); - - /* copy new line into place and display */ - strcpy(buf, hline); - eol_num = strlen(buf); - REFRESH_TO_EOL(); - continue; - } -#ifdef CONFIG_AUTO_COMPLETE - case '\t': { - int num2, col; - - /* do not autocomplete when in the middle */ - if (num < eol_num) { - getcmd_cbeep(); - break; - } - - buf[num] = '\0'; - col = strlen(prompt) + eol_num; - num2 = num; - if (cmd_auto_complete(prompt, buf, &num2, &col)) { - col = num2 - num; - num += col; - eol_num += col; - } - break; - } -#endif - default: - cread_add_char(ichar, insert, &num, &eol_num, buf, *len); - break; - } - } - *len = eol_num; - buf[eol_num] = '\0'; /* lose the newline */ - - if (buf[0] && buf[0] != CREAD_HIST_CHAR) - cread_add_to_hist(buf); - hist_cur = hist_add_idx; - - return 0; -} - -#endif /* CONFIG_CMDLINE_EDITING */ - /****************************************************************************/ /* - * Prompt for input and read a line. - * If CONFIG_BOOT_RETRY_TIME is defined and retry_time >= 0, - * time out when time goes past endtime (timebase time in ticks). - * Return: number of read characters - * -1 if break - * -2 if timed out - */ -int readline (const char *const prompt) -{ - /* - * If console_buffer isn't 0-length the user will be prompted to modify - * it instead of entering it from scratch as desired. - */ - console_buffer[0] = '\0'; - - return readline_into_buffer(prompt, console_buffer, 0); -} - - -int readline_into_buffer(const char *const prompt, char *buffer, int timeout) -{ - char *p = buffer; -#ifdef CONFIG_CMDLINE_EDITING - unsigned int len = CONFIG_SYS_CBSIZE; - int rc; - static int initted = 0; - - /* - * History uses a global array which is not - * writable until after relocation to RAM. - * Revert to non-history version if still - * running from flash. - */ - if (gd->flags & GD_FLG_RELOC) { - if (!initted) { - hist_init(); - initted = 1; - } - - if (prompt) - puts (prompt); - - rc = cread_line(prompt, p, &len, timeout); - return rc < 0 ? rc : len; - - } else { -#endif /* CONFIG_CMDLINE_EDITING */ - char * p_buf = p; - int n = 0; /* buffer index */ - int plen = 0; /* prompt length */ - int col; /* output column cnt */ - char c; - - /* print prompt */ - if (prompt) { - plen = strlen (prompt); - puts (prompt); - } - col = plen; - - for (;;) { -#ifdef CONFIG_BOOT_RETRY_TIME - while (!tstc()) { /* while no incoming data */ - if (retry_time >= 0 && get_ticks() > endtime) - return (-2); /* timed out */ - WATCHDOG_RESET(); - } -#endif - WATCHDOG_RESET(); /* Trigger watchdog, if needed */ - -#ifdef CONFIG_SHOW_ACTIVITY - while (!tstc()) { - show_activity(0); - WATCHDOG_RESET(); - } -#endif - c = getc(); - - /* - * Special character handling - */ - switch (c) { - case '\r': /* Enter */ - case '\n': - *p = '\0'; - puts ("\r\n"); - return p - p_buf; - - case '\0': /* nul */ - continue; - - case 0x03: /* ^C - break */ - p_buf[0] = '\0'; /* discard input */ - return -1; - - case 0x15: /* ^U - erase line */ - while (col > plen) { - puts (erase_seq); - --col; - } - p = p_buf; - n = 0; - continue; - - case 0x17: /* ^W - erase word */ - p=delete_char(p_buf, p, &col, &n, plen); - while ((n > 0) && (*p != ' ')) { - p=delete_char(p_buf, p, &col, &n, plen); - } - continue; - - case 0x08: /* ^H - backspace */ - case 0x7F: /* DEL - backspace */ - p=delete_char(p_buf, p, &col, &n, plen); - continue; - - default: - /* - * Must be a normal character then - */ - if (n < CONFIG_SYS_CBSIZE-2) { - if (c == '\t') { /* expand TABs */ -#ifdef CONFIG_AUTO_COMPLETE - /* if auto completion triggered just continue */ - *p = '\0'; - if (cmd_auto_complete(prompt, console_buffer, &n, &col)) { - p = p_buf + n; /* reset */ - continue; - } -#endif - puts (tab_seq+(col&07)); - col += 8 - (col&07); - } else { - char buf[2]; - - /* - * Echo input using puts() to force an - * LCD flush if we are using an LCD - */ - ++col; - buf[0] = c; - buf[1] = '\0'; - puts(buf); - } - *p++ = c; - ++n; - } else { /* Buffer full */ - putc ('\a'); - } - } - } -#ifdef CONFIG_CMDLINE_EDITING - } -#endif -} - -/****************************************************************************/ - -static char * delete_char (char *buffer, char *p, int *colp, int *np, int plen) -{ - char *s; - - if (*np == 0) { - return (p); - } - - if (*(--p) == '\t') { /* will retype the whole line */ - while (*colp > plen) { - puts (erase_seq); - (*colp)--; - } - for (s=buffer; s= CONFIG_SYS_CBSIZE) { - puts ("## Command too long!\n"); - return -1; - } - - strcpy (cmdbuf, cmd); - - /* Process separators and check for invalid - * repeatable commands - */ - - debug_parser("[PROCESS_SEPARATORS] %s\n", cmd); - while (*str) { - - /* - * Find separator, or string end - * Allow simple escape of ';' by writing "\;" - */ - for (inquotes = 0, sep = str; *sep; sep++) { - if ((*sep=='\'') && - (*(sep-1) != '\\')) - inquotes=!inquotes; - - if (!inquotes && - (*sep == ';') && /* separator */ - ( sep != str) && /* past string start */ - (*(sep-1) != '\\')) /* and NOT escaped */ - break; - } - - /* - * Limit the token to data between separators - */ - token = str; - if (*sep) { - str = sep + 1; /* start of command for next pass */ - *sep = '\0'; - } - else - str = sep; /* no more commands for next pass */ - debug_parser("token: \"%s\"\n", token); - - /* find macros in this token and replace them */ - process_macros (token, finaltoken); - - /* Extract arguments */ - if ((argc = parse_line (finaltoken, argv)) == 0) { - rc = -1; /* no command at all */ - continue; - } - - if (cmd_process(flag, argc, argv, &repeatable, NULL)) - rc = -1; - - /* Did the user stop this? */ - if (had_ctrlc ()) - return -1; /* if stopped then not repeatable */ - } - - return rc ? rc : repeatable; -} -#endif - -/* * Run a command using the selected parser. * * @param cmd Command to run @@ -1436,10 +472,10 @@ int run_command(const char *cmd, int flag) { #ifndef CONFIG_SYS_HUSH_PARSER /* - * builtin_run_command can return 0 or 1 for success, so clean up + * cli_run_command can return 0 or 1 for success, so clean up * its result. */ - if (builtin_run_command(cmd, flag) == -1) + if (cli_simple_run_command(cmd, flag) == -1) return 1; return 0; @@ -1449,49 +485,6 @@ int run_command(const char *cmd, int flag) #endif } -#ifndef CONFIG_SYS_HUSH_PARSER -/** - * Execute a list of command separated by ; or \n using the built-in parser. - * - * This function cannot take a const char * for the command, since if it - * finds newlines in the string, it replaces them with \0. - * - * @param cmd String containing list of commands - * @param flag Execution flags (CMD_FLAG_...) - * @return 0 on success, or != 0 on error. - */ -static int builtin_run_command_list(char *cmd, int flag) -{ - char *line, *next; - int rcode = 0; - - /* - * Break into individual lines, and execute each line; terminate on - * error. - */ - line = next = cmd; - while (*next) { - if (*next == '\n') { - *next = '\0'; - /* run only non-empty commands */ - if (*line) { - debug("** exec: \"%s\"\n", line); - if (builtin_run_command(line, 0) < 0) { - rcode = 1; - break; - } - } - line = next + 1; - } - ++next; - } - if (rcode == 0 && *line) - rcode = (builtin_run_command(line, 0) >= 0); - - return rcode; -} -#endif - int run_command_list(const char *cmd, int len, int flag) { int need_buff = 1; @@ -1525,7 +518,7 @@ int run_command_list(const char *cmd, int len, int flag) * doing a malloc() which is actually required only in a case that * is pretty rare. */ - rcode = builtin_run_command_list(buff, flag); + rcode = cli_simple_run_command_list(buff, flag); if (need_buff) free(buff); #endif -- cgit v1.1 From e1bf824dfd6881f6f633238c275bfa1e5d83c433 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:27 -0600 Subject: Add cli_ prefix to readline functions This makes it clear where the code resides. Signed-off-by: Simon Glass --- common/cli_hush.c | 4 ++-- common/cli_readline.c | 7 ++++--- common/cli_simple.c | 6 +++--- common/cmd_bedbug.c | 28 ++++++++++++++-------------- common/cmd_dcr.c | 2 +- common/cmd_i2c.c | 2 +- common/cmd_mem.c | 2 +- common/cmd_nvedit.c | 4 ++-- common/cmd_pci.c | 2 +- common/menu.c | 5 +++-- 10 files changed, 32 insertions(+), 30 deletions(-) (limited to 'common') diff --git a/common/cli_hush.c b/common/cli_hush.c index 91e4956..a612bfb 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -1007,9 +1007,9 @@ static void get_user_input(struct in_str *i) #endif i->__promptme = 1; if (i->promptmode == 1) { - n = readline(CONFIG_SYS_PROMPT); + n = cli_readline(CONFIG_SYS_PROMPT); } else { - n = readline(CONFIG_SYS_PROMPT_HUSH_PS2); + n = cli_readline(CONFIG_SYS_PROMPT_HUSH_PS2); } #ifdef CONFIG_BOOT_RETRY_TIME if (n == -2) { diff --git a/common/cli_readline.c b/common/cli_readline.c index cea0b7c..df446b8 100644 --- a/common/cli_readline.c +++ b/common/cli_readline.c @@ -484,7 +484,7 @@ static int cread_line(const char *const prompt, char *buf, unsigned int *len, /****************************************************************************/ -int readline(const char *const prompt) +int cli_readline(const char *const prompt) { /* * If console_buffer isn't 0-length the user will be prompted to modify @@ -492,11 +492,12 @@ int readline(const char *const prompt) */ console_buffer[0] = '\0'; - return readline_into_buffer(prompt, console_buffer, 0); + return cli_readline_into_buffer(prompt, console_buffer, 0); } -int readline_into_buffer(const char *const prompt, char *buffer, int timeout) +int cli_readline_into_buffer(const char *const prompt, char *buffer, + int timeout) { char *p = buffer; #ifdef CONFIG_CMDLINE_EDITING diff --git a/common/cli_simple.c b/common/cli_simple.c index 0610615..3039cfc 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -19,7 +19,7 @@ debug_cond(DEBUG_PARSER, fmt, ##args) -int parse_line(char *line, char *argv[]) +int cli_simple_parse_line(char *line, char *argv[]) { int nargs = 0; @@ -238,7 +238,7 @@ int cli_simple_run_command(const char *cmd, int flag) process_macros(token, finaltoken); /* Extract arguments */ - argc = parse_line(finaltoken, argv); + argc = cli_simple_parse_line(finaltoken, argv); if (argc == 0) { rc = -1; /* no command at all */ continue; @@ -272,7 +272,7 @@ void cli_loop(void) reset_cmd_timeout(); } #endif - len = readline(CONFIG_SYS_PROMPT); + len = cli_readline(CONFIG_SYS_PROMPT); flag = 0; /* assume no special flags for now */ if (len > 0) diff --git a/common/cmd_bedbug.c b/common/cmd_bedbug.c index f1a70ef..bdcf712 100644 --- a/common/cmd_bedbug.c +++ b/common/cmd_bedbug.c @@ -20,7 +20,7 @@ extern int run_command __P ((const char *, int)); ulong dis_last_addr = 0; /* Last address disassembled */ ulong dis_last_len = 20; /* Default disassembler length */ CPU_DEBUG_CTX bug_ctx; /* Bedbug context structure */ - + /* ====================================================================== * U-Boot's puts function does not append a newline, so the bedbug stuff @@ -34,7 +34,7 @@ int bedbug_puts (const char *str) printf ("%s\r\n", str); return 0; } /* bedbug_puts */ - + /* ====================================================================== @@ -66,7 +66,7 @@ void bedbug_init (void) return; } /* bedbug_init */ - + /* ====================================================================== @@ -107,7 +107,7 @@ int do_bedbug_dis (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) U_BOOT_CMD (ds, 3, 1, do_bedbug_dis, "disassemble memory", "ds
[# instructions]"); - + /* ====================================================================== * Entry point from the interpreter to the assembler. Assembles * instructions in consecutive memory locations until a '.' (period) is @@ -135,7 +135,7 @@ int do_bedbug_asm (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) F_RADHEX); sprintf (prompt, "%08lx: ", mem_addr); - readline (prompt); + cli_readline(prompt); if (console_buffer[0] && strcmp (console_buffer, ".")) { if ((instr = @@ -157,7 +157,7 @@ int do_bedbug_asm (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) U_BOOT_CMD (as, 2, 0, do_bedbug_asm, "assemble memory", "as
"); - + /* ====================================================================== * Used to set a break point from the interpreter. Simply calls into the * CPU-specific break point set routine. @@ -178,7 +178,7 @@ U_BOOT_CMD (break, 3, 0, do_bedbug_break, "break
- Break at an address\n" "break off - Disable breakpoint.\n" "break show - List breakpoints."); - + /* ====================================================================== * Called from the debug interrupt routine. Simply calls the CPU-specific * breakpoint handling routine. @@ -193,7 +193,7 @@ void do_bedbug_breakpoint (struct pt_regs *regs) return; } /* do_bedbug_breakpoint */ - + /* ====================================================================== @@ -226,7 +226,7 @@ void bedbug_main_loop (unsigned long addr, struct pt_regs *regs) /* A miniature main loop */ while (bug_ctx.stopped) { - len = readline (prompt_str); + len = cli_readline(prompt_str); flag = 0; /* assume no special flags for now */ @@ -251,7 +251,7 @@ void bedbug_main_loop (unsigned long addr, struct pt_regs *regs) return; } /* bedbug_main_loop */ - + /* ====================================================================== @@ -275,7 +275,7 @@ int do_bedbug_continue (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv U_BOOT_CMD (continue, 1, 0, do_bedbug_continue, "continue from a breakpoint", ""); - + /* ====================================================================== * Interpreter command to continue to the next instruction, stepping into * subroutines. Works by calling the find_next_addr() routine to compute @@ -306,7 +306,7 @@ int do_bedbug_step (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) U_BOOT_CMD (step, 1, 1, do_bedbug_step, "single step execution.", ""); - + /* ====================================================================== * Interpreter command to continue to the next instruction, stepping over * subroutines. Works by calling the find_next_addr() routine to compute @@ -337,7 +337,7 @@ int do_bedbug_next (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) U_BOOT_CMD (next, 1, 1, do_bedbug_next, "single step execution, stepping over subroutines.", ""); - + /* ====================================================================== * Interpreter command to print the current stack. This assumes an EABI * architecture, so it starts with GPR R1 and works back up the stack. @@ -382,7 +382,7 @@ int do_bedbug_stack (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) U_BOOT_CMD (where, 1, 1, do_bedbug_stack, "Print the running stack.", ""); - + /* ====================================================================== * Interpreter command to dump the registers. Calls the CPU-specific * show registers routine. diff --git a/common/cmd_dcr.c b/common/cmd_dcr.c index c5bcb8b..4fddd80 100644 --- a/common/cmd_dcr.c +++ b/common/cmd_dcr.c @@ -63,7 +63,7 @@ int do_setdcr (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) do { value = get_dcr (dcrn); printf ("%04x: %08lx", dcrn, value); - nbytes = readline (" ? "); + nbytes = cli_readline(" ? "); if (nbytes == 0) { /* * pressed as only input, don't modify current diff --git a/common/cmd_i2c.c b/common/cmd_i2c.c index 8ccde68..7158b5a 100644 --- a/common/cmd_i2c.c +++ b/common/cmd_i2c.c @@ -613,7 +613,7 @@ mod_i2c_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const arg printf(" %08lx", data); } - nbytes = readline (" ? "); + nbytes = cli_readline(" ? "); if (nbytes == 0) { /* * pressed as only input, don't modify current diff --git a/common/cmd_mem.c b/common/cmd_mem.c index 4b8738b..15a4b84 100644 --- a/common/cmd_mem.c +++ b/common/cmd_mem.c @@ -1150,7 +1150,7 @@ mod_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[]) else printf(" %02x", *((u8 *)ptr)); - nbytes = readline (" ? "); + nbytes = cli_readline(" ? "); if (nbytes == 0 || (nbytes == 1 && console_buffer[0] == '-')) { /* pressed as only input, don't modify current * location and move to next. "-" pressed will go back. diff --git a/common/cmd_nvedit.c b/common/cmd_nvedit.c index a1e98c6..e6c3395 100644 --- a/common/cmd_nvedit.c +++ b/common/cmd_nvedit.c @@ -409,7 +409,7 @@ int do_env_ask(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) return 1; /* prompt for input */ - len = readline(message); + len = cli_readline(message); if (size < len) console_buffer[size] = '\0'; @@ -592,7 +592,7 @@ static int do_env_edit(cmd_tbl_t *cmdtp, int flag, int argc, else buffer[0] = '\0'; - if (readline_into_buffer("edit: ", buffer, 0) < 0) + if (cli_readline_into_buffer("edit: ", buffer, 0) < 0) return 1; return setenv(argv[1], buffer); diff --git a/common/cmd_pci.c b/common/cmd_pci.c index ddda207..1ed55ce 100644 --- a/common/cmd_pci.c +++ b/common/cmd_pci.c @@ -346,7 +346,7 @@ pci_cfg_modify (pci_dev_t bdf, ulong addr, ulong size, ulong value, int incrflag printf(" %02x", val1); } - nbytes = readline (" ? "); + nbytes = cli_readline(" ? "); if (nbytes == 0 || (nbytes == 1 && console_buffer[0] == '-')) { /* pressed as only input, don't modify current * location and move to next. "-" pressed will go back. diff --git a/common/menu.c b/common/menu.c index 88d4697..94afeb2 100644 --- a/common/menu.c +++ b/common/menu.c @@ -197,8 +197,9 @@ static inline int menu_interactive_choice(struct menu *m, void **choice) menu_display(m); if (!m->item_choice) { - readret = readline_into_buffer("Enter choice: ", cbuf, - m->timeout / 10); + readret = cli_readline_into_buffer("Enter choice: ", + cbuf, + m->timeout / 10); if (readret >= 0) { choice_item = menu_item_by_key(m, cbuf); -- cgit v1.1 From 66ded17dfc8110f0d9aa9d50fe140a320bfa4e53 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:28 -0600 Subject: Move autoboot code to autoboot.c The autoboot code is complex and long. It deserves its own file with a simple interface from main.c. Signed-off-by: Simon Glass --- common/Makefile | 5 + common/autoboot.c | 363 +++++++++++++++++++++++++++++++++++++++++++++++++++++ common/main.c | 366 +----------------------------------------------------- 3 files changed, 370 insertions(+), 364 deletions(-) create mode 100644 common/autoboot.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index 7998325..ae79865 100644 --- a/common/Makefile +++ b/common/Makefile @@ -23,6 +23,11 @@ obj-y += s_record.o obj-y += xyzModem.o obj-y += cmd_disk.o +# This option is not just y/n - it can have a numeric value +ifdef CONFIG_BOOTDELAY +obj-y += autoboot.o +endif + # boards obj-$(CONFIG_SYS_GENERIC_BOARD) += board_f.o obj-$(CONFIG_SYS_GENERIC_BOARD) += board_r.o diff --git a/common/autoboot.c b/common/autoboot.c new file mode 100644 index 0000000..6933e3f --- /dev/null +++ b/common/autoboot.c @@ -0,0 +1,363 @@ +/* + * (C) Copyright 2000 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#define MAX_DELAY_STOP_STR 32 + +#ifndef DEBUG_BOOTKEYS +#define DEBUG_BOOTKEYS 0 +#endif +#define debug_bootkeys(fmt, args...) \ + debug_cond(DEBUG_BOOTKEYS, fmt, ##args) + +/*************************************************************************** + * Watch for 'delay' seconds for autoboot stop or autoboot delay string. + * returns: 0 - no key string, allow autoboot 1 - got key string, abort + */ +# if defined(CONFIG_AUTOBOOT_KEYED) +static int abortboot_keyed(int bootdelay) +{ + int abort = 0; + uint64_t etime = endtick(bootdelay); + struct { + char *str; + u_int len; + int retry; + } + delaykey[] = { + { str: getenv("bootdelaykey"), retry: 1 }, + { str: getenv("bootdelaykey2"), retry: 1 }, + { str: getenv("bootstopkey"), retry: 0 }, + { str: getenv("bootstopkey2"), retry: 0 }, + }; + + char presskey[MAX_DELAY_STOP_STR]; + u_int presskey_len = 0; + u_int presskey_max = 0; + u_int i; + +#ifndef CONFIG_ZERO_BOOTDELAY_CHECK + if (bootdelay == 0) + return 0; +#endif + +# ifdef CONFIG_AUTOBOOT_PROMPT + printf(CONFIG_AUTOBOOT_PROMPT); +# endif + +# ifdef CONFIG_AUTOBOOT_DELAY_STR + if (delaykey[0].str == NULL) + delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR; +# endif +# ifdef CONFIG_AUTOBOOT_DELAY_STR2 + if (delaykey[1].str == NULL) + delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2; +# endif +# ifdef CONFIG_AUTOBOOT_STOP_STR + if (delaykey[2].str == NULL) + delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR; +# endif +# ifdef CONFIG_AUTOBOOT_STOP_STR2 + if (delaykey[3].str == NULL) + delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2; +# endif + + for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i++) { + delaykey[i].len = delaykey[i].str == NULL ? + 0 : strlen(delaykey[i].str); + delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ? + MAX_DELAY_STOP_STR : delaykey[i].len; + + presskey_max = presskey_max > delaykey[i].len ? + presskey_max : delaykey[i].len; + + debug_bootkeys("%s key:<%s>\n", + delaykey[i].retry ? "delay" : "stop", + delaykey[i].str ? delaykey[i].str : "NULL"); + } + + /* In order to keep up with incoming data, check timeout only + * when catch up. + */ + do { + if (tstc()) { + if (presskey_len < presskey_max) { + presskey[presskey_len++] = getc(); + } else { + for (i = 0; i < presskey_max - 1; i++) + presskey[i] = presskey[i + 1]; + + presskey[i] = getc(); + } + } + + for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i++) { + if (delaykey[i].len > 0 && + presskey_len >= delaykey[i].len && + memcmp(presskey + presskey_len - + delaykey[i].len, delaykey[i].str, + delaykey[i].len) == 0) { + debug_bootkeys("got %skey\n", + delaykey[i].retry ? "delay" : + "stop"); + +# ifdef CONFIG_BOOT_RETRY_TIME + /* don't retry auto boot */ + if (!delaykey[i].retry) + bootretry_dont_retry(); +# endif + abort = 1; + } + } + } while (!abort && get_ticks() <= etime); + + if (!abort) + debug_bootkeys("key timeout\n"); + +#ifdef CONFIG_SILENT_CONSOLE + if (abort) + gd->flags &= ~GD_FLG_SILENT; +#endif + + return abort; +} + +# else /* !defined(CONFIG_AUTOBOOT_KEYED) */ + +#ifdef CONFIG_MENUKEY +static int menukey; +#endif + +static int abortboot_normal(int bootdelay) +{ + int abort = 0; + unsigned long ts; + +#ifdef CONFIG_MENUPROMPT + printf(CONFIG_MENUPROMPT); +#else + if (bootdelay >= 0) + printf("Hit any key to stop autoboot: %2d ", bootdelay); +#endif + +#if defined CONFIG_ZERO_BOOTDELAY_CHECK + /* + * Check if key already pressed + * Don't check if bootdelay < 0 + */ + if (bootdelay >= 0) { + if (tstc()) { /* we got a key press */ + (void) getc(); /* consume input */ + puts("\b\b\b 0"); + abort = 1; /* don't auto boot */ + } + } +#endif + + while ((bootdelay > 0) && (!abort)) { + --bootdelay; + /* delay 1000 ms */ + ts = get_timer(0); + do { + if (tstc()) { /* we got a key press */ + abort = 1; /* don't auto boot */ + bootdelay = 0; /* no more delay */ +# ifdef CONFIG_MENUKEY + menukey = getc(); +# else + (void) getc(); /* consume input */ +# endif + break; + } + udelay(10000); + } while (!abort && get_timer(ts) < 1000); + + printf("\b\b\b%2d ", bootdelay); + } + + putc('\n'); + +#ifdef CONFIG_SILENT_CONSOLE + if (abort) + gd->flags &= ~GD_FLG_SILENT; +#endif + + return abort; +} +# endif /* CONFIG_AUTOBOOT_KEYED */ + +static int abortboot(int bootdelay) +{ +#ifdef CONFIG_AUTOBOOT_KEYED + return abortboot_keyed(bootdelay); +#else + return abortboot_normal(bootdelay); +#endif +} + +/* + * Runs the given boot command securely. Specifically: + * - Doesn't run the command with the shell (run_command or parse_string_outer), + * since that's a lot of code surface that an attacker might exploit. + * Because of this, we don't do any argument parsing--the secure boot command + * has to be a full-fledged u-boot command. + * - Doesn't check for keypresses before booting, since that could be a + * security hole; also disables Ctrl-C. + * - Doesn't allow the command to return. + * + * Upon any failures, this function will drop into an infinite loop after + * printing the error message to console. + */ + +#if defined(CONFIG_OF_CONTROL) +static void secure_boot_cmd(char *cmd) +{ + cmd_tbl_t *cmdtp; + int rc; + + if (!cmd) { + printf("## Error: Secure boot command not specified\n"); + goto err; + } + + /* Disable Ctrl-C just in case some command is used that checks it. */ + disable_ctrlc(1); + + /* Find the command directly. */ + cmdtp = find_cmd(cmd); + if (!cmdtp) { + printf("## Error: \"%s\" not defined\n", cmd); + goto err; + } + + /* Run the command, forcing no flags and faking argc and argv. */ + rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd); + + /* Shouldn't ever return from boot command. */ + printf("## Error: \"%s\" returned (code %d)\n", cmd, rc); + +err: + /* + * Not a whole lot to do here. Rebooting won't help much, since we'll + * just end up right back here. Just loop. + */ + hang(); +} + +static void process_fdt_options(const void *blob) +{ + ulong addr; + + /* Add an env variable to point to a kernel payload, if available */ + addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0); + if (addr) + setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr)); + + /* Add an env variable to point to a root disk, if available */ + addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0); + if (addr) + setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr)); +} +#endif /* CONFIG_OF_CONTROL */ + +void bootdelay_process(void) +{ +#ifdef CONFIG_OF_CONTROL + char *env; +#endif + char *s; + int bootdelay; +#ifdef CONFIG_BOOTCOUNT_LIMIT + unsigned long bootcount = 0; + unsigned long bootlimit = 0; +#endif /* CONFIG_BOOTCOUNT_LIMIT */ + +#ifdef CONFIG_BOOTCOUNT_LIMIT + bootcount = bootcount_load(); + bootcount++; + bootcount_store(bootcount); + setenv_ulong("bootcount", bootcount); + bootlimit = getenv_ulong("bootlimit", 10, 0); +#endif /* CONFIG_BOOTCOUNT_LIMIT */ + + s = getenv("bootdelay"); + bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY; + +#ifdef CONFIG_OF_CONTROL + bootdelay = fdtdec_get_config_int(gd->fdt_blob, "bootdelay", + bootdelay); +#endif + + debug("### main_loop entered: bootdelay=%d\n\n", bootdelay); + +#if defined(CONFIG_MENU_SHOW) + bootdelay = menu_show(bootdelay); +#endif +# ifdef CONFIG_BOOT_RETRY_TIME + init_cmd_timeout(); +# endif /* CONFIG_BOOT_RETRY_TIME */ + +#ifdef CONFIG_POST + if (gd->flags & GD_FLG_POSTFAIL) { + s = getenv("failbootcmd"); + } else +#endif /* CONFIG_POST */ +#ifdef CONFIG_BOOTCOUNT_LIMIT + if (bootlimit && (bootcount > bootlimit)) { + printf("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n", + (unsigned)bootlimit); + s = getenv("altbootcmd"); + } else +#endif /* CONFIG_BOOTCOUNT_LIMIT */ + s = getenv("bootcmd"); +#ifdef CONFIG_OF_CONTROL + /* Allow the fdt to override the boot command */ + env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd"); + if (env) + s = env; + + process_fdt_options(gd->fdt_blob); + + /* + * If the bootsecure option was chosen, use secure_boot_cmd(). + * Always use 'env' in this case, since bootsecure requres that the + * bootcmd was specified in the FDT too. + */ + if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0)) + secure_boot_cmd(env); + +#endif /* CONFIG_OF_CONTROL */ + + debug("### main_loop: bootcmd=\"%s\"\n", s ? s : ""); + + if (bootdelay != -1 && s && !abortboot(bootdelay)) { +#if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC) + int prev = disable_ctrlc(1); /* disable Control C checking */ +#endif + + run_command_list(s, -1, 0); + +#if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC) + disable_ctrlc(prev); /* restore Control C checking */ +#endif + } + +#ifdef CONFIG_MENUKEY + if (menukey == CONFIG_MENUKEY) { + s = getenv("menucmd"); + if (s) + run_command_list(s, -1, 0); + } +#endif /* CONFIG_MENUKEY */ +} diff --git a/common/main.c b/common/main.c index 88b0adb..19d6f2c 100644 --- a/common/main.c +++ b/common/main.c @@ -8,384 +8,24 @@ /* #define DEBUG */ #include +#include #include #include -#include #include #include -#include -#include #include -DECLARE_GLOBAL_DATA_PTR; - /* * Board-specific Platform code can reimplement show_boot_progress () if needed */ void inline __show_boot_progress (int val) {} void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress"))); -#define MAX_DELAY_STOP_STR 32 - -#ifndef DEBUG_BOOTKEYS -#define DEBUG_BOOTKEYS 0 -#endif -#define debug_bootkeys(fmt, args...) \ - debug_cond(DEBUG_BOOTKEYS, fmt, ##args) - #ifdef CONFIG_MODEM_SUPPORT int do_mdm_init = 0; extern void mdm_init(void); /* defined in board.c */ #endif -/*************************************************************************** - * Watch for 'delay' seconds for autoboot stop or autoboot delay string. - * returns: 0 - no key string, allow autoboot 1 - got key string, abort - */ -#if defined(CONFIG_BOOTDELAY) -# if defined(CONFIG_AUTOBOOT_KEYED) -static int abortboot_keyed(int bootdelay) -{ - int abort = 0; - uint64_t etime = endtick(bootdelay); - struct { - char* str; - u_int len; - int retry; - } - delaykey [] = { - { str: getenv ("bootdelaykey"), retry: 1 }, - { str: getenv ("bootdelaykey2"), retry: 1 }, - { str: getenv ("bootstopkey"), retry: 0 }, - { str: getenv ("bootstopkey2"), retry: 0 }, - }; - - char presskey [MAX_DELAY_STOP_STR]; - u_int presskey_len = 0; - u_int presskey_max = 0; - u_int i; - -#ifndef CONFIG_ZERO_BOOTDELAY_CHECK - if (bootdelay == 0) - return 0; -#endif - -# ifdef CONFIG_AUTOBOOT_PROMPT - printf(CONFIG_AUTOBOOT_PROMPT); -# endif - -# ifdef CONFIG_AUTOBOOT_DELAY_STR - if (delaykey[0].str == NULL) - delaykey[0].str = CONFIG_AUTOBOOT_DELAY_STR; -# endif -# ifdef CONFIG_AUTOBOOT_DELAY_STR2 - if (delaykey[1].str == NULL) - delaykey[1].str = CONFIG_AUTOBOOT_DELAY_STR2; -# endif -# ifdef CONFIG_AUTOBOOT_STOP_STR - if (delaykey[2].str == NULL) - delaykey[2].str = CONFIG_AUTOBOOT_STOP_STR; -# endif -# ifdef CONFIG_AUTOBOOT_STOP_STR2 - if (delaykey[3].str == NULL) - delaykey[3].str = CONFIG_AUTOBOOT_STOP_STR2; -# endif - - for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) { - delaykey[i].len = delaykey[i].str == NULL ? - 0 : strlen (delaykey[i].str); - delaykey[i].len = delaykey[i].len > MAX_DELAY_STOP_STR ? - MAX_DELAY_STOP_STR : delaykey[i].len; - - presskey_max = presskey_max > delaykey[i].len ? - presskey_max : delaykey[i].len; - - debug_bootkeys("%s key:<%s>\n", - delaykey[i].retry ? "delay" : "stop", - delaykey[i].str ? delaykey[i].str : "NULL"); - } - - /* In order to keep up with incoming data, check timeout only - * when catch up. - */ - do { - if (tstc()) { - if (presskey_len < presskey_max) { - presskey [presskey_len ++] = getc(); - } - else { - for (i = 0; i < presskey_max - 1; i ++) - presskey [i] = presskey [i + 1]; - - presskey [i] = getc(); - } - } - - for (i = 0; i < sizeof(delaykey) / sizeof(delaykey[0]); i ++) { - if (delaykey[i].len > 0 && - presskey_len >= delaykey[i].len && - memcmp (presskey + presskey_len - delaykey[i].len, - delaykey[i].str, - delaykey[i].len) == 0) { - debug_bootkeys("got %skey\n", - delaykey[i].retry ? "delay" : - "stop"); - -# ifdef CONFIG_BOOT_RETRY_TIME - /* don't retry auto boot */ - if (! delaykey[i].retry) - bootretry_dont_retry(); -# endif - abort = 1; - } - } - } while (!abort && get_ticks() <= etime); - - if (!abort) - debug_bootkeys("key timeout\n"); - -#ifdef CONFIG_SILENT_CONSOLE - if (abort) - gd->flags &= ~GD_FLG_SILENT; -#endif - - return abort; -} - -# else /* !defined(CONFIG_AUTOBOOT_KEYED) */ - -#ifdef CONFIG_MENUKEY -static int menukey = 0; -#endif - -static int abortboot_normal(int bootdelay) -{ - int abort = 0; - unsigned long ts; - -#ifdef CONFIG_MENUPROMPT - printf(CONFIG_MENUPROMPT); -#else - if (bootdelay >= 0) - printf("Hit any key to stop autoboot: %2d ", bootdelay); -#endif - -#if defined CONFIG_ZERO_BOOTDELAY_CHECK - /* - * Check if key already pressed - * Don't check if bootdelay < 0 - */ - if (bootdelay >= 0) { - if (tstc()) { /* we got a key press */ - (void) getc(); /* consume input */ - puts ("\b\b\b 0"); - abort = 1; /* don't auto boot */ - } - } -#endif - - while ((bootdelay > 0) && (!abort)) { - --bootdelay; - /* delay 1000 ms */ - ts = get_timer(0); - do { - if (tstc()) { /* we got a key press */ - abort = 1; /* don't auto boot */ - bootdelay = 0; /* no more delay */ -# ifdef CONFIG_MENUKEY - menukey = getc(); -# else - (void) getc(); /* consume input */ -# endif - break; - } - udelay(10000); - } while (!abort && get_timer(ts) < 1000); - - printf("\b\b\b%2d ", bootdelay); - } - - putc('\n'); - -#ifdef CONFIG_SILENT_CONSOLE - if (abort) - gd->flags &= ~GD_FLG_SILENT; -#endif - - return abort; -} -# endif /* CONFIG_AUTOBOOT_KEYED */ - -static int abortboot(int bootdelay) -{ -#ifdef CONFIG_AUTOBOOT_KEYED - return abortboot_keyed(bootdelay); -#else - return abortboot_normal(bootdelay); -#endif -} -#endif /* CONFIG_BOOTDELAY */ - -/* - * Runs the given boot command securely. Specifically: - * - Doesn't run the command with the shell (run_command or parse_string_outer), - * since that's a lot of code surface that an attacker might exploit. - * Because of this, we don't do any argument parsing--the secure boot command - * has to be a full-fledged u-boot command. - * - Doesn't check for keypresses before booting, since that could be a - * security hole; also disables Ctrl-C. - * - Doesn't allow the command to return. - * - * Upon any failures, this function will drop into an infinite loop after - * printing the error message to console. - */ - -#if defined(CONFIG_BOOTDELAY) && defined(CONFIG_OF_CONTROL) -static void secure_boot_cmd(char *cmd) -{ - cmd_tbl_t *cmdtp; - int rc; - - if (!cmd) { - printf("## Error: Secure boot command not specified\n"); - goto err; - } - - /* Disable Ctrl-C just in case some command is used that checks it. */ - disable_ctrlc(1); - - /* Find the command directly. */ - cmdtp = find_cmd(cmd); - if (!cmdtp) { - printf("## Error: \"%s\" not defined\n", cmd); - goto err; - } - - /* Run the command, forcing no flags and faking argc and argv. */ - rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd); - - /* Shouldn't ever return from boot command. */ - printf("## Error: \"%s\" returned (code %d)\n", cmd, rc); - -err: - /* - * Not a whole lot to do here. Rebooting won't help much, since we'll - * just end up right back here. Just loop. - */ - hang(); -} - -static void process_fdt_options(const void *blob) -{ - ulong addr; - - /* Add an env variable to point to a kernel payload, if available */ - addr = fdtdec_get_config_int(gd->fdt_blob, "kernel-offset", 0); - if (addr) - setenv_addr("kernaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr)); - - /* Add an env variable to point to a root disk, if available */ - addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0); - if (addr) - setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr)); -} -#endif /* CONFIG_OF_CONTROL */ - -#ifdef CONFIG_BOOTDELAY -static void process_boot_delay(void) -{ -#ifdef CONFIG_OF_CONTROL - char *env; -#endif - char *s; - int bootdelay; -#ifdef CONFIG_BOOTCOUNT_LIMIT - unsigned long bootcount = 0; - unsigned long bootlimit = 0; -#endif /* CONFIG_BOOTCOUNT_LIMIT */ - -#ifdef CONFIG_BOOTCOUNT_LIMIT - bootcount = bootcount_load(); - bootcount++; - bootcount_store (bootcount); - setenv_ulong("bootcount", bootcount); - bootlimit = getenv_ulong("bootlimit", 10, 0); -#endif /* CONFIG_BOOTCOUNT_LIMIT */ - - s = getenv ("bootdelay"); - bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY; - -#ifdef CONFIG_OF_CONTROL - bootdelay = fdtdec_get_config_int(gd->fdt_blob, "bootdelay", - bootdelay); -#endif - - debug ("### main_loop entered: bootdelay=%d\n\n", bootdelay); - -#if defined(CONFIG_MENU_SHOW) - bootdelay = menu_show(bootdelay); -#endif -# ifdef CONFIG_BOOT_RETRY_TIME - init_cmd_timeout (); -# endif /* CONFIG_BOOT_RETRY_TIME */ - -#ifdef CONFIG_POST - if (gd->flags & GD_FLG_POSTFAIL) { - s = getenv("failbootcmd"); - } - else -#endif /* CONFIG_POST */ -#ifdef CONFIG_BOOTCOUNT_LIMIT - if (bootlimit && (bootcount > bootlimit)) { - printf ("Warning: Bootlimit (%u) exceeded. Using altbootcmd.\n", - (unsigned)bootlimit); - s = getenv ("altbootcmd"); - } - else -#endif /* CONFIG_BOOTCOUNT_LIMIT */ - s = getenv ("bootcmd"); -#ifdef CONFIG_OF_CONTROL - /* Allow the fdt to override the boot command */ - env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd"); - if (env) - s = env; - - process_fdt_options(gd->fdt_blob); - - /* - * If the bootsecure option was chosen, use secure_boot_cmd(). - * Always use 'env' in this case, since bootsecure requres that the - * bootcmd was specified in the FDT too. - */ - if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0)) - secure_boot_cmd(env); - -#endif /* CONFIG_OF_CONTROL */ - - debug ("### main_loop: bootcmd=\"%s\"\n", s ? s : ""); - - if (bootdelay != -1 && s && !abortboot(bootdelay)) { -#if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC) - int prev = disable_ctrlc(1); /* disable Control C checking */ -#endif - - run_command_list(s, -1, 0); - -#if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC) - disable_ctrlc(prev); /* restore Control C checking */ -#endif - } - -#ifdef CONFIG_MENUKEY - if (menukey == CONFIG_MENUKEY) { - s = getenv("menucmd"); - if (s) - run_command_list(s, -1, 0); - } -#endif /* CONFIG_MENUKEY */ -} -#endif /* CONFIG_BOOTDELAY */ - void main_loop(void) { #ifdef CONFIG_PREBOOT @@ -444,9 +84,7 @@ void main_loop(void) update_tftp(0UL); #endif /* CONFIG_UPDATE_TFTP */ -#ifdef CONFIG_BOOTDELAY - process_boot_delay(); -#endif + bootdelay_process(); /* * Main Loop for Monitor Command Processing */ -- cgit v1.1 From 30354978ff470470c15caea2566b61b5792ad277 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:29 -0600 Subject: Move command line API into cli.c We now have a single entry point to the CLI, whether simple or hush. Put this in its own file. Signed-off-by: Simon Glass --- common/Makefile | 1 + common/cli.c | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ common/main.c | 93 ------------------------------------------------- 3 files changed, 107 insertions(+), 93 deletions(-) create mode 100644 common/cli.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index ae79865..81721f9 100644 --- a/common/Makefile +++ b/common/Makefile @@ -18,6 +18,7 @@ endif # We always have this since drivers/ddr/fs/interactive.c needs it obj-y += cli_simple.o +obj-y += cli.o obj-y += cli_readline.o obj-y += s_record.o obj-y += xyzModem.o diff --git a/common/cli.c b/common/cli.c new file mode 100644 index 0000000..9cf7ba1 --- /dev/null +++ b/common/cli.c @@ -0,0 +1,106 @@ +/* + * (C) Copyright 2000 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * Add to readline cmdline-editing by + * (C) Copyright 2005 + * JinHua Luo, GuangDong Linux Center, + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include + +/* + * Run a command using the selected parser. + * + * @param cmd Command to run + * @param flag Execution flags (CMD_FLAG_...) + * @return 0 on success, or != 0 on error. + */ +int run_command(const char *cmd, int flag) +{ +#ifndef CONFIG_SYS_HUSH_PARSER + /* + * cli_run_command can return 0 or 1 for success, so clean up + * its result. + */ + if (cli_simple_run_command(cmd, flag) == -1) + return 1; + + return 0; +#else + return parse_string_outer(cmd, + FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP); +#endif +} + +int run_command_list(const char *cmd, int len, int flag) +{ + int need_buff = 1; + char *buff = (char *)cmd; /* cast away const */ + int rcode = 0; + + if (len == -1) { + len = strlen(cmd); +#ifdef CONFIG_SYS_HUSH_PARSER + /* hush will never change our string */ + need_buff = 0; +#else + /* the built-in parser will change our string if it sees \n */ + need_buff = strchr(cmd, '\n') != NULL; +#endif + } + if (need_buff) { + buff = malloc(len + 1); + if (!buff) + return 1; + memcpy(buff, cmd, len); + buff[len] = '\0'; + } +#ifdef CONFIG_SYS_HUSH_PARSER + rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON); +#else + /* + * This function will overwrite any \n it sees with a \0, which + * is why it can't work with a const char *. Here we are making + * using of internal knowledge of this function, to avoid always + * doing a malloc() which is actually required only in a case that + * is pretty rare. + */ + rcode = cli_simple_run_command_list(buff, flag); + if (need_buff) + free(buff); +#endif + + return rcode; +} + +/****************************************************************************/ + +#if defined(CONFIG_CMD_RUN) +int do_run(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + int i; + + if (argc < 2) + return CMD_RET_USAGE; + + for (i = 1; i < argc; ++i) { + char *arg; + + arg = getenv(argv[i]); + if (arg == NULL) { + printf("## Error: \"%s\" not defined\n", argv[i]); + return 1; + } + + if (run_command(arg, flag) != 0) + return 1; + } + return 0; +} +#endif diff --git a/common/main.c b/common/main.c index 19d6f2c..c4ed846 100644 --- a/common/main.c +++ b/common/main.c @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -96,95 +95,3 @@ void main_loop(void) cli_loop(); #endif /*CONFIG_SYS_HUSH_PARSER*/ } - -/****************************************************************************/ - -/* - * Run a command using the selected parser. - * - * @param cmd Command to run - * @param flag Execution flags (CMD_FLAG_...) - * @return 0 on success, or != 0 on error. - */ -int run_command(const char *cmd, int flag) -{ -#ifndef CONFIG_SYS_HUSH_PARSER - /* - * cli_run_command can return 0 or 1 for success, so clean up - * its result. - */ - if (cli_simple_run_command(cmd, flag) == -1) - return 1; - - return 0; -#else - return parse_string_outer(cmd, - FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP); -#endif -} - -int run_command_list(const char *cmd, int len, int flag) -{ - int need_buff = 1; - char *buff = (char *)cmd; /* cast away const */ - int rcode = 0; - - if (len == -1) { - len = strlen(cmd); -#ifdef CONFIG_SYS_HUSH_PARSER - /* hush will never change our string */ - need_buff = 0; -#else - /* the built-in parser will change our string if it sees \n */ - need_buff = strchr(cmd, '\n') != NULL; -#endif - } - if (need_buff) { - buff = malloc(len + 1); - if (!buff) - return 1; - memcpy(buff, cmd, len); - buff[len] = '\0'; - } -#ifdef CONFIG_SYS_HUSH_PARSER - rcode = parse_string_outer(buff, FLAG_PARSE_SEMICOLON); -#else - /* - * This function will overwrite any \n it sees with a \0, which - * is why it can't work with a const char *. Here we are making - * using of internal knowledge of this function, to avoid always - * doing a malloc() which is actually required only in a case that - * is pretty rare. - */ - rcode = cli_simple_run_command_list(buff, flag); - if (need_buff) - free(buff); -#endif - - return rcode; -} - -/****************************************************************************/ - -#if defined(CONFIG_CMD_RUN) -int do_run (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) -{ - int i; - - if (argc < 2) - return CMD_RET_USAGE; - - for (i=1; i Date: Thu, 10 Apr 2014 20:01:30 -0600 Subject: Move bootretry code into bootretry.c and clean up This code is only used by one board, so it seems a shame to clutter up the readline code with it. Move it into its own file. Signed-off-by: Simon Glass --- common/Makefile | 5 +++++ common/autoboot.c | 1 + common/bootretry.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ common/cli_hush.c | 1 + common/cli_readline.c | 60 +++++---------------------------------------------- common/cli_simple.c | 1 + common/cmd_i2c.c | 1 + common/cmd_mem.c | 1 + common/cmd_pci.c | 1 + 9 files changed, 75 insertions(+), 55 deletions(-) create mode 100644 common/bootretry.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index 81721f9..391a8d6 100644 --- a/common/Makefile +++ b/common/Makefile @@ -29,6 +29,11 @@ ifdef CONFIG_BOOTDELAY obj-y += autoboot.o endif +# This option is not just y/n - it can have a numeric value +ifdef CONFIG_BOOT_RETRY_TIME +obj-y += bootretry.o +endif + # boards obj-$(CONFIG_SYS_GENERIC_BOARD) += board_f.o obj-$(CONFIG_SYS_GENERIC_BOARD) += board_r.o diff --git a/common/autoboot.c b/common/autoboot.c index 6933e3f..5f8d9c3 100644 --- a/common/autoboot.c +++ b/common/autoboot.c @@ -6,6 +6,7 @@ */ #include +#include #include #include #include diff --git a/common/bootretry.c b/common/bootretry.c new file mode 100644 index 0000000..12653c0 --- /dev/null +++ b/common/bootretry.c @@ -0,0 +1,59 @@ +/* + * (C) Copyright 2000 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include + +#ifndef CONFIG_BOOT_RETRY_MIN +#define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME +#endif + +static uint64_t endtime; /* must be set, default is instant timeout */ +static int retry_time = -1; /* -1 so can call readline before main_loop */ + +/*************************************************************************** + * initialize command line timeout + */ +void init_cmd_timeout(void) +{ + char *s = getenv("bootretry"); + + if (s != NULL) + retry_time = (int)simple_strtol(s, NULL, 10); + else + retry_time = CONFIG_BOOT_RETRY_TIME; + + if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN) + retry_time = CONFIG_BOOT_RETRY_MIN; +} + +/*************************************************************************** + * reset command line timeout to retry_time seconds + */ +void reset_cmd_timeout(void) +{ + endtime = endtick(retry_time); +} + +int bootretry_tstc_timeout(void) +{ + while (!tstc()) { /* while no incoming data */ + if (retry_time >= 0 && get_ticks() > endtime) + return -ETIMEDOUT; + WATCHDOG_RESET(); + } + + return 0; +} + +void bootretry_dont_retry(void) +{ + retry_time = -1; +} diff --git a/common/cli_hush.c b/common/cli_hush.c index a612bfb..d6544ae 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -79,6 +79,7 @@ #include /* malloc, free, realloc*/ #include /* isalpha, isdigit */ #include /* readline */ +#include #include #include #include /* find_cmd */ diff --git a/common/cli_readline.c b/common/cli_readline.c index df446b8..9a9fb35 100644 --- a/common/cli_readline.c +++ b/common/cli_readline.c @@ -10,6 +10,7 @@ */ #include +#include #include #include @@ -18,17 +19,8 @@ DECLARE_GLOBAL_DATA_PTR; static const char erase_seq[] = "\b \b"; /* erase sequence */ static const char tab_seq[] = " "; /* used to expand TABs */ -#ifdef CONFIG_BOOT_RETRY_TIME -static uint64_t endtime; /* must be set, default is instant timeout */ -static int retry_time = -1; /* -1 so can call readline before main_loop */ -#endif - char console_buffer[CONFIG_SYS_CBSIZE + 1]; /* console I/O buffer */ -#ifndef CONFIG_BOOT_RETRY_MIN -#define CONFIG_BOOT_RETRY_MIN CONFIG_BOOT_RETRY_TIME -#endif - static char *delete_char (char *buffer, char *p, int *colp, int *np, int plen) { char *s; @@ -267,13 +259,8 @@ static int cread_line(const char *const prompt, char *buf, unsigned int *len, cread_add_str(buf, init_len, 1, &num, &eol_num, buf, *len); while (1) { -#ifdef CONFIG_BOOT_RETRY_TIME - while (!tstc()) { /* while no incoming data */ - if (retry_time >= 0 && get_ticks() > endtime) - return -2; /* timed out */ - WATCHDOG_RESET(); - } -#endif + if (bootretry_tstc_timeout()) + return -2; /* timed out */ if (first && timeout) { uint64_t etime = endtick(timeout); @@ -539,13 +526,8 @@ int cli_readline_into_buffer(const char *const prompt, char *buffer, col = plen; for (;;) { -#ifdef CONFIG_BOOT_RETRY_TIME - while (!tstc()) { /* while no incoming data */ - if (retry_time >= 0 && get_ticks() > endtime) - return -2; /* timed out */ - WATCHDOG_RESET(); - } -#endif + if (bootretry_tstc_timeout()) + return -2; /* timed out */ WATCHDOG_RESET(); /* Trigger watchdog, if needed */ #ifdef CONFIG_SHOW_ACTIVITY @@ -637,35 +619,3 @@ int cli_readline_into_buffer(const char *const prompt, char *buffer, } #endif } - -#ifdef CONFIG_BOOT_RETRY_TIME -/*************************************************************************** - * initialize command line timeout - */ -void init_cmd_timeout(void) -{ - char *s = getenv("bootretry"); - - if (s != NULL) - retry_time = (int)simple_strtol(s, NULL, 10); - else - retry_time = CONFIG_BOOT_RETRY_TIME; - - if (retry_time >= 0 && retry_time < CONFIG_BOOT_RETRY_MIN) - retry_time = CONFIG_BOOT_RETRY_MIN; -} - -/*************************************************************************** - * reset command line timeout to retry_time seconds - */ -void reset_cmd_timeout(void) -{ - endtime = endtick(retry_time); -} - -void bootretry_dont_retry(void) -{ - retry_time = -1; -} - -#endif diff --git a/common/cli_simple.c b/common/cli_simple.c index 3039cfc..5b7e2ce 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -10,6 +10,7 @@ */ #include +#include #include #include diff --git a/common/cmd_i2c.c b/common/cmd_i2c.c index 7158b5a..4fa1213 100644 --- a/common/cmd_i2c.c +++ b/common/cmd_i2c.c @@ -66,6 +66,7 @@ */ #include +#include #include #include #include diff --git a/common/cmd_mem.c b/common/cmd_mem.c index 15a4b84..9bd7c0e 100644 --- a/common/cmd_mem.c +++ b/common/cmd_mem.c @@ -12,6 +12,7 @@ */ #include +#include #include #include #ifdef CONFIG_HAS_DATAFLASH diff --git a/common/cmd_pci.c b/common/cmd_pci.c index 1ed55ce..180b35a 100644 --- a/common/cmd_pci.c +++ b/common/cmd_pci.c @@ -14,6 +14,7 @@ */ #include +#include #include #include #include -- cgit v1.1 From b26440f1fa243396000536028ea00e5e185b6b6a Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:31 -0600 Subject: Rename bootretry functions and remove #ifdefs Add a bootretry_ prefix to these two functions, and remove the need for the #ifdef around everything (it moves to the Makefile). Signed-off-by: Simon Glass --- common/autoboot.c | 6 +----- common/bootretry.c | 4 ++-- common/cli_hush.c | 7 +------ common/cli_simple.c | 4 +--- common/cmd_i2c.c | 13 ++++--------- common/cmd_mem.c | 13 ++++--------- common/cmd_pci.c | 9 +++------ 7 files changed, 16 insertions(+), 40 deletions(-) (limited to 'common') diff --git a/common/autoboot.c b/common/autoboot.c index 5f8d9c3..9843898 100644 --- a/common/autoboot.c +++ b/common/autoboot.c @@ -113,11 +113,9 @@ static int abortboot_keyed(int bootdelay) delaykey[i].retry ? "delay" : "stop"); -# ifdef CONFIG_BOOT_RETRY_TIME /* don't retry auto boot */ if (!delaykey[i].retry) bootretry_dont_retry(); -# endif abort = 1; } } @@ -305,9 +303,7 @@ void bootdelay_process(void) #if defined(CONFIG_MENU_SHOW) bootdelay = menu_show(bootdelay); #endif -# ifdef CONFIG_BOOT_RETRY_TIME - init_cmd_timeout(); -# endif /* CONFIG_BOOT_RETRY_TIME */ + bootretry_init_cmd_timeout(); #ifdef CONFIG_POST if (gd->flags & GD_FLG_POSTFAIL) { diff --git a/common/bootretry.c b/common/bootretry.c index 12653c0..2d82798 100644 --- a/common/bootretry.c +++ b/common/bootretry.c @@ -21,7 +21,7 @@ static int retry_time = -1; /* -1 so can call readline before main_loop */ /*************************************************************************** * initialize command line timeout */ -void init_cmd_timeout(void) +void bootretry_init_cmd_timeout(void) { char *s = getenv("bootretry"); @@ -37,7 +37,7 @@ void init_cmd_timeout(void) /*************************************************************************** * reset command line timeout to retry_time seconds */ -void reset_cmd_timeout(void) +void bootretry_reset_cmd_timeout(void) { endtime = endtick(retry_time); } diff --git a/common/cli_hush.c b/common/cli_hush.c index d6544ae..0f069b0 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -1000,12 +1000,7 @@ static void get_user_input(struct in_str *i) int n; static char the_command[CONFIG_SYS_CBSIZE + 1]; -#ifdef CONFIG_BOOT_RETRY_TIME -# ifndef CONFIG_RESET_TO_RETRY -# error "This currently only works with CONFIG_RESET_TO_RETRY enabled" -# endif - reset_cmd_timeout(); -#endif + bootretry_reset_cmd_timeout(); i->__promptme = 1; if (i->promptmode == 1) { n = cli_readline(CONFIG_SYS_PROMPT); diff --git a/common/cli_simple.c b/common/cli_simple.c index 5b7e2ce..bba586e 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -265,14 +265,12 @@ void cli_loop(void) int rc = 1; for (;;) { -#ifdef CONFIG_BOOT_RETRY_TIME if (rc >= 0) { /* Saw enough of a valid command to * restart the timeout. */ - reset_cmd_timeout(); + bootretry_reset_cmd_timeout(); } -#endif len = cli_readline(CONFIG_SYS_PROMPT); flag = 0; /* assume no special flags for now */ diff --git a/common/cmd_i2c.c b/common/cmd_i2c.c index 4fa1213..d714658 100644 --- a/common/cmd_i2c.c +++ b/common/cmd_i2c.c @@ -564,9 +564,7 @@ mod_i2c_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const arg if (argc != 3) return CMD_RET_USAGE; -#ifdef CONFIG_BOOT_RETRY_TIME - reset_cmd_timeout(); /* got a good command to get here */ -#endif + bootretry_reset_cmd_timeout(); /* got a good command to get here */ /* * We use the last specified parameters, unless new ones are * entered. @@ -623,9 +621,8 @@ mod_i2c_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const arg if (incrflag) addr += size; nbytes = size; -#ifdef CONFIG_BOOT_RETRY_TIME - reset_cmd_timeout(); /* good enough to not time out */ -#endif + /* good enough to not time out */ + bootretry_reset_cmd_timeout(); } #ifdef CONFIG_BOOT_RETRY_TIME else if (nbytes == -2) @@ -642,12 +639,10 @@ mod_i2c_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const arg data = be32_to_cpu(data); nbytes = endp - console_buffer; if (nbytes) { -#ifdef CONFIG_BOOT_RETRY_TIME /* * good enough to not time out */ - reset_cmd_timeout(); -#endif + bootretry_reset_cmd_timeout(); if (i2c_write(chip, addr, alen, (uchar *)&data, size) != 0) puts ("Error writing the chip.\n"); #ifdef CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS diff --git a/common/cmd_mem.c b/common/cmd_mem.c index 9bd7c0e..1febddb 100644 --- a/common/cmd_mem.c +++ b/common/cmd_mem.c @@ -1098,9 +1098,7 @@ mod_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[]) if (argc != 2) return CMD_RET_USAGE; -#ifdef CONFIG_BOOT_RETRY_TIME - reset_cmd_timeout(); /* got a good command to get here */ -#endif + bootretry_reset_cmd_timeout(); /* got a good command to get here */ /* We use the last specified parameters, unless new ones are * entered. */ @@ -1159,9 +1157,8 @@ mod_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[]) if (incrflag) addr += nbytes ? -size : size; nbytes = 1; -#ifdef CONFIG_BOOT_RETRY_TIME - reset_cmd_timeout(); /* good enough to not time out */ -#endif + /* good enough to not time out */ + bootretry_reset_cmd_timeout(); } #ifdef CONFIG_BOOT_RETRY_TIME else if (nbytes == -2) { @@ -1177,11 +1174,9 @@ mod_mem(cmd_tbl_t *cmdtp, int incrflag, int flag, int argc, char * const argv[]) #endif nbytes = endp - console_buffer; if (nbytes) { -#ifdef CONFIG_BOOT_RETRY_TIME /* good enough to not time out */ - reset_cmd_timeout(); -#endif + bootretry_reset_cmd_timeout(); if (size == 4) *((u32 *)ptr) = i; #ifdef CONFIG_SYS_SUPPORT_64BIT_DATA diff --git a/common/cmd_pci.c b/common/cmd_pci.c index 180b35a..a1ba42e 100644 --- a/common/cmd_pci.c +++ b/common/cmd_pci.c @@ -355,9 +355,8 @@ pci_cfg_modify (pci_dev_t bdf, ulong addr, ulong size, ulong value, int incrflag if (incrflag) addr += nbytes ? -size : size; nbytes = 1; -#ifdef CONFIG_BOOT_RETRY_TIME - reset_cmd_timeout(); /* good enough to not time out */ -#endif + /* good enough to not time out */ + bootretry_reset_cmd_timeout(); } #ifdef CONFIG_BOOT_RETRY_TIME else if (nbytes == -2) { @@ -369,11 +368,9 @@ pci_cfg_modify (pci_dev_t bdf, ulong addr, ulong size, ulong value, int incrflag i = simple_strtoul(console_buffer, &endp, 16); nbytes = endp - console_buffer; if (nbytes) { -#ifdef CONFIG_BOOT_RETRY_TIME /* good enough to not time out */ - reset_cmd_timeout(); -#endif + bootretry_reset_cmd_timeout(); pci_cfg_write (bdf, addr, size, i); if (incrflag) addr += size; -- cgit v1.1 From 9272a9b4f637347267329c7dc48712ea6c31feaa Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:32 -0600 Subject: m68k: powerpc: Clean up do_mdm_init This code seems unnecessarily complex. We really just need to check the global_data. Now that is it all in one place, and not arch-specific, this is pretty easy. Signed-off-by: Simon Glass --- common/board_r.c | 14 -------------- common/main.c | 11 ++++------- 2 files changed, 4 insertions(+), 21 deletions(-) (limited to 'common') diff --git a/common/board_r.c b/common/board_r.c index d1f0aa9..602a239 100644 --- a/common/board_r.c +++ b/common/board_r.c @@ -704,17 +704,6 @@ static int initr_kbd(void) } #endif -#ifdef CONFIG_MODEM_SUPPORT -static int initr_modem(void) -{ - /* TODO: with new initcalls, move this into the driver */ - extern int do_mdm_init; - - do_mdm_init = gd->do_mdm_init; - return 0; -} -#endif - static int run_main_loop(void) { #ifdef CONFIG_SANDBOX @@ -929,9 +918,6 @@ init_fnc_t init_sequence_r[] = { #ifdef CONFIG_PS2KBD initr_kbd, #endif -#ifdef CONFIG_MODEM_SUPPORT - initr_modem, -#endif run_main_loop, }; diff --git a/common/main.c b/common/main.c index c4ed846..e3e9f84 100644 --- a/common/main.c +++ b/common/main.c @@ -14,17 +14,14 @@ #include #include +DECLARE_GLOBAL_DATA_PTR; + /* * Board-specific Platform code can reimplement show_boot_progress () if needed */ void inline __show_boot_progress (int val) {} void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress"))); -#ifdef CONFIG_MODEM_SUPPORT -int do_mdm_init = 0; -extern void mdm_init(void); /* defined in board.c */ -#endif - void main_loop(void) { #ifdef CONFIG_PREBOOT @@ -40,8 +37,8 @@ void main_loop(void) #endif #ifdef CONFIG_MODEM_SUPPORT - debug("DEBUG: main_loop: do_mdm_init=%d\n", do_mdm_init); - if (do_mdm_init) { + debug("DEBUG: main_loop: gd->do_mdm_init=%lu\n", gd->do_mdm_init); + if (gd->do_mdm_init) { char *str = strdup(getenv("mdm_cmd")); setenv("preboot", str); /* set or delete definition */ if (str != NULL) -- cgit v1.1 From 1364a0e48a64a29930a8b22620f420e8f4984cc7 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:33 -0600 Subject: Simplify the main loop The main loop is easier to follow if the code is grouped into separate functions. Make this change, so that main_loop() is easier to read. Signed-off-by: Simon Glass --- common/main.c | 59 ++++++++++++++++++++++++++++++++--------------------------- 1 file changed, 32 insertions(+), 27 deletions(-) (limited to 'common') diff --git a/common/main.c b/common/main.c index e3e9f84..b4cf289 100644 --- a/common/main.c +++ b/common/main.c @@ -22,20 +22,8 @@ DECLARE_GLOBAL_DATA_PTR; void inline __show_boot_progress (int val) {} void show_boot_progress (int val) __attribute__((weak, alias("__show_boot_progress"))); -void main_loop(void) +static void modem_init(void) { -#ifdef CONFIG_PREBOOT - char *p; -#endif - - bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop"); - -#ifndef CONFIG_SYS_GENERIC_BOARD - puts("Warning: Your board does not use generic board. Please read\n"); - puts("doc/README.generic-board and take action. Boards not\n"); - puts("upgraded by the late 2014 may break or be removed.\n"); -#endif - #ifdef CONFIG_MODEM_SUPPORT debug("DEBUG: main_loop: gd->do_mdm_init=%lu\n", gd->do_mdm_init); if (gd->do_mdm_init) { @@ -46,22 +34,13 @@ void main_loop(void) mdm_init(); /* wait for modem connection */ } #endif /* CONFIG_MODEM_SUPPORT */ +} -#ifdef CONFIG_VERSION_VARIABLE - { - setenv("ver", version_string); /* set version variable */ - } -#endif /* CONFIG_VERSION_VARIABLE */ - -#ifdef CONFIG_SYS_HUSH_PARSER - u_boot_hush_start(); -#endif - -#if defined(CONFIG_HUSH_INIT_VAR) - hush_init_var(); -#endif - +static void run_preboot_environment_command(void) +{ #ifdef CONFIG_PREBOOT + char *p; + p = getenv("preboot"); if (p != NULL) { # ifdef CONFIG_AUTOBOOT_KEYED @@ -75,6 +54,32 @@ void main_loop(void) # endif } #endif /* CONFIG_PREBOOT */ +} + +void main_loop(void) +{ + bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop"); + +#ifndef CONFIG_SYS_GENERIC_BOARD + puts("Warning: Your board does not use generic board. Please read\n"); + puts("doc/README.generic-board and take action. Boards not\n"); + puts("upgraded by the late 2014 may break or be removed.\n"); +#endif + + modem_init(); +#ifdef CONFIG_VERSION_VARIABLE + setenv("ver", version_string); /* set version variable */ +#endif /* CONFIG_VERSION_VARIABLE */ + +#ifdef CONFIG_SYS_HUSH_PARSER + u_boot_hush_start(); +#endif + +#if defined(CONFIG_HUSH_INIT_VAR) + hush_init_var(); +#endif + + run_preboot_environment_command(); #if defined(CONFIG_UPDATE_TFTP) update_tftp(0UL); -- cgit v1.1 From c1bb2cd0b6a3d1b152be3686601234b3a363772b Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:34 -0600 Subject: main: Hide the hush/simple details inside cli.c Move these details from main (which doesn't care which parser is used) to cli.c where they belong. Signed-off-by: Simon Glass --- common/cli.c | 22 ++++++++++++++++++++++ common/cli_simple.c | 2 +- common/main.c | 16 ++-------------- 3 files changed, 25 insertions(+), 15 deletions(-) (limited to 'common') diff --git a/common/cli.c b/common/cli.c index 9cf7ba1..4ac9b3f 100644 --- a/common/cli.c +++ b/common/cli.c @@ -104,3 +104,25 @@ int do_run(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) return 0; } #endif + +void cli_loop(void) +{ +#ifdef CONFIG_SYS_HUSH_PARSER + parse_file_outer(); + /* This point is never reached */ + for (;;); +#else + cli_simple_loop(); +#endif /*CONFIG_SYS_HUSH_PARSER*/ +} + +void cli_init(void) +{ +#ifdef CONFIG_SYS_HUSH_PARSER + u_boot_hush_start(); +#endif + +#if defined(CONFIG_HUSH_INIT_VAR) + hush_init_var(); +#endif +} diff --git a/common/cli_simple.c b/common/cli_simple.c index bba586e..413c2eb 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -256,7 +256,7 @@ int cli_simple_run_command(const char *cmd, int flag) return rc ? rc : repeatable; } -void cli_loop(void) +void cli_simple_loop(void) { static char lastcommand[CONFIG_SYS_CBSIZE] = { 0, }; diff --git a/common/main.c b/common/main.c index b4cf289..8c846c8 100644 --- a/common/main.c +++ b/common/main.c @@ -10,7 +10,6 @@ #include #include #include -#include #include #include @@ -71,13 +70,7 @@ void main_loop(void) setenv("ver", version_string); /* set version variable */ #endif /* CONFIG_VERSION_VARIABLE */ -#ifdef CONFIG_SYS_HUSH_PARSER - u_boot_hush_start(); -#endif - -#if defined(CONFIG_HUSH_INIT_VAR) - hush_init_var(); -#endif + cli_init(); run_preboot_environment_command(); @@ -89,11 +82,6 @@ void main_loop(void) /* * Main Loop for Monitor Command Processing */ -#ifdef CONFIG_SYS_HUSH_PARSER - parse_file_outer(); - /* This point is never reached */ - for (;;); -#else + cli_loop(); -#endif /*CONFIG_SYS_HUSH_PARSER*/ } -- cgit v1.1 From affb215626f91e717088a27081d24c473895d47d Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:35 -0600 Subject: main: Make the execution path a little clearer in main.c bootdelay_process() never returns in some circumstances, whichs makes the control flow confusing. Change it so that the decision about how to execute the boot command is made in the main_loop() code, so it is easier to follow. Move CLI stuff to cli.c. Signed-off-by: Simon Glass --- common/autoboot.c | 81 +++++++++---------------------------------------------- common/cli.c | 66 +++++++++++++++++++++++++++++++++++++++++++++ common/main.c | 12 ++++++--- 3 files changed, 86 insertions(+), 73 deletions(-) (limited to 'common') diff --git a/common/autoboot.c b/common/autoboot.c index 9843898..dc24cae 100644 --- a/common/autoboot.c +++ b/common/autoboot.c @@ -22,6 +22,9 @@ DECLARE_GLOBAL_DATA_PTR; #define debug_bootkeys(fmt, args...) \ debug_cond(DEBUG_BOOTKEYS, fmt, ##args) +/* Stored value of bootdelay, used by autoboot_command() */ +static int stored_bootdelay; + /*************************************************************************** * Watch for 'delay' seconds for autoboot stop or autoboot delay string. * returns: 0 - no key string, allow autoboot 1 - got key string, abort @@ -205,57 +208,9 @@ static int abortboot(int bootdelay) #endif } -/* - * Runs the given boot command securely. Specifically: - * - Doesn't run the command with the shell (run_command or parse_string_outer), - * since that's a lot of code surface that an attacker might exploit. - * Because of this, we don't do any argument parsing--the secure boot command - * has to be a full-fledged u-boot command. - * - Doesn't check for keypresses before booting, since that could be a - * security hole; also disables Ctrl-C. - * - Doesn't allow the command to return. - * - * Upon any failures, this function will drop into an infinite loop after - * printing the error message to console. - */ - -#if defined(CONFIG_OF_CONTROL) -static void secure_boot_cmd(char *cmd) -{ - cmd_tbl_t *cmdtp; - int rc; - - if (!cmd) { - printf("## Error: Secure boot command not specified\n"); - goto err; - } - - /* Disable Ctrl-C just in case some command is used that checks it. */ - disable_ctrlc(1); - - /* Find the command directly. */ - cmdtp = find_cmd(cmd); - if (!cmdtp) { - printf("## Error: \"%s\" not defined\n", cmd); - goto err; - } - - /* Run the command, forcing no flags and faking argc and argv. */ - rc = (cmdtp->cmd)(cmdtp, 0, 1, &cmd); - - /* Shouldn't ever return from boot command. */ - printf("## Error: \"%s\" returned (code %d)\n", cmd, rc); - -err: - /* - * Not a whole lot to do here. Rebooting won't help much, since we'll - * just end up right back here. Just loop. - */ - hang(); -} - static void process_fdt_options(const void *blob) { +#if defined(CONFIG_OF_CONTROL) ulong addr; /* Add an env variable to point to a kernel payload, if available */ @@ -267,14 +222,11 @@ static void process_fdt_options(const void *blob) addr = fdtdec_get_config_int(gd->fdt_blob, "rootdisk-offset", 0); if (addr) setenv_addr("rootaddr", (void *)(CONFIG_SYS_TEXT_BASE + addr)); -} #endif /* CONFIG_OF_CONTROL */ +} -void bootdelay_process(void) +const char *bootdelay_process(void) { -#ifdef CONFIG_OF_CONTROL - char *env; -#endif char *s; int bootdelay; #ifdef CONFIG_BOOTCOUNT_LIMIT @@ -318,27 +270,18 @@ void bootdelay_process(void) } else #endif /* CONFIG_BOOTCOUNT_LIMIT */ s = getenv("bootcmd"); -#ifdef CONFIG_OF_CONTROL - /* Allow the fdt to override the boot command */ - env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd"); - if (env) - s = env; process_fdt_options(gd->fdt_blob); + stored_bootdelay = bootdelay; - /* - * If the bootsecure option was chosen, use secure_boot_cmd(). - * Always use 'env' in this case, since bootsecure requres that the - * bootcmd was specified in the FDT too. - */ - if (fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0)) - secure_boot_cmd(env); - -#endif /* CONFIG_OF_CONTROL */ + return s; +} +void autoboot_command(const char *s) +{ debug("### main_loop: bootcmd=\"%s\"\n", s ? s : ""); - if (bootdelay != -1 && s && !abortboot(bootdelay)) { + if (stored_bootdelay != -1 && s && !abortboot(stored_bootdelay)) { #if defined(CONFIG_AUTOBOOT_KEYED) && !defined(CONFIG_AUTOBOOT_KEYED_CTRLC) int prev = disable_ctrlc(1); /* disable Control C checking */ #endif diff --git a/common/cli.c b/common/cli.c index 4ac9b3f..ea6bfb3 100644 --- a/common/cli.c +++ b/common/cli.c @@ -12,8 +12,11 @@ #include #include #include +#include #include +DECLARE_GLOBAL_DATA_PTR; + /* * Run a command using the selected parser. * @@ -105,6 +108,69 @@ int do_run(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) } #endif +#ifdef CONFIG_OF_CONTROL +bool cli_process_fdt(const char **cmdp) +{ + /* Allow the fdt to override the boot command */ + char *env = fdtdec_get_config_string(gd->fdt_blob, "bootcmd"); + if (env) + *cmdp = env; + /* + * If the bootsecure option was chosen, use secure_boot_cmd(). + * Always use 'env' in this case, since bootsecure requres that the + * bootcmd was specified in the FDT too. + */ + return fdtdec_get_config_int(gd->fdt_blob, "bootsecure", 0) != 0; +} + +/* + * Runs the given boot command securely. Specifically: + * - Doesn't run the command with the shell (run_command or parse_string_outer), + * since that's a lot of code surface that an attacker might exploit. + * Because of this, we don't do any argument parsing--the secure boot command + * has to be a full-fledged u-boot command. + * - Doesn't check for keypresses before booting, since that could be a + * security hole; also disables Ctrl-C. + * - Doesn't allow the command to return. + * + * Upon any failures, this function will drop into an infinite loop after + * printing the error message to console. + */ +void cli_secure_boot_cmd(const char *cmd) +{ + cmd_tbl_t *cmdtp; + int rc; + + if (!cmd) { + printf("## Error: Secure boot command not specified\n"); + goto err; + } + + /* Disable Ctrl-C just in case some command is used that checks it. */ + disable_ctrlc(1); + + /* Find the command directly. */ + cmdtp = find_cmd(cmd); + if (!cmdtp) { + printf("## Error: \"%s\" not defined\n", cmd); + goto err; + } + + /* Run the command, forcing no flags and faking argc and argv. */ + rc = (cmdtp->cmd)(cmdtp, 0, 1, (char **)&cmd); + + /* Shouldn't ever return from boot command. */ + printf("## Error: \"%s\" returned (code %d)\n", cmd, rc); + +err: + /* + * Not a whole lot to do here. Rebooting won't help much, since we'll + * just end up right back here. Just loop. + */ + hang(); +} +#endif /* CONFIG_OF_CONTROL */ + void cli_loop(void) { #ifdef CONFIG_SYS_HUSH_PARSER diff --git a/common/main.c b/common/main.c index 8c846c8..ce45127 100644 --- a/common/main.c +++ b/common/main.c @@ -55,8 +55,11 @@ static void run_preboot_environment_command(void) #endif /* CONFIG_PREBOOT */ } +/* We come here after U-Boot is initialised and ready to process commands */ void main_loop(void) { + const char *s; + bootstage_mark_name(BOOTSTAGE_ID_MAIN_LOOP, "main_loop"); #ifndef CONFIG_SYS_GENERIC_BOARD @@ -78,10 +81,11 @@ void main_loop(void) update_tftp(0UL); #endif /* CONFIG_UPDATE_TFTP */ - bootdelay_process(); - /* - * Main Loop for Monitor Command Processing - */ + s = bootdelay_process(); + if (cli_process_fdt(&s)) + cli_secure_boot_cmd(s); + + autoboot_command(s); cli_loop(); } -- cgit v1.1 From 95856248ca93b9048d87264fbef67ca382975650 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 10 Apr 2014 20:01:36 -0600 Subject: main: Avoid unncessary strdup()/free() It doesn't seem necessary to use memory allocation in this code. The setenv() will make a copy anyway. Signed-off-by: Simon Glass --- common/main.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/main.c b/common/main.c index ce45127..32618f1 100644 --- a/common/main.c +++ b/common/main.c @@ -10,7 +10,6 @@ #include #include #include -#include #include DECLARE_GLOBAL_DATA_PTR; @@ -26,10 +25,9 @@ static void modem_init(void) #ifdef CONFIG_MODEM_SUPPORT debug("DEBUG: main_loop: gd->do_mdm_init=%lu\n", gd->do_mdm_init); if (gd->do_mdm_init) { - char *str = strdup(getenv("mdm_cmd")); + char *str = getenv("mdm_cmd"); + setenv("preboot", str); /* set or delete definition */ - if (str != NULL) - free(str); mdm_init(); /* wait for modem connection */ } #endif /* CONFIG_MODEM_SUPPORT */ -- cgit v1.1 From 0d437bcaf9be36d7bb954cb261635678c790dff7 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Mon, 19 May 2014 14:21:17 -0600 Subject: usb: hub: fix power good delay timing usb_hub_power_on() currently waits for the maximum of (a) the hub port's power output to become good, (b) the max time the USB specification allows a device to take to connect. However, these two operations must occur in series rather than in parallel. First, the power supply ramps up to the level required to power the USB device, and then the device may take a certain amount of time to connect (assert D+/D- pullups). Related, the maximum time that a device has to assert pullups is 1s not 100ms. This is explained in "Connect Timing ECN.pdf", itself part of usb_20_042814.zip from www.usb.org. Signed-off-by: Stephen Warren --- common/usb_hub.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'common') diff --git a/common/usb_hub.c b/common/usb_hub.c index ffac0e7..4875a51 100644 --- a/common/usb_hub.c +++ b/common/usb_hub.c @@ -36,7 +36,7 @@ #endif #ifndef CONFIG_USB_HUB_MIN_POWER_ON_DELAY -#define CONFIG_USB_HUB_MIN_POWER_ON_DELAY 100 +#define CONFIG_USB_HUB_MIN_POWER_ON_DELAY 1000 #endif #define USB_BUFSIZ 512 @@ -138,8 +138,11 @@ static void usb_hub_power_on(struct usb_hub_device *hub) debug("port %d returns %lX\n", i + 1, dev->status); } - /* Wait for power to become stable */ - mdelay(max(pgood_delay, CONFIG_USB_HUB_MIN_POWER_ON_DELAY)); + /* + * Wait for power to become stable, + * plus spec-defined max time for device to connect + */ + mdelay(pgood_delay + CONFIG_USB_HUB_MIN_POWER_ON_DELAY); } void usb_hub_reset(void) -- cgit v1.1 From 77b83e6d099cb2149e5b2c33a700003227d99297 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Mon, 19 May 2014 14:21:18 -0600 Subject: usb: hub: remove CONFIG_USB_HUB_MIN_POWER_ON_DELAY Now that we wait the correct specification-mandated time at the end of usb_hub_power_on(), I suspect that CONFIG_USB_HUB_MIN_POWER_ON_DELAY has no purpose. For cm_t35.h, we already wait longer than the original MIN_POWER_ON_DELAY, so this change is safe. For gw_ventana.h, we will wait as long as the original MIN_POWER_ON_DELAY iff pgood_delay was at least 200ms. I'm not sure if this is the case or not, hence I've CC'd relevant people to test this change. Cc: Igor Grinberg Cc: Tim Harvey Signed-off-by: Stephen Warren --- common/usb_hub.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'common') diff --git a/common/usb_hub.c b/common/usb_hub.c index 4875a51..2add4b9 100644 --- a/common/usb_hub.c +++ b/common/usb_hub.c @@ -35,10 +35,6 @@ #include #endif -#ifndef CONFIG_USB_HUB_MIN_POWER_ON_DELAY -#define CONFIG_USB_HUB_MIN_POWER_ON_DELAY 1000 -#endif - #define USB_BUFSIZ 512 static struct usb_hub_device hub_dev[USB_MAX_HUB]; @@ -142,7 +138,7 @@ static void usb_hub_power_on(struct usb_hub_device *hub) * Wait for power to become stable, * plus spec-defined max time for device to connect */ - mdelay(pgood_delay + CONFIG_USB_HUB_MIN_POWER_ON_DELAY); + mdelay(pgood_delay + 1000); } void usb_hub_reset(void) -- cgit v1.1 From c9bcb6f13d08caa1db13bb8067941340eb3546d8 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Fri, 30 May 2014 14:41:49 -0600 Subject: Fix itest mask overflow The mask value used in itest overflows and therefore it can return an incorrect result for something like 'itest 0 == 1'. Fix it. Signed-off-by: Simon Glass --- common/cmd_itest.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/cmd_itest.c b/common/cmd_itest.c index ae2527b..76af62b 100644 --- a/common/cmd_itest.c +++ b/common/cmd_itest.c @@ -63,7 +63,7 @@ static long evalexp(char *s, int w) l = simple_strtoul(s, NULL, 16); } - return (l & ((1 << (w * 8)) - 1)); + return l & ((1UL << (w * 8)) - 1); } static char * evalstr(char *s) -- cgit v1.1 From 587e1d43e786ad70ce52a47f74b98d785098e378 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Fri, 30 May 2014 14:41:50 -0600 Subject: Fix hush to give the correct return code for a simple command When a simple command like 'false' is provided, hush should return the result of that command. However, hush only does this if the FLAG_EXIT_FROM_LOOP flag is provided. Without this flag, hush will happily execute the empty string command immediate after 'false' and then return a success code. This behaviour does not seem very useful, and requiring the flag also seems wrong, since it means that hush will execute only the first command in a sequence. Add a check for empty string and fall out of the loop in that case. That at least fixes the simple command case. This is a change in behaviour but it is unlikely that the old behaviour would be considered correct in any case. Reported-by: Stefan Herbrechtsmeier Signed-off-by: Simon Glass --- common/cli_hush.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/cli_hush.c b/common/cli_hush.c index 0f069b0..e0c436f 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -3215,7 +3215,9 @@ static int parse_stream_outer(struct in_str *inp, int flag) free_pipe_list(ctx.list_head,0); } b_free(&temp); - } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP)); /* loop on syntax errors, return on EOF */ + /* loop on syntax errors, return on EOF */ + } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP) && + (inp->peek != static_peek || b_peek(inp))); #ifndef __U_BOOT__ return 0; #else -- cgit v1.1 From 4eb580b780057413ddc82855d913ea2f1cbc9dd2 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Fri, 30 May 2014 14:41:51 -0600 Subject: Correct return code from builtin_run_command_list() The return code is not consistent with cli_simple_run_command_list(). For the last command in a sequence, the return code is actually inverted. Fix it. Signed-off-by: Simon Glass --- common/cli_simple.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/cli_simple.c b/common/cli_simple.c index 413c2eb..49d5833 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -331,7 +331,7 @@ int cli_simple_run_command_list(char *cmd, int flag) ++next; } if (rcode == 0 && *line) - rcode = (cli_simple_run_command(line, 0) >= 0); + rcode = (cli_simple_run_command(line, 0) < 0); return rcode; } -- cgit v1.1 From ed6a5d4f880ac248530dbf64683b2257dbe54b64 Mon Sep 17 00:00:00 2001 From: Siva Durga Prasad Paladugu Date: Mon, 26 May 2014 19:51:22 +0530 Subject: env_eeprom: Assign default environment during board_init_f Assign default environment and set env valid during board_init_f before relocation as the actual environment will be read from eeprom later. Signed-off-by: Siva Durga Prasad Paladugu Acked-by: Michal Simek --- common/env_eeprom.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'common') diff --git a/common/env_eeprom.c b/common/env_eeprom.c index 490ac73..905d39a 100644 --- a/common/env_eeprom.c +++ b/common/env_eeprom.c @@ -147,6 +147,7 @@ int saveenv(void) #ifdef CONFIG_ENV_OFFSET_REDUND int env_init(void) { +#ifdef ENV_IS_EMBEDDED ulong len, crc[2], crc_tmp; unsigned int off, off_env[2]; uchar buf[64], flags[2]; @@ -212,12 +213,16 @@ int env_init(void) gd->env_addr = off_env[1] + offsetof(env_t, data); else if (gd->env_valid == 1) gd->env_addr = off_env[0] + offsetof(env_t, data); - +#else + gd->env_addr = (ulong)&default_environment[0]; + gd->env_valid = 1; +#endif return 0; } #else int env_init(void) { +#ifdef ENV_IS_EMBEDDED ulong crc, len, new; unsigned off; uchar buf[64]; @@ -250,7 +255,10 @@ int env_init(void) gd->env_addr = 0; gd->env_valid = 0; } - +#else + gd->env_addr = (ulong)&default_environment[0]; + gd->env_valid = 1; +#endif return 0; } #endif -- cgit v1.1 From 21d29f7f9f4888a4858b58b368ae7cf8783a6ebf Mon Sep 17 00:00:00 2001 From: Heiko Schocher Date: Wed, 28 May 2014 11:33:33 +0200 Subject: bootm: make use of legacy image format configurable make the use of legacy image format configurable through the config define CONFIG_IMAGE_FORMAT_LEGACY. When relying on signed FIT images with required signature check the legacy image format should be disabled. Therefore introduce this new define and enable legacy image format if CONFIG_FIT_SIGNATURE is not set. If CONFIG_FIT_SIGNATURE is set disable per default the legacy image format. Signed-off-by: Heiko Schocher Cc: Simon Glass Cc: Lars Steubesand Cc: Mike Pearce Cc: Wolfgang Denk Cc: Tom Rini Cc: Michal Simek Acked-by: Simon Glass --- common/cmd_bootm.c | 14 ++++++++++++++ common/cmd_disk.c | 4 ++++ common/cmd_fdc.c | 4 ++++ common/cmd_fpga.c | 2 ++ common/cmd_nand.c | 4 ++++ common/cmd_source.c | 4 ++++ common/cmd_ximg.c | 9 +++++++-- common/image-fdt.c | 10 ++++++++-- common/image.c | 25 ++++++++++++++++++------- 9 files changed, 65 insertions(+), 11 deletions(-) (limited to 'common') diff --git a/common/cmd_bootm.c b/common/cmd_bootm.c index 449bb36..9b11c0e 100644 --- a/common/cmd_bootm.c +++ b/common/cmd_bootm.c @@ -230,6 +230,7 @@ static int bootm_find_os(cmd_tbl_t *cmdtp, int flag, int argc, /* get image parameters */ switch (genimg_get_format(os_hdr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: images.os.type = image_get_type(os_hdr); images.os.comp = image_get_comp(os_hdr); @@ -238,6 +239,7 @@ static int bootm_find_os(cmd_tbl_t *cmdtp, int flag, int argc, images.os.end = image_get_image_end(os_hdr); images.os.load = image_get_load(os_hdr); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: if (fit_image_get_type(images.fit_hdr_os, @@ -847,6 +849,7 @@ int bootm_maybe_autostart(cmd_tbl_t *cmdtp, const char *cmd) return 0; } +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) /** * image_get_kernel - verify legacy format kernel image * @img_addr: in RAM address of the legacy format image to be verified @@ -897,6 +900,7 @@ static image_header_t *image_get_kernel(ulong img_addr, int verify) } return hdr; } +#endif /** * boot_get_kernel - find kernel image @@ -914,7 +918,9 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[], bootm_headers_t *images, ulong *os_data, ulong *os_len) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) image_header_t *hdr; +#endif ulong img_addr; const void *buf; #if defined(CONFIG_FIT) @@ -952,6 +958,7 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, *os_data = *os_len = 0; buf = map_sysmem(img_addr, 0); switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: printf("## Booting kernel from Legacy Image at %08lx ...\n", img_addr); @@ -994,6 +1001,7 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, images->legacy_hdr_valid = 1; bootstage_mark(BOOTSTAGE_ID_DECOMP_IMAGE); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: os_noffset = fit_image_load(images, FIT_KERNEL_PROP, @@ -1131,6 +1139,7 @@ static int image_info(ulong addr) printf("\n## Checking Image at %08lx ...\n", addr); switch (genimg_get_format(hdr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: puts(" Legacy image found\n"); if (!image_check_magic(hdr)) { @@ -1152,6 +1161,7 @@ static int image_info(ulong addr) } puts("OK\n"); return 0; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: puts(" FIT image found\n"); @@ -1211,6 +1221,7 @@ static int do_imls_nor(void) goto next_sector; switch (genimg_get_format(hdr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: if (!image_check_hcrc(hdr)) goto next_sector; @@ -1225,6 +1236,7 @@ static int do_imls_nor(void) puts("OK\n"); } break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: if (!fit_check_format(hdr)) @@ -1359,12 +1371,14 @@ static int do_imls_nand(void) } switch (genimg_get_format(buffer)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: header = (const image_header_t *)buffer; len = image_get_image_size(header); nand_imls_legacyimage(nand, nand_dev, off, len); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: len = fit_get_size(buffer); diff --git a/common/cmd_disk.c b/common/cmd_disk.c index 3e457f6..8a1fda9 100644 --- a/common/cmd_disk.c +++ b/common/cmd_disk.c @@ -17,7 +17,9 @@ int common_diskboot(cmd_tbl_t *cmdtp, const char *intf, int argc, ulong addr = CONFIG_SYS_LOAD_ADDR; ulong cnt; disk_partition_t info; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) image_header_t *hdr; +#endif block_dev_desc_t *dev_desc; #if defined(CONFIG_FIT) @@ -62,6 +64,7 @@ int common_diskboot(cmd_tbl_t *cmdtp, const char *intf, int argc, bootstage_mark(BOOTSTAGE_ID_IDE_PART_READ); switch (genimg_get_format((void *) addr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: hdr = (image_header_t *) addr; @@ -78,6 +81,7 @@ int common_diskboot(cmd_tbl_t *cmdtp, const char *intf, int argc, cnt = image_get_image_size(hdr); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: fit_hdr = (const void *) addr; diff --git a/common/cmd_fdc.c b/common/cmd_fdc.c index 1cfb656..5766b56 100644 --- a/common/cmd_fdc.c +++ b/common/cmd_fdc.c @@ -635,7 +635,9 @@ int do_fdcboot (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) FD_GEO_STRUCT *pFG = (FD_GEO_STRUCT *)floppy_type; FDC_COMMAND_STRUCT *pCMD = &cmd; unsigned long addr,imsize; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) image_header_t *hdr; /* used for fdc boot */ +#endif unsigned char boot_drive; int i,nrofblk; #if defined(CONFIG_FIT) @@ -689,12 +691,14 @@ int do_fdcboot (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) } switch (genimg_get_format ((void *)addr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: hdr = (image_header_t *)addr; image_print_contents (hdr); imsize = image_get_image_size (hdr); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: fit_hdr = (const void *)addr; diff --git a/common/cmd_fpga.c b/common/cmd_fpga.c index bda5c8f..8c5bf44 100644 --- a/common/cmd_fpga.c +++ b/common/cmd_fpga.c @@ -201,6 +201,7 @@ int do_fpga(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]) #if defined(CONFIG_CMD_FPGA_LOADMK) case FPGA_LOADMK: switch (genimg_get_format(fpga_data)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: { image_header_t *hdr = @@ -229,6 +230,7 @@ int do_fpga(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]) BIT_FULL); } break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: { diff --git a/common/cmd_nand.c b/common/cmd_nand.c index a84f7dc..f9ced9d 100644 --- a/common/cmd_nand.c +++ b/common/cmd_nand.c @@ -898,7 +898,9 @@ static int nand_load_image(cmd_tbl_t *cmdtp, nand_info_t *nand, int r; char *s; size_t cnt; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) image_header_t *hdr; +#endif #if defined(CONFIG_FIT) const void *fit_hdr = NULL; #endif @@ -924,6 +926,7 @@ static int nand_load_image(cmd_tbl_t *cmdtp, nand_info_t *nand, bootstage_mark(BOOTSTAGE_ID_NAND_HDR_READ); switch (genimg_get_format ((void *)addr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: hdr = (image_header_t *)addr; @@ -932,6 +935,7 @@ static int nand_load_image(cmd_tbl_t *cmdtp, nand_info_t *nand, cnt = image_get_image_size (hdr); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: fit_hdr = (const void *)addr; diff --git a/common/cmd_source.c b/common/cmd_source.c index 54ffd16..f3e9e60 100644 --- a/common/cmd_source.c +++ b/common/cmd_source.c @@ -29,7 +29,9 @@ int source (ulong addr, const char *fit_uname) { ulong len; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) const image_header_t *hdr; +#endif ulong *data; int verify; void *buf; @@ -44,6 +46,7 @@ source (ulong addr, const char *fit_uname) buf = map_sysmem(addr, 0); switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: hdr = buf; @@ -84,6 +87,7 @@ source (ulong addr, const char *fit_uname) */ while (*data++); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: if (fit_uname == NULL) { diff --git a/common/cmd_ximg.c b/common/cmd_ximg.c index 65a8319..ae2714d 100644 --- a/common/cmd_ximg.c +++ b/common/cmd_ximg.c @@ -32,10 +32,13 @@ do_imgextract(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) { ulong addr = load_addr; ulong dest = 0; - ulong data, len, count; + ulong data, len; int verify; int part = 0; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) + ulong count; image_header_t *hdr = NULL; +#endif #if defined(CONFIG_FIT) const char *uname = NULL; const void* fit_hdr; @@ -64,6 +67,7 @@ do_imgextract(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) } switch (genimg_get_format((void *)addr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: printf("## Copying part %d from legacy image " @@ -114,6 +118,7 @@ do_imgextract(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) image_multi_getimg(hdr, part, &data, &len); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: if (uname == NULL) { @@ -211,7 +216,7 @@ do_imgextract(cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) } break; #endif -#if defined(CONFIG_BZIP2) +#if defined(CONFIG_BZIP2) && defined(CONFIG_IMAGE_FORMAT_LEGACY) case IH_COMP_BZIP2: { int i; diff --git a/common/image-fdt.c b/common/image-fdt.c index 5d64009..ac4563f 100644 --- a/common/image-fdt.c +++ b/common/image-fdt.c @@ -29,6 +29,7 @@ static void fdt_error(const char *msg) puts(" - must RESET the board to recover.\n"); } +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) static const image_header_t *image_get_fdt(ulong fdt_addr) { const image_header_t *fdt_hdr = map_sysmem(fdt_addr, 0); @@ -61,6 +62,7 @@ static const image_header_t *image_get_fdt(ulong fdt_addr) } return fdt_hdr; } +#endif /** * boot_fdt_add_mem_rsv_regions - Mark the memreserve sections as unusable @@ -220,11 +222,13 @@ error: int boot_get_fdt(int flag, int argc, char * const argv[], uint8_t arch, bootm_headers_t *images, char **of_flat_tree, ulong *of_size) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) const image_header_t *fdt_hdr; + ulong load, load_end; + ulong image_start, image_data, image_end; +#endif ulong fdt_addr; char *fdt_blob = NULL; - ulong image_start, image_data, image_end; - ulong load, load_end; void *buf; #if defined(CONFIG_FIT) const char *fit_uname_config = images->fit_uname_cfg; @@ -298,6 +302,7 @@ int boot_get_fdt(int flag, int argc, char * const argv[], uint8_t arch, */ buf = map_sysmem(fdt_addr, 0); switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: /* verify fdt_addr points to a valid image header */ printf("## Flattened Device Tree from Legacy Image at %08lx\n", @@ -337,6 +342,7 @@ int boot_get_fdt(int flag, int argc, char * const argv[], uint8_t arch, fdt_addr = load; break; +#endif case IMAGE_FORMAT_FIT: /* * This case will catch both: new uImage format diff --git a/common/image.c b/common/image.c index 26eb89a..f33b175 100644 --- a/common/image.c +++ b/common/image.c @@ -44,8 +44,10 @@ extern int do_bdinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]); DECLARE_GLOBAL_DATA_PTR; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch, int verify); +#endif #else #include "mkimage.h" #include @@ -330,6 +332,7 @@ void image_print_contents(const void *ptr) #ifndef USE_HOSTCC +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) /** * image_get_ramdisk - get and verify ramdisk image * @rd_addr: ramdisk image start address @@ -391,6 +394,7 @@ static const image_header_t *image_get_ramdisk(ulong rd_addr, uint8_t arch, return rd_hdr; } +#endif #endif /* !USE_HOSTCC */ /*****************************************************************************/ @@ -654,22 +658,23 @@ int genimg_get_comp_id(const char *name) */ int genimg_get_format(const void *img_addr) { - ulong format = IMAGE_FORMAT_INVALID; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) const image_header_t *hdr; hdr = (const image_header_t *)img_addr; if (image_check_magic(hdr)) - format = IMAGE_FORMAT_LEGACY; + return IMAGE_FORMAT_LEGACY; +#endif #if defined(CONFIG_FIT) || defined(CONFIG_OF_LIBFDT) - else if (fdt_check_header(img_addr) == 0) - format = IMAGE_FORMAT_FIT; + if (fdt_check_header(img_addr) == 0) + return IMAGE_FORMAT_FIT; #endif #ifdef CONFIG_ANDROID_BOOT_IMAGE - else if (android_image_check_header(img_addr) == 0) - format = IMAGE_FORMAT_ANDROID; + if (android_image_check_header(img_addr) == 0) + return IMAGE_FORMAT_ANDROID; #endif - return format; + return IMAGE_FORMAT_INVALID; } /** @@ -711,12 +716,14 @@ ulong genimg_get_image(ulong img_addr) /* get data size */ switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: d_size = image_get_data_size(buf); debug(" Legacy format image found at 0x%08lx, " "size 0x%08lx\n", ram_addr, d_size); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: d_size = fit_get_size(buf) - h_size; @@ -792,7 +799,9 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images, { ulong rd_addr, rd_load; ulong rd_data, rd_len; +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) const image_header_t *rd_hdr; +#endif void *buf; #ifdef CONFIG_SUPPORT_RAW_INITRD char *end; @@ -875,6 +884,7 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images, */ buf = map_sysmem(rd_addr, 0); switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) case IMAGE_FORMAT_LEGACY: printf("## Loading init Ramdisk from Legacy " "Image at %08lx ...\n", rd_addr); @@ -890,6 +900,7 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images, rd_len = image_get_data_size(rd_hdr); rd_load = image_get_load(rd_hdr); break; +#endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: rd_noffset = fit_image_load(images, FIT_RAMDISK_PROP, -- cgit v1.1 From 66948c25bb7d90d561c1b8be3d69696ef649358f Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Wed, 4 Jun 2014 10:26:53 +0900 Subject: nand_spl: remove nand_spl infrastructure Remove the common infrastructure of nand_spl and clean-up the code inside ifdef(CONFIG_NAND_U_BOOT)..endif. Signed-off-by: Masahiro Yamada --- common/env_embedded.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/env_embedded.c b/common/env_embedded.c index 1c4f915..56a13cb 100644 --- a/common/env_embedded.c +++ b/common/env_embedded.c @@ -33,7 +33,7 @@ * a seperate section. Note that ENV_CRC is only defined when building * U-Boot itself. */ -#if (defined(CONFIG_SYS_USE_PPCENV) || defined(CONFIG_NAND_U_BOOT)) && \ +#if defined(CONFIG_SYS_USE_PPCENV) && \ defined(ENV_CRC) /* Environment embedded in U-Boot .ppcenv section */ /* XXX - This only works with GNU C */ # define __PPCENV__ __attribute__ ((section(".ppcenv"))) -- cgit v1.1 From 31e997f9212be04e7bbe9c05785d72c4931dcfd4 Mon Sep 17 00:00:00 2001 From: "Wu, Josh" Date: Wed, 4 Jun 2014 11:01:24 +0800 Subject: fs: fatwrite: use map_sysmem before use file_fat_write When the map_sysmem, then the fatwrite command can support sandbox. Following command will show how to use it: => sb bind 0 sd.img => fatls host 0 => fatwrite host 0 $memaddr filename $filesize Signed-off-by: Josh Wu Acked-by: Simon Glass --- common/cmd_fat.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/cmd_fat.c b/common/cmd_fat.c index a12d8fa..fbe3346 100644 --- a/common/cmd_fat.c +++ b/common/cmd_fat.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -93,6 +94,7 @@ static int do_fat_fswrite(cmd_tbl_t *cmdtp, int flag, disk_partition_t info; int dev = 0; int part = 1; + void *buf; if (argc < 5) return cmd_usage(cmdtp); @@ -111,7 +113,9 @@ static int do_fat_fswrite(cmd_tbl_t *cmdtp, int flag, addr = simple_strtoul(argv[3], NULL, 16); count = simple_strtoul(argv[5], NULL, 16); - size = file_fat_write(argv[4], (void *)addr, count); + buf = map_sysmem(addr, count); + size = file_fat_write(argv[4], buf, count); + unmap_sysmem(buf); if (size == -1) { printf("\n** Unable to write \"%s\" from %s %d:%d **\n", argv[4], argv[1], dev, part); -- cgit v1.1 From 31890ae299bca739c58b311dfced0bb199a5f520 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Mon, 2 Jun 2014 22:04:49 -0600 Subject: hash: Export the function to show a hash This function is useful for displaying a hash value, so export it. Signed-off-by: Simon Glass --- common/hash.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/hash.c b/common/hash.c index 7627b84..41a4a28 100644 --- a/common/hash.c +++ b/common/hash.c @@ -311,8 +311,7 @@ int hash_lookup_algo(const char *algo_name, struct hash_algo **algop) return -EPROTONOSUPPORT; } -static void show_hash(struct hash_algo *algo, ulong addr, ulong len, - u8 *output) +void hash_show(struct hash_algo *algo, ulong addr, ulong len, u8 *output) { int i; @@ -392,7 +391,7 @@ int hash_command(const char *algo_name, int flags, cmd_tbl_t *cmdtp, int flag, if (memcmp(output, vsum, algo->digest_size) != 0) { int i; - show_hash(algo, addr, len, output); + hash_show(algo, addr, len, output); printf(" != "); for (i = 0; i < algo->digest_size; i++) printf("%02x", vsum[i]); @@ -400,7 +399,7 @@ int hash_command(const char *algo_name, int flags, cmd_tbl_t *cmdtp, int flag, return 1; } } else { - show_hash(algo, addr, len, output); + hash_show(algo, addr, len, output); printf("\n"); if (argc) { -- cgit v1.1 From 4f427a421fcba92b0325907fe79464c9791e85d5 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Mon, 2 Jun 2014 22:04:51 -0600 Subject: fdt: Update functions which write to an FDT to return -ENOSPC When writing values into an FDT it is possible that there will be insufficient space. If the caller gets a useful error then it can potentially deal with the situation. Adjust these functions to return -ENOSPC when the FDT is full. Signed-off-by: Simon Glass --- common/image-fit.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'common') diff --git a/common/image-fit.c b/common/image-fit.c index 77f32bc..732505a 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -833,7 +833,7 @@ static int fit_image_hash_get_ignore(const void *fit, int noffset, int *ignore) * * returns: * 0, on success - * -1, on property read failure + * -ENOSPC if no space in device tree, -1 for other error */ int fit_set_timestamp(void *fit, int noffset, time_t timestamp) { @@ -847,7 +847,7 @@ int fit_set_timestamp(void *fit, int noffset, time_t timestamp) printf("Can't set '%s' property for '%s' node (%s)\n", FIT_TIMESTAMP_PROP, fit_get_name(fit, noffset, NULL), fdt_strerror(ret)); - return -1; + return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -1; } return 0; -- cgit v1.1 From 73671dad49bf2368959b7bf0e30ba931ea95565c Mon Sep 17 00:00:00 2001 From: Thomas Betker Date: Thu, 5 Jun 2014 20:07:56 +0200 Subject: Check run_command() return code properly run_command() returns 0 for success, 1 for failure. Fix places which assume that failure is indicated by a negative return code. Signed-off-by: Thomas Betker Acked-by: Simon Glass Tested-by: Simon Glass Tested-by: Stefan Roese --- common/cmd_bootm.c | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'common') diff --git a/common/cmd_bootm.c b/common/cmd_bootm.c index 9b11c0e..c06f4b7 100644 --- a/common/cmd_bootm.c +++ b/common/cmd_bootm.c @@ -1087,11 +1087,7 @@ U_BOOT_CMD( #if defined(CONFIG_CMD_BOOTD) int do_bootd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { - int rcode = 0; - - if (run_command(getenv("bootcmd"), flag) < 0) - rcode = 1; - return rcode; + return run_command(getenv("bootcmd"), flag); } U_BOOT_CMD( -- cgit v1.1 From 1d43bfd2d54240c18ec6bfd68a57349cae839f13 Mon Sep 17 00:00:00 2001 From: Thomas Betker Date: Thu, 5 Jun 2014 20:07:57 +0200 Subject: Add run_command_repeatable() run_command() returns 0 on success and 1 on error. However, there are some invocations which expect 0 or 1 for success (not repeatable or repeatable) and -1 for error; add run_command_repeatable() for this purpose. Signed-off-by: Thomas Betker Acked-by: Simon Glass Tested-by: Simon Glass --- common/cli.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'common') diff --git a/common/cli.c b/common/cli.c index ea6bfb3..272b028 100644 --- a/common/cli.c +++ b/common/cli.c @@ -41,6 +41,30 @@ int run_command(const char *cmd, int flag) #endif } +/* + * Run a command using the selected parser, and check if it is repeatable. + * + * @param cmd Command to run + * @param flag Execution flags (CMD_FLAG_...) + * @return 0 (not repeatable) or 1 (repeatable) on success, -1 on error. + */ +int run_command_repeatable(const char *cmd, int flag) +{ +#ifndef CONFIG_SYS_HUSH_PARSER + return cli_simple_run_command(cmd, flag); +#else + /* + * parse_string_outer() returns 1 for failure, so clean up + * its result. + */ + if (parse_string_outer(cmd, + FLAG_PARSE_SEMICOLON | FLAG_EXIT_FROM_LOOP)) + return -1; + + return 0; +#endif +} + int run_command_list(const char *cmd, int len, int flag) { int need_buff = 1; -- cgit v1.1 From 52715f89317ef24426a4613bd2980debfa4699b7 Mon Sep 17 00:00:00 2001 From: Thomas Betker Date: Thu, 5 Jun 2014 20:07:58 +0200 Subject: Use run_command_repeatable() Replace run_command() by run_command_repeatable() in places which depend on the return code to indicate repeatability. Signed-off-by: Thomas Betker Acked-by: Simon Glass Tested-by: Simon Glass --- common/cli_simple.c | 2 +- common/cmd_bedbug.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'common') diff --git a/common/cli_simple.c b/common/cli_simple.c index 49d5833..353ceeb 100644 --- a/common/cli_simple.c +++ b/common/cli_simple.c @@ -295,7 +295,7 @@ void cli_simple_loop(void) if (len == -1) puts("\n"); else - rc = run_command(lastcommand, flag); + rc = run_command_repeatable(lastcommand, flag); if (rc <= 0) { /* invalid command or not repeatable, forget it */ diff --git a/common/cmd_bedbug.c b/common/cmd_bedbug.c index bdcf712..57a8a3f 100644 --- a/common/cmd_bedbug.c +++ b/common/cmd_bedbug.c @@ -238,7 +238,7 @@ void bedbug_main_loop (unsigned long addr, struct pt_regs *regs) if (len == -1) printf ("\n"); else - rc = run_command(lastcommand, flag); + rc = run_command_repeatable(lastcommand, flag); if (rc <= 0) { /* invalid command or not repeatable, forget it */ -- cgit v1.1 From 8b9cc866c10787b057b4ac91c8783cfa752f1151 Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Mon, 9 Jun 2014 11:02:02 +0200 Subject: common: hash: zero end the string instead of the pointer if algo->digest_size is zero nothing is set in the str_output buffer. An attempt is made to zero end the buffer, but the pointer to the buffer is set to zero instead. I am unaware if it causes any actual problems, but solves the following warning: common/hash.c:217:13: warning: expression which evaluates to zero treated as a null pointer constant of type 'char *' [-Wnon-literal-null-conversion] str_ptr = '\0'; ^~~~ cc: Simon Glass Signed-off-by: Jeroen Hofstee --- common/hash.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/hash.c b/common/hash.c index 41a4a28..237bd04 100644 --- a/common/hash.c +++ b/common/hash.c @@ -214,7 +214,7 @@ static void store_result(struct hash_algo *algo, const u8 *sum, sprintf(str_ptr, "%02x", sum[i]); str_ptr += 2; } - str_ptr = '\0'; + *str_ptr = '\0'; setenv(dest, str_output); } else { ulong addr; -- cgit v1.1 From 930e4254ec29ea5133c0772d4a3804ba1c59b275 Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Wed, 11 Jun 2014 00:28:47 +0200 Subject: common/cli_hush.c: remove unnecessary double braces Clang interpretes an if condition like "if ((a = b) == NULL) as it tries to assign a value in a statement. Hence if you do "if ((something)) it warns you that you might be confused. Hence drop the double braces for plane if statements. Simon Glass Signed-off-by: Jeroen Hofstee --- common/cli_hush.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'common') diff --git a/common/cli_hush.c b/common/cli_hush.c index e0c436f..38da5a0 100644 --- a/common/cli_hush.c +++ b/common/cli_hush.c @@ -1840,7 +1840,7 @@ static int run_list_real(struct pipe *pi) if (rmode == RES_DO) { if (!flag_rep) continue; } - if ((rmode == RES_DONE)) { + if (rmode == RES_DONE) { if (flag_rep) { flag_restore = 1; } else { @@ -3569,7 +3569,7 @@ static char **make_list_in(char **inp, char *name) p3 = insert_var_value(inp[i]); p1 = p3; while (*p1) { - if ((*p1 == ' ')) { + if (*p1 == ' ') { p1++; continue; } -- cgit v1.1 From e153b13c8e300236e6d505bea629cc81fd0988cb Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Wed, 11 Jun 2014 01:04:42 +0200 Subject: common/xyzModem.c: move empty statements to newline To prevent a warning for clang the loop without a body is made more clear by moving it to a line of its own. This prevents a clang warning. cc: sbabic@denx.de Signed-off-by: Jeroen Hofstee --- common/xyzModem.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/xyzModem.c b/common/xyzModem.c index 39f7d17..56f4bca 100644 --- a/common/xyzModem.c +++ b/common/xyzModem.c @@ -759,7 +759,8 @@ xyzModem_stream_terminate (bool abort, int (*getc) (void)) * If we don't eat it now, RedBoot will think the user typed it. */ ZM_DEBUG (zm_dprintf ("Trailing gunk:\n")); - while ((c = (*getc) ()) > -1); + while ((c = (*getc) ()) > -1) + ; ZM_DEBUG (zm_dprintf ("\n")); /* * Make a small delay to give terminal programs like minicom -- cgit v1.1 From 60dc58f735f173458ebed217cc7fe0c24816f383 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Fri, 23 May 2014 12:48:10 -0600 Subject: cmd_mmc: default to HW partition 0 if not specified Currently, "mmc dev 0" does not change the selected HW partition. I think it makes more sense if "mmc dev 0" is an alias for "mmc dev 0 0", i.e. that HW partition 0 (main data area) is always selected by default if the user didn't request a specific partition. Otherwise, the following happens, which feels wrong: Select HW partition 1 (boot0): mmc dev 0 1 Doesn't change the HW partition, so it's still 1 (boot0): mmc dev 0 With this patch, the second command above re-selects the main data area. Note that some MMC devices (i.e. SD cards) don't support HW partitions. However, this patch still works, since mmc_start_init() sets the current partition number to 0, and mmc_select_hwpart() succeeds if the requested partition is already selected. Signed-off-by: Stephen Warren Acked-by: Pantelis Antoniou --- common/cmd_mmc.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'common') diff --git a/common/cmd_mmc.c b/common/cmd_mmc.c index eea3375..9e6a26f 100644 --- a/common/cmd_mmc.c +++ b/common/cmd_mmc.c @@ -403,7 +403,7 @@ static int do_mmc_part(cmd_tbl_t *cmdtp, int flag, static int do_mmc_dev(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { - int dev, part = -1, ret; + int dev, part = 0, ret; struct mmc *mmc; if (argc == 1) { @@ -426,13 +426,12 @@ static int do_mmc_dev(cmd_tbl_t *cmdtp, int flag, if (!mmc) return CMD_RET_FAILURE; - if (part != -1) { - ret = mmc_select_hwpart(dev, part); - printf("switch to partitions #%d, %s\n", - part, (!ret) ? "OK" : "ERROR"); - if (ret) - return 1; - } + ret = mmc_select_hwpart(dev, part); + printf("switch to partitions #%d, %s\n", + part, (!ret) ? "OK" : "ERROR"); + if (ret) + return 1; + curr_device = dev; if (mmc->part_config == MMCPART_NOAVAILABLE) printf("mmc%d is current device\n", curr_device); -- cgit v1.1 From 1ae24a5041b6fab7cc986bda7fec92b3d643ac96 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Fri, 23 May 2014 13:24:45 -0600 Subject: cmd_mmc: add force_init parameter to init_mmc_device() This allows callers to inject mmc->has_init = 0 between finding the MMC device, and calling mmc_init(), which forces mmc_init() to rescan the HW. Future changes will use this feature. Signed-off-by: Stephen Warren Acked-by: Jaehoon Chung Acked-by: Pantelis Antoniou --- common/cmd_mmc.c | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) (limited to 'common') diff --git a/common/cmd_mmc.c b/common/cmd_mmc.c index 9e6a26f..6741ebe 100644 --- a/common/cmd_mmc.c +++ b/common/cmd_mmc.c @@ -92,7 +92,7 @@ static void print_mmcinfo(struct mmc *mmc) printf("Bus Width: %d-bit\n", mmc->bus_width); } -static struct mmc *init_mmc_device(int dev) +static struct mmc *init_mmc_device(int dev, bool force_init) { struct mmc *mmc; mmc = find_mmc_device(dev); @@ -100,6 +100,8 @@ static struct mmc *init_mmc_device(int dev) printf("no mmc device at slot %x\n", dev); return NULL; } + if (force_init) + mmc->has_init = 0; if (mmc_init(mmc)) return NULL; return mmc; @@ -117,7 +119,7 @@ static int do_mmcinfo(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) } } - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -247,7 +249,7 @@ static int do_mmcrpmb(cmd_tbl_t *cmdtp, int flag, if (flag == CMD_FLAG_REPEAT && !cp->repeatable) return CMD_RET_SUCCESS; - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -292,7 +294,7 @@ static int do_mmc_read(cmd_tbl_t *cmdtp, int flag, blk = simple_strtoul(argv[2], NULL, 16); cnt = simple_strtoul(argv[3], NULL, 16); - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -320,7 +322,7 @@ static int do_mmc_write(cmd_tbl_t *cmdtp, int flag, blk = simple_strtoul(argv[2], NULL, 16); cnt = simple_strtoul(argv[3], NULL, 16); - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -348,7 +350,7 @@ static int do_mmc_erase(cmd_tbl_t *cmdtp, int flag, blk = simple_strtoul(argv[1], NULL, 16); cnt = simple_strtoul(argv[2], NULL, 16); - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -387,7 +389,7 @@ static int do_mmc_part(cmd_tbl_t *cmdtp, int flag, block_dev_desc_t *mmc_dev; struct mmc *mmc; - mmc = init_mmc_device(curr_device); + mmc = init_mmc_device(curr_device, false); if (!mmc) return CMD_RET_FAILURE; @@ -422,7 +424,7 @@ static int do_mmc_dev(cmd_tbl_t *cmdtp, int flag, return CMD_RET_USAGE; } - mmc = init_mmc_device(dev); + mmc = init_mmc_device(dev, false); if (!mmc) return CMD_RET_FAILURE; @@ -462,7 +464,7 @@ static int do_mmc_bootbus(cmd_tbl_t *cmdtp, int flag, reset = simple_strtoul(argv[3], NULL, 10); mode = simple_strtoul(argv[4], NULL, 10); - mmc = init_mmc_device(dev); + mmc = init_mmc_device(dev, false); if (!mmc) return CMD_RET_FAILURE; @@ -487,7 +489,7 @@ static int do_mmc_boot_resize(cmd_tbl_t *cmdtp, int flag, bootsize = simple_strtoul(argv[2], NULL, 10); rpmbsize = simple_strtoul(argv[3], NULL, 10); - mmc = init_mmc_device(dev); + mmc = init_mmc_device(dev, false); if (!mmc) return CMD_RET_FAILURE; @@ -520,7 +522,7 @@ static int do_mmc_partconf(cmd_tbl_t *cmdtp, int flag, part_num = simple_strtoul(argv[3], NULL, 10); access = simple_strtoul(argv[4], NULL, 10); - mmc = init_mmc_device(dev); + mmc = init_mmc_device(dev, false); if (!mmc) return CMD_RET_FAILURE; @@ -555,7 +557,7 @@ static int do_mmc_rst_func(cmd_tbl_t *cmdtp, int flag, return CMD_RET_USAGE; } - mmc = init_mmc_device(dev); + mmc = init_mmc_device(dev, false); if (!mmc) return CMD_RET_FAILURE; -- cgit v1.1 From 941944e445193a07dea77787680666db049a14dc Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Fri, 23 May 2014 13:24:46 -0600 Subject: cmd_mmc: Use init_mmc_device() from do_mmc_rescan() The body of init_mmc_device() is now identical to that of do_mmc_rescan() except for the error codes returned. Modify do_mmc_rescan() to simply call init_mmc_device() and convert the error codes, to avoid code duplication. Signed-off-by: Stephen Warren Acked-by: Pantelis Antoniou --- common/cmd_mmc.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) (limited to 'common') diff --git a/common/cmd_mmc.c b/common/cmd_mmc.c index 6741ebe..6c8db2e 100644 --- a/common/cmd_mmc.c +++ b/common/cmd_mmc.c @@ -371,16 +371,10 @@ static int do_mmc_rescan(cmd_tbl_t *cmdtp, int flag, { struct mmc *mmc; - mmc = find_mmc_device(curr_device); - if (!mmc) { - printf("no mmc device at slot %x\n", curr_device); + mmc = init_mmc_device(curr_device, true); + if (!mmc) return CMD_RET_FAILURE; - } - - mmc->has_init = 0; - if (mmc_init(mmc)) - return CMD_RET_FAILURE; return CMD_RET_SUCCESS; } static int do_mmc_part(cmd_tbl_t *cmdtp, int flag, -- cgit v1.1 From a5710920b7b0016c6d83897d251b44922f5ca832 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Fri, 23 May 2014 13:24:47 -0600 Subject: cmd_mmc: make mmc dev always re-probe the HW Currently, U-Boot behaves as follows: - Begin with no SD card inserted in "mmc 1" - Execute: mmc dev 1 - This fails, since there is no card - User plugs in an SD card - Execute: mmc dev 1 - This still fails, since the HW isn't reprobed. With this change, U-Boot behaves as follows: - Begin with no SD card inserted in "mmc 1" - Execute: mmc dev 1 - This fails, since there is no card - User plugs in an SD card - Execute: mmc dev 1 - The newly present SD card is detected I know that "mmc rescan" will force the HW to be reprobed, but I feel it makes more sense if "mmc dev" always reprobes the HW after selecting the current MMC device. This allows scripts to just execute "mmc dev", and not have to also execute "mmc rescan" to check for media presense. Signed-off-by: Stephen Warren Acked-by: Pantelis Antoniou --- common/cmd_mmc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/cmd_mmc.c b/common/cmd_mmc.c index 6c8db2e..1e40983 100644 --- a/common/cmd_mmc.c +++ b/common/cmd_mmc.c @@ -418,7 +418,7 @@ static int do_mmc_dev(cmd_tbl_t *cmdtp, int flag, return CMD_RET_USAGE; } - mmc = init_mmc_device(dev, false); + mmc = init_mmc_device(dev, true); if (!mmc) return CMD_RET_FAILURE; -- cgit v1.1 From b1f49ab8c7bad60426b30c134ae065ef77d2dfc1 Mon Sep 17 00:00:00 2001 From: Dan Murphy Date: Wed, 2 Oct 2013 14:00:15 -0500 Subject: ARM: fdt support: Add usbethaddr as an acceptable MAC A board that has a USB ethernet device only may set the usbetheraddr and not the ethaddr. ethaddr will be the default MAC address that is chosen and if that is not populated then the usbethaddr is looked at. If neither are set then then device tree blob is not modified. Signed-off-by: Dan Murphy --- common/fdt_support.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index fcd2523..c690768 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -479,8 +479,18 @@ void fdt_fixup_ethernet(void *fdt) if (node < 0) return; + if (!getenv("ethaddr")) { + if (getenv("usbethaddr")) { + strcpy(mac, "usbethaddr"); + } else { + debug("No ethernet MAC Address defined\n"); + return; + } + } else { + strcpy(mac, "ethaddr"); + } + i = 0; - strcpy(mac, "ethaddr"); while ((tmp = getenv(mac)) != NULL) { sprintf(enet, "ethernet%d", i); path = fdt_getprop(fdt, node, enet, NULL); -- cgit v1.1 From 0613c57ce306722bb79637ffffc685c9acf35a7f Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:40:57 +0900 Subject: fdt_support: delete unnecessary DECLARE_GLOBAL_DATA_PTR gd->bd is not used in fdt_support.c. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 5 ----- 1 file changed, 5 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index c690768..3c4edc4 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -17,11 +17,6 @@ #include /* - * Global data (for the gd->bd) - */ -DECLARE_GLOBAL_DATA_PTR; - -/* * Get cells len in bytes * if #NNNN-cells property is 2 then len is 8 * otherwise len is 4 -- cgit v1.1 From 8edb21925e6135fb402770a288c4f321f7a05e1b Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:40:58 +0900 Subject: fdt_support: refactor with fdt_find_or_add_subnode helper func Some functions in fdt_support.c do the same routine: search a node with a given name ("chosen", "memory", etc.) or newly create it if it does not exist. So this commit makes that routine to a helper function. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 71 ++++++++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 35 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index 3c4edc4..0fede8e 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -124,6 +124,31 @@ int fdt_find_and_setprop(void *fdt, const char *node, const char *prop, return fdt_setprop(fdt, nodeoff, prop, val, len); } +/** + * fdt_find_or_add_subnode - find or possibly add a subnode of a given node + * @fdt: pointer to the device tree blob + * @parentoffset: structure block offset of a node + * @name: name of the subnode to locate + * + * fdt_subnode_offset() finds a subnode of the node with a given name. + * If the subnode does not exist, it will be created. + */ +static int fdt_find_or_add_subnode(void *fdt, int parentoffset, + const char *name) +{ + int offset; + + offset = fdt_subnode_offset(fdt, parentoffset, name); + + if (offset == -FDT_ERR_NOTFOUND) + offset = fdt_add_subnode(fdt, parentoffset, name); + + if (offset < 0) + printf("%s: %s: %s\n", __func__, name, fdt_strerror(offset)); + + return offset; +} + #ifdef CONFIG_OF_STDOUT_VIA_ALIAS #ifdef CONFIG_CONS_INDEX @@ -186,14 +211,10 @@ int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end, int force) const char *path; uint64_t addr, size; - /* Find the "chosen" node. */ - nodeoffset = fdt_path_offset (fdt, "/chosen"); - - /* If there is no "chosen" node in the blob return */ - if (nodeoffset < 0) { - printf("fdt_initrd: %s\n", fdt_strerror(nodeoffset)); + /* find or create "/chosen" node. */ + nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen"); + if (nodeoffset < 0) return nodeoffset; - } /* just return if initrd_start/end aren't valid */ if ((initrd_start == 0) || (initrd_end == 0)) @@ -259,25 +280,10 @@ int fdt_chosen(void *fdt, int force) return err; } - /* - * Find the "chosen" node. - */ - nodeoffset = fdt_path_offset (fdt, "/chosen"); - - /* - * If there is no "chosen" node in the blob, create it. - */ - if (nodeoffset < 0) { - /* - * Create a new node "/chosen" (offset 0 is root level) - */ - nodeoffset = fdt_add_subnode(fdt, 0, "chosen"); - if (nodeoffset < 0) { - printf("WARNING: could not create /chosen %s.\n", - fdt_strerror(nodeoffset)); - return nodeoffset; - } - } + /* find or create "/chosen" node. */ + nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen"); + if (nodeoffset < 0) + return nodeoffset; /* * Create /chosen properites that don't exist in the fdt. @@ -419,16 +425,11 @@ int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks) return err; } - /* update, or add and update /memory node */ - nodeoffset = fdt_path_offset(blob, "/memory"); - if (nodeoffset < 0) { - nodeoffset = fdt_add_subnode(blob, 0, "memory"); - if (nodeoffset < 0) { - printf("WARNING: could not create /memory: %s.\n", - fdt_strerror(nodeoffset)); + /* find or create "/memory" node. */ + nodeoffset = fdt_find_or_add_subnode(blob, 0, "memory"); + if (nodeoffset < 0) return nodeoffset; - } - } + err = fdt_setprop(blob, nodeoffset, "device_type", "memory", sizeof("memory")); if (err < 0) { -- cgit v1.1 From dbe963ae516356395182325a032a55356d46d275 Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:40:59 +0900 Subject: fdt_support: delete force argument of fdt_initrd() After all, we have realized "force" argument is completely useless. fdt_initrd() was always called with force = 1. We should always want to do the same thing (set appropriate value to the property) even if the property already exists. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/cmd_fdt.c | 2 +- common/fdt_support.c | 35 +++++++++++++++-------------------- common/image-fdt.c | 2 +- 3 files changed, 17 insertions(+), 22 deletions(-) (limited to 'common') diff --git a/common/cmd_fdt.c b/common/cmd_fdt.c index a6744ed..cc2b0e2 100644 --- a/common/cmd_fdt.c +++ b/common/cmd_fdt.c @@ -582,7 +582,7 @@ static int do_fdt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) } fdt_chosen(working_fdt, 1); - fdt_initrd(working_fdt, initrd_start, initrd_end, 1); + fdt_initrd(working_fdt, initrd_start, initrd_end); #if defined(CONFIG_FIT_SIGNATURE) } else if (strncmp(argv[1], "che", 3) == 0) { diff --git a/common/fdt_support.c b/common/fdt_support.c index 0fede8e..321dd2a 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -203,12 +203,11 @@ static int fdt_fixup_stdout(void *fdt, int chosenoff) } #endif -int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end, int force) +int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) { int nodeoffset, addr_cell_len; int err, j, total; fdt64_t tmp; - const char *path; uint64_t addr, size; /* find or create "/chosen" node. */ @@ -242,26 +241,22 @@ int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end, int force) addr_cell_len = get_cells_len(fdt, "#address-cells"); - path = fdt_getprop(fdt, nodeoffset, "linux,initrd-start", NULL); - if ((path == NULL) || force) { - write_cell((u8 *)&tmp, initrd_start, addr_cell_len); - err = fdt_setprop(fdt, nodeoffset, - "linux,initrd-start", &tmp, addr_cell_len); - if (err < 0) { - printf("WARNING: " - "could not set linux,initrd-start %s.\n", - fdt_strerror(err)); - return err; - } - write_cell((u8 *)&tmp, initrd_end, addr_cell_len); - err = fdt_setprop(fdt, nodeoffset, + write_cell((u8 *)&tmp, initrd_start, addr_cell_len); + err = fdt_setprop(fdt, nodeoffset, + "linux,initrd-start", &tmp, addr_cell_len); + if (err < 0) { + printf("WARNING: could not set linux,initrd-start %s.\n", + fdt_strerror(err)); + return err; + } + write_cell((u8 *)&tmp, initrd_end, addr_cell_len); + err = fdt_setprop(fdt, nodeoffset, "linux,initrd-end", &tmp, addr_cell_len); - if (err < 0) { - printf("WARNING: could not set linux,initrd-end %s.\n", - fdt_strerror(err)); + if (err < 0) { + printf("WARNING: could not set linux,initrd-end %s.\n", + fdt_strerror(err)); - return err; - } + return err; } return 0; diff --git a/common/image-fdt.c b/common/image-fdt.c index ac4563f..173d362 100644 --- a/common/image-fdt.c +++ b/common/image-fdt.c @@ -489,7 +489,7 @@ int image_setup_libfdt(bootm_headers_t *images, void *blob, /* Create a new LMB reservation */ lmb_reserve(lmb, (ulong)blob, of_size); - fdt_initrd(blob, *initrd_start, *initrd_end, 1); + fdt_initrd(blob, *initrd_start, *initrd_end); if (!ft_verify_fdt(blob)) return -1; -- cgit v1.1 From bc6ed0f9dc56fe1738646e6882a0b87e6766eaaa Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:00 +0900 Subject: fdt_support: delete force argument of fdt_chosen() After all, we have realized "force" argument is completely useless. fdt_chosen() was always called with force = 1. We should always want to do the same thing (set appropriate value to the property) even if the property already exists. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/cmd_fdt.c | 2 +- common/fdt_support.c | 38 ++++++++++++-------------------------- common/image-fdt.c | 2 +- 3 files changed, 14 insertions(+), 28 deletions(-) (limited to 'common') diff --git a/common/cmd_fdt.c b/common/cmd_fdt.c index cc2b0e2..6831af4 100644 --- a/common/cmd_fdt.c +++ b/common/cmd_fdt.c @@ -581,7 +581,7 @@ static int do_fdt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) initrd_end = simple_strtoul(argv[3], NULL, 16); } - fdt_chosen(working_fdt, 1); + fdt_chosen(working_fdt); fdt_initrd(working_fdt, initrd_start, initrd_end); #if defined(CONFIG_FIT_SIGNATURE) diff --git a/common/fdt_support.c b/common/fdt_support.c index 321dd2a..f5a5cdf 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -262,12 +262,11 @@ int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) return 0; } -int fdt_chosen(void *fdt, int force) +int fdt_chosen(void *fdt) { int nodeoffset; int err; char *str; /* used to set string properties */ - const char *path; err = fdt_check_header(fdt); if (err < 0) { @@ -280,38 +279,25 @@ int fdt_chosen(void *fdt, int force) if (nodeoffset < 0) return nodeoffset; - /* - * Create /chosen properites that don't exist in the fdt. - * If the property exists, update it only if the "force" parameter - * is true. - */ str = getenv("bootargs"); if (str != NULL) { - path = fdt_getprop(fdt, nodeoffset, "bootargs", NULL); - if ((path == NULL) || force) { - err = fdt_setprop(fdt, nodeoffset, - "bootargs", str, strlen(str)+1); - if (err < 0) - printf("WARNING: could not set bootargs %s.\n", - fdt_strerror(err)); - } + err = fdt_setprop(fdt, nodeoffset, + "bootargs", str, strlen(str)+1); + if (err < 0) + printf("WARNING: could not set bootargs %s.\n", + fdt_strerror(err)); } #ifdef CONFIG_OF_STDOUT_VIA_ALIAS - path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL); - if ((path == NULL) || force) - err = fdt_fixup_stdout(fdt, nodeoffset); + err = fdt_fixup_stdout(fdt, nodeoffset); #endif #ifdef OF_STDOUT_PATH - path = fdt_getprop(fdt, nodeoffset, "linux,stdout-path", NULL); - if ((path == NULL) || force) { - err = fdt_setprop(fdt, nodeoffset, - "linux,stdout-path", OF_STDOUT_PATH, strlen(OF_STDOUT_PATH)+1); - if (err < 0) - printf("WARNING: could not set linux,stdout-path %s.\n", - fdt_strerror(err)); - } + err = fdt_setprop(fdt, nodeoffset, "linux,stdout-path", + OF_STDOUT_PATH, strlen(OF_STDOUT_PATH)+1); + if (err < 0) + printf("WARNING: could not set linux,stdout-path %s.\n", + fdt_strerror(err)); #endif return err; diff --git a/common/image-fdt.c b/common/image-fdt.c index 173d362..27a8a44 100644 --- a/common/image-fdt.c +++ b/common/image-fdt.c @@ -463,7 +463,7 @@ int image_setup_libfdt(bootm_headers_t *images, void *blob, ulong *initrd_end = &images->initrd_end; int ret; - if (fdt_chosen(blob, 1) < 0) { + if (fdt_chosen(blob) < 0) { puts("ERROR: /chosen node create failed"); puts(" - must RESET the board to recover.\n"); return -1; -- cgit v1.1 From 972f2a8905a1ca3fc25401e60a9a1d7f6a7ab898 Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:01 +0900 Subject: fdt_support: refactor fdt_fixup_stdout() function - Do not use a deep indentation. We have only 80-character on each line and 1 indentation consumes 8 spaces. Before the code moves far to the right, you should consider to fix your code. See Linux Documentation/CodingStyle. - Add CONFIG_OF_STDOUT_VIA_ALIAS and OF_STDOUT_PATH macros only to their definition. Do not add them to both callee and caller. This is a tip to avoid using #ifdef everywhere. - OF_STDOUT_PATH and CONFIG_OF_STDOUT_VIA_ALIAS are exclusive. If both are defined, the former takes precedence. Do not try to fix-up "linux,stdout-path" property twice. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 85 ++++++++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 43 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index f5a5cdf..9a9151a 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -149,9 +149,14 @@ static int fdt_find_or_add_subnode(void *fdt, int parentoffset, return offset; } -#ifdef CONFIG_OF_STDOUT_VIA_ALIAS - -#ifdef CONFIG_CONS_INDEX +/* rename to CONFIG_OF_STDOUT_PATH ? */ +#if defined(OF_STDOUT_PATH) +static int fdt_fixup_stdout(void *fdt, int chosenoff) +{ + return fdt_setprop(fdt, chosenoff, "linux,stdout-path", + OF_STDOUT_PATH, strlen(OF_STDOUT_PATH) + 1); +} +#elif defined(CONFIG_OF_STDOUT_VIA_ALIAS) && defined(CONFIG_CONS_INDEX) static void fdt_fill_multisername(char *sername, size_t maxlen) { const char *outname = stdio_devices[stdout]->name; @@ -163,44 +168,48 @@ static void fdt_fill_multisername(char *sername, size_t maxlen) if (strcmp(outname + 1, "serial") > 0) strncpy(sername, outname + 1, maxlen); } -#endif static int fdt_fixup_stdout(void *fdt, int chosenoff) { - int err = 0; -#ifdef CONFIG_CONS_INDEX - int node; + int err; + int aliasoff; char sername[9] = { 0 }; - const char *path; + const void *path; + int len; + char tmp[256]; /* long enough */ fdt_fill_multisername(sername, sizeof(sername) - 1); if (!sername[0]) sprintf(sername, "serial%d", CONFIG_CONS_INDEX - 1); - err = node = fdt_path_offset(fdt, "/aliases"); - if (node >= 0) { - int len; - path = fdt_getprop(fdt, node, sername, &len); - if (path) { - char *p = malloc(len); - err = -FDT_ERR_NOSPACE; - if (p) { - memcpy(p, path, len); - err = fdt_setprop(fdt, chosenoff, - "linux,stdout-path", p, len); - free(p); - } - } else { - err = len; - } + aliasoff = fdt_path_offset(fdt, "/aliases"); + if (aliasoff < 0) { + err = aliasoff; + goto error; } -#endif + + path = fdt_getprop(fdt, aliasoff, sername, &len); + if (!path) { + err = len; + goto error; + } + + /* fdt_setprop may break "path" so we copy it to tmp buffer */ + memcpy(tmp, path, len); + + err = fdt_setprop(fdt, chosenoff, "linux,stdout-path", tmp, len); +error: if (err < 0) printf("WARNING: could not set linux,stdout-path %s.\n", - fdt_strerror(err)); + fdt_strerror(err)); return err; } +#else +static int fdt_fixup_stdout(void *fdt, int chosenoff) +{ + return 0; +} #endif int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) @@ -280,27 +289,17 @@ int fdt_chosen(void *fdt) return nodeoffset; str = getenv("bootargs"); - if (str != NULL) { - err = fdt_setprop(fdt, nodeoffset, - "bootargs", str, strlen(str)+1); - if (err < 0) + if (str) { + err = fdt_setprop(fdt, nodeoffset, "bootargs", str, + strlen(str) + 1); + if (err < 0) { printf("WARNING: could not set bootargs %s.\n", fdt_strerror(err)); + return err; + } } -#ifdef CONFIG_OF_STDOUT_VIA_ALIAS - err = fdt_fixup_stdout(fdt, nodeoffset); -#endif - -#ifdef OF_STDOUT_PATH - err = fdt_setprop(fdt, nodeoffset, "linux,stdout-path", - OF_STDOUT_PATH, strlen(OF_STDOUT_PATH)+1); - if (err < 0) - printf("WARNING: could not set linux,stdout-path %s.\n", - fdt_strerror(err)); -#endif - - return err; + return fdt_fixup_stdout(fdt, nodeoffset); } void do_fixup_by_path(void *fdt, const char *path, const char *prop, -- cgit v1.1 From f89d482fe5a95db637190cd49e1954588995d881 Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:02 +0900 Subject: fdt_support: add 'const' qualifier for unchanged argument In the next commit, I will add a new function, fdt_pack_reg() which uses get_cells_len(). Beforehand, this commit adds 'const' qualifier to get_cells_len(). Otherwise, a warning message will appear: warning: passing argument 1 of 'get_cells_len' discards 'const' qualifier from pointer target type [enabled by default] Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index 9a9151a..fe85a8b 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -21,11 +21,11 @@ * if #NNNN-cells property is 2 then len is 8 * otherwise len is 4 */ -static int get_cells_len(void *blob, char *nr_cells_name) +static int get_cells_len(const void *fdt, const char *nr_cells_name) { const fdt32_t *cell; - cell = fdt_getprop(blob, 0, nr_cells_name, NULL); + cell = fdt_getprop(fdt, 0, nr_cells_name, NULL); if (cell && fdt32_to_cpu(*cell) == 2) return 8; -- cgit v1.1 From 739a01ed8e02c3b79a0f059d34b749bfab1a30df Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:03 +0900 Subject: fdt_support: fix an endian bug of fdt_fixup_memory_banks Data written to DTB must be converted to big endian order. It is usually done by using cpu_to_fdt32(), cpu_to_fdt64(), etc. fdt_fixup_memory_banks() invoked write_cell(), which always swaps byte order. It means the function only worked on little endian architectures. This commit adds and uses a new helper function, fdt_pack_reg(), which works on both big endian and little endian architrectures. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index fe85a8b..ae714e7 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -380,6 +380,34 @@ void do_fixup_by_compat_u32(void *fdt, const char *compat, do_fixup_by_compat(fdt, compat, prop, &tmp, 4, create); } +/* + * fdt_pack_reg - pack address and size array into the "reg"-suitable stream + */ +static int fdt_pack_reg(const void *fdt, void *buf, uint64_t *address, + uint64_t *size, int n) +{ + int i; + int address_len = get_cells_len(fdt, "#address-cells"); + int size_len = get_cells_len(fdt, "#size-cells"); + char *p = buf; + + for (i = 0; i < n; i++) { + if (address_len == 8) + *(fdt64_t *)p = cpu_to_fdt64(address[i]); + else + *(fdt32_t *)p = cpu_to_fdt32(address[i]); + p += address_len; + + if (size_len == 8) + *(fdt64_t *)p = cpu_to_fdt64(size[i]); + else + *(fdt32_t *)p = cpu_to_fdt32(size[i]); + p += size_len; + } + + return p - (char *)buf; +} + #ifdef CONFIG_NR_DRAM_BANKS #define MEMORY_BANKS_MAX CONFIG_NR_DRAM_BANKS #else @@ -388,9 +416,8 @@ void do_fixup_by_compat_u32(void *fdt, const char *compat, int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks) { int err, nodeoffset; - int addr_cell_len, size_cell_len, len; + int len; u8 tmp[MEMORY_BANKS_MAX * 16]; /* Up to 64-bit address + 64-bit size */ - int bank; if (banks > MEMORY_BANKS_MAX) { printf("%s: num banks %d exceeds hardcoded limit %d." @@ -418,16 +445,7 @@ int fdt_fixup_memory_banks(void *blob, u64 start[], u64 size[], int banks) return err; } - addr_cell_len = get_cells_len(blob, "#address-cells"); - size_cell_len = get_cells_len(blob, "#size-cells"); - - for (bank = 0, len = 0; bank < banks; bank++) { - write_cell(tmp + len, start[bank], addr_cell_len); - len += addr_cell_len; - - write_cell(tmp + len, size[bank], size_cell_len); - len += size_cell_len; - } + len = fdt_pack_reg(blob, tmp, start, size, banks); err = fdt_setprop(blob, nodeoffset, "reg", tmp, len); if (err < 0) { -- cgit v1.1 From f18295d3837c282f10167502e25a964abb04acf7 Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:04 +0900 Subject: fdt_support: fix an endian bug of fdt_initrd() Data written to DTB must be converted to big endian order. It is usually done by using cpu_to_fdt32(), cpu_to_fdt64(), etc. fdt_initrd() invoked write_cell(), which always swaps byte order. It means the function only worked on little endian architectures. (On big endian architectures, the byte order should be kept as it is) This commit uses cpu_to_fdt32() and cpu_to_fdt64() and deletes write_cell(). Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index ae714e7..324d6b9 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -32,18 +32,6 @@ static int get_cells_len(const void *fdt, const char *nr_cells_name) return 4; } -/* - * Write a 4 or 8 byte big endian cell - */ -static void write_cell(u8 *addr, u64 val, int size) -{ - int shift = (size - 1) * 8; - while (size-- > 0) { - *addr++ = (val >> shift) & 0xff; - shift -= 8; - } -} - /** * fdt_getprop_u32_default_node - Return a node's property or a default * @@ -212,11 +200,21 @@ static int fdt_fixup_stdout(void *fdt, int chosenoff) } #endif +static inline int fdt_setprop_uxx(void *fdt, int nodeoffset, const char *name, + uint64_t val, int is_u64) +{ + if (is_u64) + return fdt_setprop_u64(fdt, nodeoffset, name, val); + else + return fdt_setprop_u32(fdt, nodeoffset, name, (uint32_t)val); +} + + int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) { - int nodeoffset, addr_cell_len; + int nodeoffset; int err, j, total; - fdt64_t tmp; + int is_u64; uint64_t addr, size; /* find or create "/chosen" node. */ @@ -248,19 +246,20 @@ int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) return err; } - addr_cell_len = get_cells_len(fdt, "#address-cells"); + is_u64 = (get_cells_len(fdt, "#address-cells") == 8); + + err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-start", + (uint64_t)initrd_start, is_u64); - write_cell((u8 *)&tmp, initrd_start, addr_cell_len); - err = fdt_setprop(fdt, nodeoffset, - "linux,initrd-start", &tmp, addr_cell_len); if (err < 0) { printf("WARNING: could not set linux,initrd-start %s.\n", fdt_strerror(err)); return err; } - write_cell((u8 *)&tmp, initrd_end, addr_cell_len); - err = fdt_setprop(fdt, nodeoffset, - "linux,initrd-end", &tmp, addr_cell_len); + + err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-end", + (uint64_t)initrd_end, is_u64); + if (err < 0) { printf("WARNING: could not set linux,initrd-end %s.\n", fdt_strerror(err)); -- cgit v1.1 From 50babaf852e3b48680f7ea782a756043f64f8fe2 Mon Sep 17 00:00:00 2001 From: Masahiro Yamada Date: Fri, 18 Apr 2014 17:41:05 +0900 Subject: fdt_support: correct the return condition of fdt_initrd() Before this commit, fdt_initrd() just returned if initrd start address is zero. But it is possible if the RAM is located at address 0. This commit makes the return condition more reasonable: Just return if the size of initrd is zero. Signed-off-by: Masahiro Yamada Acked-by: Simon Glass --- common/fdt_support.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/fdt_support.c b/common/fdt_support.c index 324d6b9..7927a83 100644 --- a/common/fdt_support.c +++ b/common/fdt_support.c @@ -217,15 +217,15 @@ int fdt_initrd(void *fdt, ulong initrd_start, ulong initrd_end) int is_u64; uint64_t addr, size; + /* just return if the size of initrd is zero */ + if (initrd_start == initrd_end) + return 0; + /* find or create "/chosen" node. */ nodeoffset = fdt_find_or_add_subnode(fdt, 0, "chosen"); if (nodeoffset < 0) return nodeoffset; - /* just return if initrd_start/end aren't valid */ - if ((initrd_start == 0) || (initrd_end == 0)) - return 0; - total = fdt_num_mem_rsv(fdt); /* -- cgit v1.1 From 04819a4ff1c93972ac46aedd3f17becbd5e0b588 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:41 -0600 Subject: hash: Use uint8_t in preference to u8 This type is more readily available on the host compiler, so use it instead. Signed-off-by: Simon Glass --- common/hash.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'common') diff --git a/common/hash.c b/common/hash.c index 237bd04..3d95378 100644 --- a/common/hash.c +++ b/common/hash.c @@ -187,7 +187,7 @@ static struct hash_algo hash_algo[] = { * @allow_env_vars: non-zero to permit storing the result to an * variable environment */ -static void store_result(struct hash_algo *algo, const u8 *sum, +static void store_result(struct hash_algo *algo, const uint8_t *sum, const char *dest, int allow_env_vars) { unsigned int i; @@ -243,8 +243,8 @@ static void store_result(struct hash_algo *algo, const u8 *sum, * address, and the * prefix is not expected. * @return 0 if ok, non-zero on error */ -static int parse_verify_sum(struct hash_algo *algo, char *verify_str, u8 *vsum, - int allow_env_vars) +static int parse_verify_sum(struct hash_algo *algo, char *verify_str, + uint8_t *vsum, int allow_env_vars) { int env_var = 0; @@ -311,7 +311,7 @@ int hash_lookup_algo(const char *algo_name, struct hash_algo **algop) return -EPROTONOSUPPORT; } -void hash_show(struct hash_algo *algo, ulong addr, ulong len, u8 *output) +void hash_show(struct hash_algo *algo, ulong addr, ulong len, uint8_t *output) { int i; @@ -355,8 +355,8 @@ int hash_command(const char *algo_name, int flags, cmd_tbl_t *cmdtp, int flag, if (multi_hash()) { struct hash_algo *algo; - u8 output[HASH_MAX_DIGEST_SIZE]; - u8 vsum[HASH_MAX_DIGEST_SIZE]; + uint8_t output[HASH_MAX_DIGEST_SIZE]; + uint8_t vsum[HASH_MAX_DIGEST_SIZE]; void *buf; if (hash_lookup_algo(algo_name, &algo)) { -- cgit v1.1 From 12df2abe3e159d622701611766c085b860329f78 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:45 -0600 Subject: Reverse the meaning of the fit_config_verify() return code It is more common to have 0 mean OK, and -ve mean error. Change this function to work the same way to avoid confusion. Signed-off-by: Simon Glass --- common/cmd_fdt.c | 2 +- common/image-fit.c | 2 +- common/image-sig.c | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/cmd_fdt.c b/common/cmd_fdt.c index 6831af4..e86d992 100644 --- a/common/cmd_fdt.c +++ b/common/cmd_fdt.c @@ -612,7 +612,7 @@ static int do_fdt(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) } ret = fit_config_verify(working_fdt, cfg_noffset); - if (ret == 1) + if (ret == 0) return CMD_RET_SUCCESS; else return CMD_RET_FAILURE; diff --git a/common/image-fit.c b/common/image-fit.c index 732505a..40c7e27 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -1534,7 +1534,7 @@ int fit_image_load(bootm_headers_t *images, const char *prop_name, ulong addr, images->fit_uname_cfg = fit_uname_config; if (IMAGE_ENABLE_VERIFY && images->verify) { puts(" Verifying Hash Integrity ... "); - if (!fit_config_verify(fit, cfg_noffset)) { + if (fit_config_verify(fit, cfg_noffset)) { puts("Bad Data Hash\n"); bootstage_error(bootstage_id + BOOTSTAGE_SUB_HASH); diff --git a/common/image-sig.c b/common/image-sig.c index 72284eb..48788f9 100644 --- a/common/image-sig.c +++ b/common/image-sig.c @@ -467,6 +467,6 @@ int fit_config_verify_required_sigs(const void *fit, int conf_noffset, int fit_config_verify(const void *fit, int conf_noffset) { - return !fit_config_verify_required_sigs(fit, conf_noffset, - gd_fdt_blob()); + return fit_config_verify_required_sigs(fit, conf_noffset, + gd_fdt_blob()); } -- cgit v1.1 From b639640371ed38c76602387af865b814967473ba Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:46 -0600 Subject: bootm: Split out code from cmd_bootm.c This file has code in three different categories: - Command processing - OS-specific boot code - Locating images and setting up to boot Only the first category really belongs in a file called cmd_bootm.c. Leave the command processing code where it is. Split out the OS-specific boot code into bootm_os.c. Split out the other code into bootm.c Header files and extern declarations are tidied but otherwise no code changes are made, to make it easier to review. Signed-off-by: Simon Glass --- common/Makefile | 2 +- common/bootm.c | 812 +++++++++++++++++++++++++++++++ common/bootm_os.c | 480 +++++++++++++++++++ common/cmd_bootm.c | 1345 +--------------------------------------------------- 4 files changed, 1301 insertions(+), 1338 deletions(-) create mode 100644 common/bootm.c create mode 100644 common/bootm_os.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index 391a8d6..f6cd980 100644 --- a/common/Makefile +++ b/common/Makefile @@ -40,7 +40,7 @@ obj-$(CONFIG_SYS_GENERIC_BOARD) += board_r.o # core command obj-y += cmd_boot.o -obj-$(CONFIG_CMD_BOOTM) += cmd_bootm.o +obj-$(CONFIG_CMD_BOOTM) += cmd_bootm.o bootm.o bootm_os.o obj-y += cmd_help.o obj-y += cmd_version.o diff --git a/common/bootm.c b/common/bootm.c new file mode 100644 index 0000000..27a7f02 --- /dev/null +++ b/common/bootm.c @@ -0,0 +1,812 @@ +/* + * (C) Copyright 2000-2009 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CONFIG_CMD_USB) +#include +#endif + +DECLARE_GLOBAL_DATA_PTR; + +#ifndef CONFIG_SYS_BOOTM_LEN +/* use 8MByte as default max gunzip size */ +#define CONFIG_SYS_BOOTM_LEN 0x800000 +#endif + +#define IH_INITRD_ARCH IH_ARCH_DEFAULT + +static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[], bootm_headers_t *images, + ulong *os_data, ulong *os_len); + +#ifdef CONFIG_LMB +static void boot_start_lmb(bootm_headers_t *images) +{ + ulong mem_start; + phys_size_t mem_size; + + lmb_init(&images->lmb); + + mem_start = getenv_bootm_low(); + mem_size = getenv_bootm_size(); + + lmb_add(&images->lmb, (phys_addr_t)mem_start, mem_size); + + arch_lmb_reserve(&images->lmb); + board_lmb_reserve(&images->lmb); +} +#else +#define lmb_reserve(lmb, base, size) +static inline void boot_start_lmb(bootm_headers_t *images) { } +#endif + +static int bootm_start(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[]) +{ + memset((void *)&images, 0, sizeof(images)); + images.verify = getenv_yesno("verify"); + + boot_start_lmb(&images); + + bootstage_mark_name(BOOTSTAGE_ID_BOOTM_START, "bootm_start"); + images.state = BOOTM_STATE_START; + + return 0; +} + +static int bootm_find_os(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[]) +{ + const void *os_hdr; + bool ep_found = false; + + /* get kernel image header, start address and length */ + os_hdr = boot_get_kernel(cmdtp, flag, argc, argv, + &images, &images.os.image_start, &images.os.image_len); + if (images.os.image_len == 0) { + puts("ERROR: can't get kernel image!\n"); + return 1; + } + + /* get image parameters */ + switch (genimg_get_format(os_hdr)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) + case IMAGE_FORMAT_LEGACY: + images.os.type = image_get_type(os_hdr); + images.os.comp = image_get_comp(os_hdr); + images.os.os = image_get_os(os_hdr); + + images.os.end = image_get_image_end(os_hdr); + images.os.load = image_get_load(os_hdr); + break; +#endif +#if defined(CONFIG_FIT) + case IMAGE_FORMAT_FIT: + if (fit_image_get_type(images.fit_hdr_os, + images.fit_noffset_os, + &images.os.type)) { + puts("Can't get image type!\n"); + bootstage_error(BOOTSTAGE_ID_FIT_TYPE); + return 1; + } + + if (fit_image_get_comp(images.fit_hdr_os, + images.fit_noffset_os, + &images.os.comp)) { + puts("Can't get image compression!\n"); + bootstage_error(BOOTSTAGE_ID_FIT_COMPRESSION); + return 1; + } + + if (fit_image_get_os(images.fit_hdr_os, images.fit_noffset_os, + &images.os.os)) { + puts("Can't get image OS!\n"); + bootstage_error(BOOTSTAGE_ID_FIT_OS); + return 1; + } + + images.os.end = fit_get_end(images.fit_hdr_os); + + if (fit_image_get_load(images.fit_hdr_os, images.fit_noffset_os, + &images.os.load)) { + puts("Can't get image load address!\n"); + bootstage_error(BOOTSTAGE_ID_FIT_LOADADDR); + return 1; + } + break; +#endif +#ifdef CONFIG_ANDROID_BOOT_IMAGE + case IMAGE_FORMAT_ANDROID: + images.os.type = IH_TYPE_KERNEL; + images.os.comp = IH_COMP_NONE; + images.os.os = IH_OS_LINUX; + images.ep = images.os.load; + ep_found = true; + + images.os.end = android_image_get_end(os_hdr); + images.os.load = android_image_get_kload(os_hdr); + break; +#endif + default: + puts("ERROR: unknown image format type!\n"); + return 1; + } + + /* find kernel entry point */ + if (images.legacy_hdr_valid) { + images.ep = image_get_ep(&images.legacy_hdr_os_copy); +#if defined(CONFIG_FIT) + } else if (images.fit_uname_os) { + int ret; + + ret = fit_image_get_entry(images.fit_hdr_os, + images.fit_noffset_os, &images.ep); + if (ret) { + puts("Can't get entry point property!\n"); + return 1; + } +#endif + } else if (!ep_found) { + puts("Could not find kernel entry point!\n"); + return 1; + } + + if (images.os.type == IH_TYPE_KERNEL_NOLOAD) { + images.os.load = images.os.image_start; + images.ep += images.os.load; + } + + images.os.start = (ulong)os_hdr; + + return 0; +} + +static int bootm_find_ramdisk(int flag, int argc, char * const argv[]) +{ + int ret; + + /* find ramdisk */ + ret = boot_get_ramdisk(argc, argv, &images, IH_INITRD_ARCH, + &images.rd_start, &images.rd_end); + if (ret) { + puts("Ramdisk image is corrupt or invalid\n"); + return 1; + } + + return 0; +} + +#if defined(CONFIG_OF_LIBFDT) +static int bootm_find_fdt(int flag, int argc, char * const argv[]) +{ + int ret; + + /* find flattened device tree */ + ret = boot_get_fdt(flag, argc, argv, IH_ARCH_DEFAULT, &images, + &images.ft_addr, &images.ft_len); + if (ret) { + puts("Could not find a valid device tree\n"); + return 1; + } + + set_working_fdt_addr(images.ft_addr); + + return 0; +} +#endif + +int bootm_find_ramdisk_fdt(int flag, int argc, char * const argv[]) +{ + if (bootm_find_ramdisk(flag, argc, argv)) + return 1; + +#if defined(CONFIG_OF_LIBFDT) + if (bootm_find_fdt(flag, argc, argv)) + return 1; +#endif + + return 0; +} + +static int bootm_find_other(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[]) +{ + if (((images.os.type == IH_TYPE_KERNEL) || + (images.os.type == IH_TYPE_KERNEL_NOLOAD) || + (images.os.type == IH_TYPE_MULTI)) && + (images.os.os == IH_OS_LINUX || + images.os.os == IH_OS_VXWORKS)) + return bootm_find_ramdisk_fdt(flag, argc, argv); + + return 0; +} + +static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, + int boot_progress) +{ + image_info_t os = images->os; + uint8_t comp = os.comp; + ulong load = os.load; + ulong blob_start = os.start; + ulong blob_end = os.end; + ulong image_start = os.image_start; + ulong image_len = os.image_len; + __maybe_unused uint unc_len = CONFIG_SYS_BOOTM_LEN; + int no_overlap = 0; + void *load_buf, *image_buf; +#if defined(CONFIG_LZMA) || defined(CONFIG_LZO) + int ret; +#endif /* defined(CONFIG_LZMA) || defined(CONFIG_LZO) */ + + const char *type_name = genimg_get_type_name(os.type); + + load_buf = map_sysmem(load, unc_len); + image_buf = map_sysmem(image_start, image_len); + switch (comp) { + case IH_COMP_NONE: + if (load == image_start) { + printf(" XIP %s ... ", type_name); + no_overlap = 1; + } else { + printf(" Loading %s ... ", type_name); + memmove_wd(load_buf, image_buf, image_len, CHUNKSZ); + } + *load_end = load + image_len; + break; +#ifdef CONFIG_GZIP + case IH_COMP_GZIP: + printf(" Uncompressing %s ... ", type_name); + if (gunzip(load_buf, unc_len, image_buf, &image_len) != 0) { + puts("GUNZIP: uncompress, out-of-mem or overwrite error - must RESET board to recover\n"); + if (boot_progress) + bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); + return BOOTM_ERR_RESET; + } + + *load_end = load + image_len; + break; +#endif /* CONFIG_GZIP */ +#ifdef CONFIG_BZIP2 + case IH_COMP_BZIP2: + printf(" Uncompressing %s ... ", type_name); + /* + * If we've got less than 4 MB of malloc() space, + * use slower decompression algorithm which requires + * at most 2300 KB of memory. + */ + int i = BZ2_bzBuffToBuffDecompress(load_buf, &unc_len, + image_buf, image_len, + CONFIG_SYS_MALLOC_LEN < (4096 * 1024), 0); + if (i != BZ_OK) { + printf("BUNZIP2: uncompress or overwrite error %d - must RESET board to recover\n", + i); + if (boot_progress) + bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); + return BOOTM_ERR_RESET; + } + + *load_end = load + unc_len; + break; +#endif /* CONFIG_BZIP2 */ +#ifdef CONFIG_LZMA + case IH_COMP_LZMA: { + SizeT lzma_len = unc_len; + printf(" Uncompressing %s ... ", type_name); + + ret = lzmaBuffToBuffDecompress(load_buf, &lzma_len, + image_buf, image_len); + unc_len = lzma_len; + if (ret != SZ_OK) { + printf("LZMA: uncompress or overwrite error %d - must RESET board to recover\n", + ret); + bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); + return BOOTM_ERR_RESET; + } + *load_end = load + unc_len; + break; + } +#endif /* CONFIG_LZMA */ +#ifdef CONFIG_LZO + case IH_COMP_LZO: { + size_t size = unc_len; + + printf(" Uncompressing %s ... ", type_name); + + ret = lzop_decompress(image_buf, image_len, load_buf, &size); + if (ret != LZO_E_OK) { + printf("LZO: uncompress or overwrite error %d - must RESET board to recover\n", + ret); + if (boot_progress) + bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); + return BOOTM_ERR_RESET; + } + + *load_end = load + size; + break; + } +#endif /* CONFIG_LZO */ + default: + printf("Unimplemented compression type %d\n", comp); + return BOOTM_ERR_UNIMPLEMENTED; + } + + flush_cache(load, (*load_end - load) * sizeof(ulong)); + + puts("OK\n"); + debug(" kernel loaded at 0x%08lx, end = 0x%08lx\n", load, *load_end); + bootstage_mark(BOOTSTAGE_ID_KERNEL_LOADED); + + if (!no_overlap && (load < blob_end) && (*load_end > blob_start)) { + debug("images.os.start = 0x%lX, images.os.end = 0x%lx\n", + blob_start, blob_end); + debug("images.os.load = 0x%lx, load_end = 0x%lx\n", load, + *load_end); + + /* Check what type of image this is. */ + if (images->legacy_hdr_valid) { + if (image_get_type(&images->legacy_hdr_os_copy) + == IH_TYPE_MULTI) + puts("WARNING: legacy format multi component image overwritten\n"); + return BOOTM_ERR_OVERLAP; + } else { + puts("ERROR: new format image overwritten - must RESET the board to recover\n"); + bootstage_error(BOOTSTAGE_ID_OVERWRITTEN); + return BOOTM_ERR_RESET; + } + } + + return 0; +} + +/** + * bootm_disable_interrupts() - Disable interrupts in preparation for load/boot + * + * @return interrupt flag (0 if interrupts were disabled, non-zero if they were + * enabled) + */ +ulong bootm_disable_interrupts(void) +{ + ulong iflag; + + /* + * We have reached the point of no return: we are going to + * overwrite all exception vector code, so we cannot easily + * recover from any failures any more... + */ + iflag = disable_interrupts(); +#ifdef CONFIG_NETCONSOLE + /* Stop the ethernet stack if NetConsole could have left it up */ + eth_halt(); + eth_unregister(eth_get_dev()); +#endif + +#if defined(CONFIG_CMD_USB) + /* + * turn off USB to prevent the host controller from writing to the + * SDRAM while Linux is booting. This could happen (at least for OHCI + * controller), because the HCCA (Host Controller Communication Area) + * lies within the SDRAM and the host controller writes continously to + * this area (as busmaster!). The HccaFrameNumber is for example + * updated every 1 ms within the HCCA structure in SDRAM! For more + * details see the OpenHCI specification. + */ + usb_stop(); +#endif + return iflag; +} + +#if defined(CONFIG_SILENT_CONSOLE) && !defined(CONFIG_SILENT_U_BOOT_ONLY) + +#define CONSOLE_ARG "console=" +#define CONSOLE_ARG_LEN (sizeof(CONSOLE_ARG) - 1) + +static void fixup_silent_linux(void) +{ + char *buf; + const char *env_val; + char *cmdline = getenv("bootargs"); + int want_silent; + + /* + * Only fix cmdline when requested. The environment variable can be: + * + * no - we never fixup + * yes - we always fixup + * unset - we rely on the console silent flag + */ + want_silent = getenv_yesno("silent_linux"); + if (want_silent == 0) + return; + else if (want_silent == -1 && !(gd->flags & GD_FLG_SILENT)) + return; + + debug("before silent fix-up: %s\n", cmdline); + if (cmdline && (cmdline[0] != '\0')) { + char *start = strstr(cmdline, CONSOLE_ARG); + + /* Allocate space for maximum possible new command line */ + buf = malloc(strlen(cmdline) + 1 + CONSOLE_ARG_LEN + 1); + if (!buf) { + debug("%s: out of memory\n", __func__); + return; + } + + if (start) { + char *end = strchr(start, ' '); + int num_start_bytes = start - cmdline + CONSOLE_ARG_LEN; + + strncpy(buf, cmdline, num_start_bytes); + if (end) + strcpy(buf + num_start_bytes, end); + else + buf[num_start_bytes] = '\0'; + } else { + sprintf(buf, "%s %s", cmdline, CONSOLE_ARG); + } + env_val = buf; + } else { + buf = NULL; + env_val = CONSOLE_ARG; + } + + setenv("bootargs", env_val); + debug("after silent fix-up: %s\n", env_val); + free(buf); +} +#endif /* CONFIG_SILENT_CONSOLE */ + +/** + * Execute selected states of the bootm command. + * + * Note the arguments to this state must be the first argument, Any 'bootm' + * or sub-command arguments must have already been taken. + * + * Note that if states contains more than one flag it MUST contain + * BOOTM_STATE_START, since this handles and consumes the command line args. + * + * Also note that aside from boot_os_fn functions and bootm_load_os no other + * functions we store the return value of in 'ret' may use a negative return + * value, without special handling. + * + * @param cmdtp Pointer to bootm command table entry + * @param flag Command flags (CMD_FLAG_...) + * @param argc Number of subcommand arguments (0 = no arguments) + * @param argv Arguments + * @param states Mask containing states to run (BOOTM_STATE_...) + * @param images Image header information + * @param boot_progress 1 to show boot progress, 0 to not do this + * @return 0 if ok, something else on error. Some errors will cause this + * function to perform a reboot! If states contains BOOTM_STATE_OS_GO + * then the intent is to boot an OS, so this function will not return + * unless the image type is standalone. + */ +int do_bootm_states(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[], + int states, bootm_headers_t *images, int boot_progress) +{ + boot_os_fn *boot_fn; + ulong iflag = 0; + int ret = 0, need_boot_fn; + + images->state |= states; + + /* + * Work through the states and see how far we get. We stop on + * any error. + */ + if (states & BOOTM_STATE_START) + ret = bootm_start(cmdtp, flag, argc, argv); + + if (!ret && (states & BOOTM_STATE_FINDOS)) + ret = bootm_find_os(cmdtp, flag, argc, argv); + + if (!ret && (states & BOOTM_STATE_FINDOTHER)) { + ret = bootm_find_other(cmdtp, flag, argc, argv); + argc = 0; /* consume the args */ + } + + /* Load the OS */ + if (!ret && (states & BOOTM_STATE_LOADOS)) { + ulong load_end; + + iflag = bootm_disable_interrupts(); + ret = bootm_load_os(images, &load_end, 0); + if (ret == 0) + lmb_reserve(&images->lmb, images->os.load, + (load_end - images->os.load)); + else if (ret && ret != BOOTM_ERR_OVERLAP) + goto err; + else if (ret == BOOTM_ERR_OVERLAP) + ret = 0; +#if defined(CONFIG_SILENT_CONSOLE) && !defined(CONFIG_SILENT_U_BOOT_ONLY) + if (images->os.os == IH_OS_LINUX) + fixup_silent_linux(); +#endif + } + + /* Relocate the ramdisk */ +#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH + if (!ret && (states & BOOTM_STATE_RAMDISK)) { + ulong rd_len = images->rd_end - images->rd_start; + + ret = boot_ramdisk_high(&images->lmb, images->rd_start, + rd_len, &images->initrd_start, &images->initrd_end); + if (!ret) { + setenv_hex("initrd_start", images->initrd_start); + setenv_hex("initrd_end", images->initrd_end); + } + } +#endif +#if defined(CONFIG_OF_LIBFDT) && defined(CONFIG_LMB) + if (!ret && (states & BOOTM_STATE_FDT)) { + boot_fdt_add_mem_rsv_regions(&images->lmb, images->ft_addr); + ret = boot_relocate_fdt(&images->lmb, &images->ft_addr, + &images->ft_len); + } +#endif + + /* From now on, we need the OS boot function */ + if (ret) + return ret; + boot_fn = bootm_os_get_boot_func(images->os.os); + need_boot_fn = states & (BOOTM_STATE_OS_CMDLINE | + BOOTM_STATE_OS_BD_T | BOOTM_STATE_OS_PREP | + BOOTM_STATE_OS_FAKE_GO | BOOTM_STATE_OS_GO); + if (boot_fn == NULL && need_boot_fn) { + if (iflag) + enable_interrupts(); + printf("ERROR: booting os '%s' (%d) is not supported\n", + genimg_get_os_name(images->os.os), images->os.os); + bootstage_error(BOOTSTAGE_ID_CHECK_BOOT_OS); + return 1; + } + + /* Call various other states that are not generally used */ + if (!ret && (states & BOOTM_STATE_OS_CMDLINE)) + ret = boot_fn(BOOTM_STATE_OS_CMDLINE, argc, argv, images); + if (!ret && (states & BOOTM_STATE_OS_BD_T)) + ret = boot_fn(BOOTM_STATE_OS_BD_T, argc, argv, images); + if (!ret && (states & BOOTM_STATE_OS_PREP)) + ret = boot_fn(BOOTM_STATE_OS_PREP, argc, argv, images); + +#ifdef CONFIG_TRACE + /* Pretend to run the OS, then run a user command */ + if (!ret && (states & BOOTM_STATE_OS_FAKE_GO)) { + char *cmd_list = getenv("fakegocmd"); + + ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_FAKE_GO, + images, boot_fn); + if (!ret && cmd_list) + ret = run_command_list(cmd_list, -1, flag); + } +#endif + + /* Check for unsupported subcommand. */ + if (ret) { + puts("subcommand not supported\n"); + return ret; + } + + /* Now run the OS! We hope this doesn't return */ + if (!ret && (states & BOOTM_STATE_OS_GO)) + ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_GO, + images, boot_fn); + + /* Deal with any fallout */ +err: + if (iflag) + enable_interrupts(); + + if (ret == BOOTM_ERR_UNIMPLEMENTED) + bootstage_error(BOOTSTAGE_ID_DECOMP_UNIMPL); + else if (ret == BOOTM_ERR_RESET) + do_reset(cmdtp, flag, argc, argv); + + return ret; +} + +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) +/** + * image_get_kernel - verify legacy format kernel image + * @img_addr: in RAM address of the legacy format image to be verified + * @verify: data CRC verification flag + * + * image_get_kernel() verifies legacy image integrity and returns pointer to + * legacy image header if image verification was completed successfully. + * + * returns: + * pointer to a legacy image header if valid image was found + * otherwise return NULL + */ +static image_header_t *image_get_kernel(ulong img_addr, int verify) +{ + image_header_t *hdr = (image_header_t *)img_addr; + + if (!image_check_magic(hdr)) { + puts("Bad Magic Number\n"); + bootstage_error(BOOTSTAGE_ID_CHECK_MAGIC); + return NULL; + } + bootstage_mark(BOOTSTAGE_ID_CHECK_HEADER); + + if (!image_check_hcrc(hdr)) { + puts("Bad Header Checksum\n"); + bootstage_error(BOOTSTAGE_ID_CHECK_HEADER); + return NULL; + } + + bootstage_mark(BOOTSTAGE_ID_CHECK_CHECKSUM); + image_print_contents(hdr); + + if (verify) { + puts(" Verifying Checksum ... "); + if (!image_check_dcrc(hdr)) { + printf("Bad Data CRC\n"); + bootstage_error(BOOTSTAGE_ID_CHECK_CHECKSUM); + return NULL; + } + puts("OK\n"); + } + bootstage_mark(BOOTSTAGE_ID_CHECK_ARCH); + + if (!image_check_target_arch(hdr)) { + printf("Unsupported Architecture 0x%x\n", image_get_arch(hdr)); + bootstage_error(BOOTSTAGE_ID_CHECK_ARCH); + return NULL; + } + return hdr; +} +#endif + +/** + * boot_get_kernel - find kernel image + * @os_data: pointer to a ulong variable, will hold os data start address + * @os_len: pointer to a ulong variable, will hold os data length + * + * boot_get_kernel() tries to find a kernel image, verifies its integrity + * and locates kernel data. + * + * returns: + * pointer to image header if valid image was found, plus kernel start + * address and length, otherwise NULL + */ +static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, + char * const argv[], bootm_headers_t *images, + ulong *os_data, ulong *os_len) +{ +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) + image_header_t *hdr; +#endif + ulong img_addr; + const void *buf; +#if defined(CONFIG_FIT) + const char *fit_uname_config = NULL; + const char *fit_uname_kernel = NULL; + int os_noffset; +#endif + + /* find out kernel image address */ + if (argc < 1) { + img_addr = load_addr; + debug("* kernel: default image load address = 0x%08lx\n", + load_addr); +#if defined(CONFIG_FIT) + } else if (fit_parse_conf(argv[0], load_addr, &img_addr, + &fit_uname_config)) { + debug("* kernel: config '%s' from image at 0x%08lx\n", + fit_uname_config, img_addr); + } else if (fit_parse_subimage(argv[0], load_addr, &img_addr, + &fit_uname_kernel)) { + debug("* kernel: subimage '%s' from image at 0x%08lx\n", + fit_uname_kernel, img_addr); +#endif + } else { + img_addr = simple_strtoul(argv[0], NULL, 16); + debug("* kernel: cmdline image address = 0x%08lx\n", + img_addr); + } + + bootstage_mark(BOOTSTAGE_ID_CHECK_MAGIC); + + /* copy from dataflash if needed */ + img_addr = genimg_get_image(img_addr); + + /* check image type, for FIT images get FIT kernel node */ + *os_data = *os_len = 0; + buf = map_sysmem(img_addr, 0); + switch (genimg_get_format(buf)) { +#if defined(CONFIG_IMAGE_FORMAT_LEGACY) + case IMAGE_FORMAT_LEGACY: + printf("## Booting kernel from Legacy Image at %08lx ...\n", + img_addr); + hdr = image_get_kernel(img_addr, images->verify); + if (!hdr) + return NULL; + bootstage_mark(BOOTSTAGE_ID_CHECK_IMAGETYPE); + + /* get os_data and os_len */ + switch (image_get_type(hdr)) { + case IH_TYPE_KERNEL: + case IH_TYPE_KERNEL_NOLOAD: + *os_data = image_get_data(hdr); + *os_len = image_get_data_size(hdr); + break; + case IH_TYPE_MULTI: + image_multi_getimg(hdr, 0, os_data, os_len); + break; + case IH_TYPE_STANDALONE: + *os_data = image_get_data(hdr); + *os_len = image_get_data_size(hdr); + break; + default: + printf("Wrong Image Type for %s command\n", + cmdtp->name); + bootstage_error(BOOTSTAGE_ID_CHECK_IMAGETYPE); + return NULL; + } + + /* + * copy image header to allow for image overwrites during + * kernel decompression. + */ + memmove(&images->legacy_hdr_os_copy, hdr, + sizeof(image_header_t)); + + /* save pointer to image header */ + images->legacy_hdr_os = hdr; + + images->legacy_hdr_valid = 1; + bootstage_mark(BOOTSTAGE_ID_DECOMP_IMAGE); + break; +#endif +#if defined(CONFIG_FIT) + case IMAGE_FORMAT_FIT: + os_noffset = fit_image_load(images, FIT_KERNEL_PROP, + img_addr, + &fit_uname_kernel, &fit_uname_config, + IH_ARCH_DEFAULT, IH_TYPE_KERNEL, + BOOTSTAGE_ID_FIT_KERNEL_START, + FIT_LOAD_IGNORED, os_data, os_len); + if (os_noffset < 0) + return NULL; + + images->fit_hdr_os = map_sysmem(img_addr, 0); + images->fit_uname_os = fit_uname_kernel; + images->fit_uname_cfg = fit_uname_config; + images->fit_noffset_os = os_noffset; + break; +#endif +#ifdef CONFIG_ANDROID_BOOT_IMAGE + case IMAGE_FORMAT_ANDROID: + printf("## Booting Android Image at 0x%08lx ...\n", img_addr); + if (android_image_get_kernel((void *)img_addr, images->verify, + os_data, os_len)) + return NULL; + break; +#endif + default: + printf("Wrong Image Format for %s command\n", cmdtp->name); + bootstage_error(BOOTSTAGE_ID_FIT_KERNEL_INFO); + return NULL; + } + + debug(" kernel data at 0x%08lx, len = 0x%08lx (%ld)\n", + *os_data, *os_len, *os_len); + + return buf; +} diff --git a/common/bootm_os.c b/common/bootm_os.c new file mode 100644 index 0000000..f7769ac --- /dev/null +++ b/common/bootm_os.c @@ -0,0 +1,480 @@ +/* + * (C) Copyright 2000-2009 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +static int do_bootm_standalone(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + char *s; + int (*appl)(int, char *const[]); + + /* Don't start if "autostart" is set to "no" */ + s = getenv("autostart"); + if ((s != NULL) && !strcmp(s, "no")) { + setenv_hex("filesize", images->os.image_len); + return 0; + } + appl = (int (*)(int, char * const []))images->ep; + appl(argc, argv); + return 0; +} + +/*******************************************************************/ +/* OS booting routines */ +/*******************************************************************/ + +#if defined(CONFIG_BOOTM_NETBSD) || defined(CONFIG_BOOTM_PLAN9) +static void copy_args(char *dest, int argc, char * const argv[], char delim) +{ + int i; + + for (i = 0; i < argc; i++) { + if (i > 0) + *dest++ = delim; + strcpy(dest, argv[i]); + dest += strlen(argv[i]); + } +} +#endif + +#ifdef CONFIG_BOOTM_NETBSD +static int do_bootm_netbsd(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + void (*loader)(bd_t *, image_header_t *, char *, char *); + image_header_t *os_hdr, *hdr; + ulong kernel_data, kernel_len; + char *consdev; + char *cmdline; + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("NetBSD"); + return 1; + } +#endif + hdr = images->legacy_hdr_os; + + /* + * Booting a (NetBSD) kernel image + * + * This process is pretty similar to a standalone application: + * The (first part of an multi-) image must be a stage-2 loader, + * which in turn is responsible for loading & invoking the actual + * kernel. The only differences are the parameters being passed: + * besides the board info strucure, the loader expects a command + * line, the name of the console device, and (optionally) the + * address of the original image header. + */ + os_hdr = NULL; + if (image_check_type(&images->legacy_hdr_os_copy, IH_TYPE_MULTI)) { + image_multi_getimg(hdr, 1, &kernel_data, &kernel_len); + if (kernel_len) + os_hdr = hdr; + } + + consdev = ""; +#if defined(CONFIG_8xx_CONS_SMC1) + consdev = "smc1"; +#elif defined(CONFIG_8xx_CONS_SMC2) + consdev = "smc2"; +#elif defined(CONFIG_8xx_CONS_SCC2) + consdev = "scc2"; +#elif defined(CONFIG_8xx_CONS_SCC3) + consdev = "scc3"; +#endif + + if (argc > 0) { + ulong len; + int i; + + for (i = 0, len = 0; i < argc; i += 1) + len += strlen(argv[i]) + 1; + cmdline = malloc(len); + copy_args(cmdline, argc, argv, ' '); + } else { + cmdline = getenv("bootargs"); + if (cmdline == NULL) + cmdline = ""; + } + + loader = (void (*)(bd_t *, image_header_t *, char *, char *))images->ep; + + printf("## Transferring control to NetBSD stage-2 loader (at address %08lx) ...\n", + (ulong)loader); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + + /* + * NetBSD Stage-2 Loader Parameters: + * arg[0]: pointer to board info data + * arg[1]: image load address + * arg[2]: char pointer to the console device to use + * arg[3]: char pointer to the boot arguments + */ + (*loader)(gd->bd, os_hdr, consdev, cmdline); + + return 1; +} +#endif /* CONFIG_BOOTM_NETBSD*/ + +#ifdef CONFIG_LYNXKDI +static int do_bootm_lynxkdi(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + image_header_t *hdr = &images->legacy_hdr_os_copy; + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("Lynx"); + return 1; + } +#endif + + lynxkdi_boot((image_header_t *)hdr); + + return 1; +} +#endif /* CONFIG_LYNXKDI */ + +#ifdef CONFIG_BOOTM_RTEMS +static int do_bootm_rtems(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + void (*entry_point)(bd_t *); + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("RTEMS"); + return 1; + } +#endif + + entry_point = (void (*)(bd_t *))images->ep; + + printf("## Transferring control to RTEMS (at address %08lx) ...\n", + (ulong)entry_point); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + + /* + * RTEMS Parameters: + * r3: ptr to board info data + */ + (*entry_point)(gd->bd); + + return 1; +} +#endif /* CONFIG_BOOTM_RTEMS */ + +#if defined(CONFIG_BOOTM_OSE) +static int do_bootm_ose(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + void (*entry_point)(void); + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("OSE"); + return 1; + } +#endif + + entry_point = (void (*)(void))images->ep; + + printf("## Transferring control to OSE (at address %08lx) ...\n", + (ulong)entry_point); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + + /* + * OSE Parameters: + * None + */ + (*entry_point)(); + + return 1; +} +#endif /* CONFIG_BOOTM_OSE */ + +#if defined(CONFIG_BOOTM_PLAN9) +static int do_bootm_plan9(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + void (*entry_point)(void); + char *s; + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("Plan 9"); + return 1; + } +#endif + + /* See README.plan9 */ + s = getenv("confaddr"); + if (s != NULL) { + char *confaddr = (char *)simple_strtoul(s, NULL, 16); + + if (argc > 0) { + copy_args(confaddr, argc, argv, '\n'); + } else { + s = getenv("bootargs"); + if (s != NULL) + strcpy(confaddr, s); + } + } + + entry_point = (void (*)(void))images->ep; + + printf("## Transferring control to Plan 9 (at address %08lx) ...\n", + (ulong)entry_point); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + + /* + * Plan 9 Parameters: + * None + */ + (*entry_point)(); + + return 1; +} +#endif /* CONFIG_BOOTM_PLAN9 */ + +#if defined(CONFIG_BOOTM_VXWORKS) && \ + (defined(CONFIG_PPC) || defined(CONFIG_ARM)) + +void do_bootvx_fdt(bootm_headers_t *images) +{ +#if defined(CONFIG_OF_LIBFDT) + int ret; + char *bootline; + ulong of_size = images->ft_len; + char **of_flat_tree = &images->ft_addr; + struct lmb *lmb = &images->lmb; + + if (*of_flat_tree) { + boot_fdt_add_mem_rsv_regions(lmb, *of_flat_tree); + + ret = boot_relocate_fdt(lmb, of_flat_tree, &of_size); + if (ret) + return; + + ret = fdt_add_subnode(*of_flat_tree, 0, "chosen"); + if ((ret >= 0 || ret == -FDT_ERR_EXISTS)) { + bootline = getenv("bootargs"); + if (bootline) { + ret = fdt_find_and_setprop(*of_flat_tree, + "/chosen", "bootargs", + bootline, + strlen(bootline) + 1, 1); + if (ret < 0) { + printf("## ERROR: %s : %s\n", __func__, + fdt_strerror(ret)); + return; + } + } + } else { + printf("## ERROR: %s : %s\n", __func__, + fdt_strerror(ret)); + return; + } + } +#endif + + boot_prep_vxworks(images); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + +#if defined(CONFIG_OF_LIBFDT) + printf("## Starting vxWorks at 0x%08lx, device tree at 0x%08lx ...\n", + (ulong)images->ep, (ulong)*of_flat_tree); +#else + printf("## Starting vxWorks at 0x%08lx\n", (ulong)images->ep); +#endif + + boot_jump_vxworks(images); + + puts("## vxWorks terminated\n"); +} + +static int do_bootm_vxworks(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("VxWorks"); + return 1; + } +#endif + + do_bootvx_fdt(images); + + return 1; +} +#endif + +#if defined(CONFIG_CMD_ELF) +static int do_bootm_qnxelf(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + char *local_args[2]; + char str[16]; + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("QNX"); + return 1; + } +#endif + + sprintf(str, "%lx", images->ep); /* write entry-point into string */ + local_args[0] = argv[0]; + local_args[1] = str; /* and provide it via the arguments */ + do_bootelf(NULL, 0, 2, local_args); + + return 1; +} +#endif + +#ifdef CONFIG_INTEGRITY +static int do_bootm_integrity(int flag, int argc, char * const argv[], + bootm_headers_t *images) +{ + void (*entry_point)(void); + + if (flag != BOOTM_STATE_OS_GO) + return 0; + +#if defined(CONFIG_FIT) + if (!images->legacy_hdr_valid) { + fit_unsupported_reset("INTEGRITY"); + return 1; + } +#endif + + entry_point = (void (*)(void))images->ep; + + printf("## Transferring control to INTEGRITY (at address %08lx) ...\n", + (ulong)entry_point); + + bootstage_mark(BOOTSTAGE_ID_RUN_OS); + + /* + * INTEGRITY Parameters: + * None + */ + (*entry_point)(); + + return 1; +} +#endif + +static boot_os_fn *boot_os[] = { + [IH_OS_U_BOOT] = do_bootm_standalone, +#ifdef CONFIG_BOOTM_LINUX + [IH_OS_LINUX] = do_bootm_linux, +#endif +#ifdef CONFIG_BOOTM_NETBSD + [IH_OS_NETBSD] = do_bootm_netbsd, +#endif +#ifdef CONFIG_LYNXKDI + [IH_OS_LYNXOS] = do_bootm_lynxkdi, +#endif +#ifdef CONFIG_BOOTM_RTEMS + [IH_OS_RTEMS] = do_bootm_rtems, +#endif +#if defined(CONFIG_BOOTM_OSE) + [IH_OS_OSE] = do_bootm_ose, +#endif +#if defined(CONFIG_BOOTM_PLAN9) + [IH_OS_PLAN9] = do_bootm_plan9, +#endif +#if defined(CONFIG_BOOTM_VXWORKS) && \ + (defined(CONFIG_PPC) || defined(CONFIG_ARM)) + [IH_OS_VXWORKS] = do_bootm_vxworks, +#endif +#if defined(CONFIG_CMD_ELF) + [IH_OS_QNX] = do_bootm_qnxelf, +#endif +#ifdef CONFIG_INTEGRITY + [IH_OS_INTEGRITY] = do_bootm_integrity, +#endif +}; + +/* Allow for arch specific config before we boot */ +static void __arch_preboot_os(void) +{ + /* please define platform specific arch_preboot_os() */ +} +void arch_preboot_os(void) __attribute__((weak, alias("__arch_preboot_os"))); + +int boot_selected_os(int argc, char * const argv[], int state, + bootm_headers_t *images, boot_os_fn *boot_fn) +{ + arch_preboot_os(); + boot_fn(state, argc, argv, images); + + /* Stand-alone may return when 'autostart' is 'no' */ + if (images->os.type == IH_TYPE_STANDALONE || + state == BOOTM_STATE_OS_FAKE_GO) /* We expect to return */ + return 0; + bootstage_error(BOOTSTAGE_ID_BOOT_OS_RETURNED); +#ifdef DEBUG + puts("\n## Control returned to monitor - resetting...\n"); +#endif + return BOOTM_ERR_RESET; +} + +boot_os_fn *bootm_os_get_boot_func(int os) +{ +#ifdef CONFIG_NEEDS_MANUAL_RELOC + static bool relocated; + + if (!relocated) { + int i; + + /* relocate boot function table */ + for (i = 0; i < ARRAY_SIZE(boot_os); i++) + if (boot_os[i] != NULL) + boot_os[i] += gd->reloc_off; + + relocated = true; + } +#endif + return boot_os[os]; +} diff --git a/common/cmd_bootm.c b/common/cmd_bootm.c index c06f4b7..8b897c8 100644 --- a/common/cmd_bootm.c +++ b/common/cmd_bootm.c @@ -5,58 +5,25 @@ * SPDX-License-Identifier: GPL-2.0+ */ - /* * Boot support */ #include -#include +#include #include -#include -#include -#include -#include #include +#include #include -#include +#include +#include #include -#include #include - -#if defined(CONFIG_BOOTM_VXWORKS) && \ - (defined(CONFIG_PPC) || defined(CONFIG_ARM)) -#include -#endif - -#if defined(CONFIG_CMD_USB) -#include -#endif - -#if defined(CONFIG_OF_LIBFDT) -#include -#include -#endif - -#ifdef CONFIG_LZMA -#include -#include -#include -#endif /* CONFIG_LZMA */ - -#ifdef CONFIG_LZO -#include -#endif /* CONFIG_LZO */ +#include +#include +#include DECLARE_GLOBAL_DATA_PTR; -#ifndef CONFIG_SYS_BOOTM_LEN -#define CONFIG_SYS_BOOTM_LEN 0x800000 /* use 8MByte as default max gunzip size */ -#endif - -#ifdef CONFIG_BZIP2 -extern void bz_internal_error(int); -#endif - #if defined(CONFIG_CMD_IMI) static int image_info(unsigned long addr); #endif @@ -71,465 +38,8 @@ extern flash_info_t flash_info[]; /* info for FLASH chips */ static int do_imls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]); #endif -#include -#include - -#if defined(CONFIG_SILENT_CONSOLE) && !defined(CONFIG_SILENT_U_BOOT_ONLY) -static void fixup_silent_linux(void); -#endif - -static int do_bootm_standalone(int flag, int argc, char * const argv[], - bootm_headers_t *images); - -static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[], bootm_headers_t *images, - ulong *os_data, ulong *os_len); - -/* - * Continue booting an OS image; caller already has: - * - copied image header to global variable `header' - * - checked header magic number, checksums (both header & image), - * - verified image architecture (PPC) and type (KERNEL or MULTI), - * - loaded (first part of) image to header load address, - * - disabled interrupts. - * - * @flag: Flags indicating what to do (BOOTM_STATE_...) - * @argc: Number of arguments. Note that the arguments are shifted down - * so that 0 is the first argument not processed by U-Boot, and - * argc is adjusted accordingly. This avoids confusion as to how - * many arguments are available for the OS. - * @images: Pointers to os/initrd/fdt - * @return 1 on error. On success the OS boots so this function does - * not return. - */ -typedef int boot_os_fn(int flag, int argc, char * const argv[], - bootm_headers_t *images); - -#ifdef CONFIG_BOOTM_LINUX -extern boot_os_fn do_bootm_linux; -#endif -#ifdef CONFIG_BOOTM_NETBSD -static boot_os_fn do_bootm_netbsd; -#endif -#if defined(CONFIG_LYNXKDI) -static boot_os_fn do_bootm_lynxkdi; -extern void lynxkdi_boot(image_header_t *); -#endif -#ifdef CONFIG_BOOTM_RTEMS -static boot_os_fn do_bootm_rtems; -#endif -#if defined(CONFIG_BOOTM_OSE) -static boot_os_fn do_bootm_ose; -#endif -#if defined(CONFIG_BOOTM_PLAN9) -static boot_os_fn do_bootm_plan9; -#endif -#if defined(CONFIG_BOOTM_VXWORKS) && \ - (defined(CONFIG_PPC) || defined(CONFIG_ARM)) -static boot_os_fn do_bootm_vxworks; -#endif -#if defined(CONFIG_CMD_ELF) -static boot_os_fn do_bootm_qnxelf; -int do_bootvx(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]); -int do_bootelf(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]); -#endif -#if defined(CONFIG_INTEGRITY) -static boot_os_fn do_bootm_integrity; -#endif - -static boot_os_fn *boot_os[] = { - [IH_OS_U_BOOT] = do_bootm_standalone, -#ifdef CONFIG_BOOTM_LINUX - [IH_OS_LINUX] = do_bootm_linux, -#endif -#ifdef CONFIG_BOOTM_NETBSD - [IH_OS_NETBSD] = do_bootm_netbsd, -#endif -#ifdef CONFIG_LYNXKDI - [IH_OS_LYNXOS] = do_bootm_lynxkdi, -#endif -#ifdef CONFIG_BOOTM_RTEMS - [IH_OS_RTEMS] = do_bootm_rtems, -#endif -#if defined(CONFIG_BOOTM_OSE) - [IH_OS_OSE] = do_bootm_ose, -#endif -#if defined(CONFIG_BOOTM_PLAN9) - [IH_OS_PLAN9] = do_bootm_plan9, -#endif -#if defined(CONFIG_BOOTM_VXWORKS) && \ - (defined(CONFIG_PPC) || defined(CONFIG_ARM)) - [IH_OS_VXWORKS] = do_bootm_vxworks, -#endif -#if defined(CONFIG_CMD_ELF) - [IH_OS_QNX] = do_bootm_qnxelf, -#endif -#ifdef CONFIG_INTEGRITY - [IH_OS_INTEGRITY] = do_bootm_integrity, -#endif -}; - bootm_headers_t images; /* pointers to os/initrd/fdt images */ -/* Allow for arch specific config before we boot */ -static void __arch_preboot_os(void) -{ - /* please define platform specific arch_preboot_os() */ -} -void arch_preboot_os(void) __attribute__((weak, alias("__arch_preboot_os"))); - -#define IH_INITRD_ARCH IH_ARCH_DEFAULT - -#ifdef CONFIG_LMB -static void boot_start_lmb(bootm_headers_t *images) -{ - ulong mem_start; - phys_size_t mem_size; - - lmb_init(&images->lmb); - - mem_start = getenv_bootm_low(); - mem_size = getenv_bootm_size(); - - lmb_add(&images->lmb, (phys_addr_t)mem_start, mem_size); - - arch_lmb_reserve(&images->lmb); - board_lmb_reserve(&images->lmb); -} -#else -#define lmb_reserve(lmb, base, size) -static inline void boot_start_lmb(bootm_headers_t *images) { } -#endif - -static int bootm_start(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) -{ - memset((void *)&images, 0, sizeof(images)); - images.verify = getenv_yesno("verify"); - - boot_start_lmb(&images); - - bootstage_mark_name(BOOTSTAGE_ID_BOOTM_START, "bootm_start"); - images.state = BOOTM_STATE_START; - - return 0; -} - -static int bootm_find_os(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[]) -{ - const void *os_hdr; - bool ep_found = false; - - /* get kernel image header, start address and length */ - os_hdr = boot_get_kernel(cmdtp, flag, argc, argv, - &images, &images.os.image_start, &images.os.image_len); - if (images.os.image_len == 0) { - puts("ERROR: can't get kernel image!\n"); - return 1; - } - - /* get image parameters */ - switch (genimg_get_format(os_hdr)) { -#if defined(CONFIG_IMAGE_FORMAT_LEGACY) - case IMAGE_FORMAT_LEGACY: - images.os.type = image_get_type(os_hdr); - images.os.comp = image_get_comp(os_hdr); - images.os.os = image_get_os(os_hdr); - - images.os.end = image_get_image_end(os_hdr); - images.os.load = image_get_load(os_hdr); - break; -#endif -#if defined(CONFIG_FIT) - case IMAGE_FORMAT_FIT: - if (fit_image_get_type(images.fit_hdr_os, - images.fit_noffset_os, &images.os.type)) { - puts("Can't get image type!\n"); - bootstage_error(BOOTSTAGE_ID_FIT_TYPE); - return 1; - } - - if (fit_image_get_comp(images.fit_hdr_os, - images.fit_noffset_os, &images.os.comp)) { - puts("Can't get image compression!\n"); - bootstage_error(BOOTSTAGE_ID_FIT_COMPRESSION); - return 1; - } - - if (fit_image_get_os(images.fit_hdr_os, - images.fit_noffset_os, &images.os.os)) { - puts("Can't get image OS!\n"); - bootstage_error(BOOTSTAGE_ID_FIT_OS); - return 1; - } - - images.os.end = fit_get_end(images.fit_hdr_os); - - if (fit_image_get_load(images.fit_hdr_os, images.fit_noffset_os, - &images.os.load)) { - puts("Can't get image load address!\n"); - bootstage_error(BOOTSTAGE_ID_FIT_LOADADDR); - return 1; - } - break; -#endif -#ifdef CONFIG_ANDROID_BOOT_IMAGE - case IMAGE_FORMAT_ANDROID: - images.os.type = IH_TYPE_KERNEL; - images.os.comp = IH_COMP_NONE; - images.os.os = IH_OS_LINUX; - images.ep = images.os.load; - ep_found = true; - - images.os.end = android_image_get_end(os_hdr); - images.os.load = android_image_get_kload(os_hdr); - break; -#endif - default: - puts("ERROR: unknown image format type!\n"); - return 1; - } - - /* find kernel entry point */ - if (images.legacy_hdr_valid) { - images.ep = image_get_ep(&images.legacy_hdr_os_copy); -#if defined(CONFIG_FIT) - } else if (images.fit_uname_os) { - int ret; - - ret = fit_image_get_entry(images.fit_hdr_os, - images.fit_noffset_os, &images.ep); - if (ret) { - puts("Can't get entry point property!\n"); - return 1; - } -#endif - } else if (!ep_found) { - puts("Could not find kernel entry point!\n"); - return 1; - } - - if (images.os.type == IH_TYPE_KERNEL_NOLOAD) { - images.os.load = images.os.image_start; - images.ep += images.os.load; - } - - images.os.start = (ulong)os_hdr; - - return 0; -} - -static int bootm_find_ramdisk(int flag, int argc, char * const argv[]) -{ - int ret; - - /* find ramdisk */ - ret = boot_get_ramdisk(argc, argv, &images, IH_INITRD_ARCH, - &images.rd_start, &images.rd_end); - if (ret) { - puts("Ramdisk image is corrupt or invalid\n"); - return 1; - } - - return 0; -} - -#if defined(CONFIG_OF_LIBFDT) -static int bootm_find_fdt(int flag, int argc, char * const argv[]) -{ - int ret; - - /* find flattened device tree */ - ret = boot_get_fdt(flag, argc, argv, IH_ARCH_DEFAULT, &images, - &images.ft_addr, &images.ft_len); - if (ret) { - puts("Could not find a valid device tree\n"); - return 1; - } - - set_working_fdt_addr(images.ft_addr); - - return 0; -} -#endif - -static int bootm_find_other(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[]) -{ - if (((images.os.type == IH_TYPE_KERNEL) || - (images.os.type == IH_TYPE_KERNEL_NOLOAD) || - (images.os.type == IH_TYPE_MULTI)) && - (images.os.os == IH_OS_LINUX || - images.os.os == IH_OS_VXWORKS)) { - if (bootm_find_ramdisk(flag, argc, argv)) - return 1; - -#if defined(CONFIG_OF_LIBFDT) - if (bootm_find_fdt(flag, argc, argv)) - return 1; -#endif - } - - return 0; -} - -#define BOOTM_ERR_RESET -1 -#define BOOTM_ERR_OVERLAP -2 -#define BOOTM_ERR_UNIMPLEMENTED -3 -static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, - int boot_progress) -{ - image_info_t os = images->os; - uint8_t comp = os.comp; - ulong load = os.load; - ulong blob_start = os.start; - ulong blob_end = os.end; - ulong image_start = os.image_start; - ulong image_len = os.image_len; - __maybe_unused uint unc_len = CONFIG_SYS_BOOTM_LEN; - int no_overlap = 0; - void *load_buf, *image_buf; -#if defined(CONFIG_LZMA) || defined(CONFIG_LZO) - int ret; -#endif /* defined(CONFIG_LZMA) || defined(CONFIG_LZO) */ - - const char *type_name = genimg_get_type_name(os.type); - - load_buf = map_sysmem(load, unc_len); - image_buf = map_sysmem(image_start, image_len); - switch (comp) { - case IH_COMP_NONE: - if (load == image_start) { - printf(" XIP %s ... ", type_name); - no_overlap = 1; - } else { - printf(" Loading %s ... ", type_name); - memmove_wd(load_buf, image_buf, image_len, CHUNKSZ); - } - *load_end = load + image_len; - break; -#ifdef CONFIG_GZIP - case IH_COMP_GZIP: - printf(" Uncompressing %s ... ", type_name); - if (gunzip(load_buf, unc_len, image_buf, &image_len) != 0) { - puts("GUNZIP: uncompress, out-of-mem or overwrite " - "error - must RESET board to recover\n"); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); - return BOOTM_ERR_RESET; - } - - *load_end = load + image_len; - break; -#endif /* CONFIG_GZIP */ -#ifdef CONFIG_BZIP2 - case IH_COMP_BZIP2: - printf(" Uncompressing %s ... ", type_name); - /* - * If we've got less than 4 MB of malloc() space, - * use slower decompression algorithm which requires - * at most 2300 KB of memory. - */ - int i = BZ2_bzBuffToBuffDecompress(load_buf, &unc_len, - image_buf, image_len, - CONFIG_SYS_MALLOC_LEN < (4096 * 1024), 0); - if (i != BZ_OK) { - printf("BUNZIP2: uncompress or overwrite error %d " - "- must RESET board to recover\n", i); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); - return BOOTM_ERR_RESET; - } - - *load_end = load + unc_len; - break; -#endif /* CONFIG_BZIP2 */ -#ifdef CONFIG_LZMA - case IH_COMP_LZMA: { - SizeT lzma_len = unc_len; - printf(" Uncompressing %s ... ", type_name); - - ret = lzmaBuffToBuffDecompress(load_buf, &lzma_len, - image_buf, image_len); - unc_len = lzma_len; - if (ret != SZ_OK) { - printf("LZMA: uncompress or overwrite error %d " - "- must RESET board to recover\n", ret); - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); - return BOOTM_ERR_RESET; - } - *load_end = load + unc_len; - break; - } -#endif /* CONFIG_LZMA */ -#ifdef CONFIG_LZO - case IH_COMP_LZO: { - size_t size = unc_len; - - printf(" Uncompressing %s ... ", type_name); - - ret = lzop_decompress(image_buf, image_len, load_buf, &size); - if (ret != LZO_E_OK) { - printf("LZO: uncompress or overwrite error %d " - "- must RESET board to recover\n", ret); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); - return BOOTM_ERR_RESET; - } - - *load_end = load + size; - break; - } -#endif /* CONFIG_LZO */ - default: - printf("Unimplemented compression type %d\n", comp); - return BOOTM_ERR_UNIMPLEMENTED; - } - - flush_cache(load, (*load_end - load) * sizeof(ulong)); - - puts("OK\n"); - debug(" kernel loaded at 0x%08lx, end = 0x%08lx\n", load, *load_end); - bootstage_mark(BOOTSTAGE_ID_KERNEL_LOADED); - - if (!no_overlap && (load < blob_end) && (*load_end > blob_start)) { - debug("images.os.start = 0x%lX, images.os.end = 0x%lx\n", - blob_start, blob_end); - debug("images.os.load = 0x%lx, load_end = 0x%lx\n", load, - *load_end); - - /* Check what type of image this is. */ - if (images->legacy_hdr_valid) { - if (image_get_type(&images->legacy_hdr_os_copy) - == IH_TYPE_MULTI) - puts("WARNING: legacy format multi component image overwritten\n"); - return BOOTM_ERR_OVERLAP; - } else { - puts("ERROR: new format image overwritten - must RESET the board to recover\n"); - bootstage_error(BOOTSTAGE_ID_OVERWRITTEN); - return BOOTM_ERR_RESET; - } - } - - return 0; -} - -static int do_bootm_standalone(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - char *s; - int (*appl)(int, char * const []); - - /* Don't start if "autostart" is set to "no" */ - if (((s = getenv("autostart")) != NULL) && (strcmp(s, "no") == 0)) { - setenv_hex("filesize", images->os.image_len); - return 0; - } - appl = (int (*)(int, char * const []))images->ep; - appl(argc, argv); - return 0; -} - /* we overload the cmd field with our state machine info instead of a * function pointer */ static cmd_tbl_t cmd_bootm_sub[] = { @@ -548,210 +58,6 @@ static cmd_tbl_t cmd_bootm_sub[] = { U_BOOT_CMD_MKENT(go, 0, 1, (void *)BOOTM_STATE_OS_GO, "", ""), }; -static int boot_selected_os(int argc, char * const argv[], int state, - bootm_headers_t *images, boot_os_fn *boot_fn) -{ - arch_preboot_os(); - boot_fn(state, argc, argv, images); - - /* Stand-alone may return when 'autostart' is 'no' */ - if (images->os.type == IH_TYPE_STANDALONE || - state == BOOTM_STATE_OS_FAKE_GO) /* We expect to return */ - return 0; - bootstage_error(BOOTSTAGE_ID_BOOT_OS_RETURNED); -#ifdef DEBUG - puts("\n## Control returned to monitor - resetting...\n"); -#endif - return BOOTM_ERR_RESET; -} - -/** - * bootm_disable_interrupts() - Disable interrupts in preparation for load/boot - * - * @return interrupt flag (0 if interrupts were disabled, non-zero if they were - * enabled) - */ -static ulong bootm_disable_interrupts(void) -{ - ulong iflag; - - /* - * We have reached the point of no return: we are going to - * overwrite all exception vector code, so we cannot easily - * recover from any failures any more... - */ - iflag = disable_interrupts(); -#ifdef CONFIG_NETCONSOLE - /* Stop the ethernet stack if NetConsole could have left it up */ - eth_halt(); - eth_unregister(eth_get_dev()); -#endif - -#if defined(CONFIG_CMD_USB) - /* - * turn off USB to prevent the host controller from writing to the - * SDRAM while Linux is booting. This could happen (at least for OHCI - * controller), because the HCCA (Host Controller Communication Area) - * lies within the SDRAM and the host controller writes continously to - * this area (as busmaster!). The HccaFrameNumber is for example - * updated every 1 ms within the HCCA structure in SDRAM! For more - * details see the OpenHCI specification. - */ - usb_stop(); -#endif - return iflag; -} - -/** - * Execute selected states of the bootm command. - * - * Note the arguments to this state must be the first argument, Any 'bootm' - * or sub-command arguments must have already been taken. - * - * Note that if states contains more than one flag it MUST contain - * BOOTM_STATE_START, since this handles and consumes the command line args. - * - * Also note that aside from boot_os_fn functions and bootm_load_os no other - * functions we store the return value of in 'ret' may use a negative return - * value, without special handling. - * - * @param cmdtp Pointer to bootm command table entry - * @param flag Command flags (CMD_FLAG_...) - * @param argc Number of subcommand arguments (0 = no arguments) - * @param argv Arguments - * @param states Mask containing states to run (BOOTM_STATE_...) - * @param images Image header information - * @param boot_progress 1 to show boot progress, 0 to not do this - * @return 0 if ok, something else on error. Some errors will cause this - * function to perform a reboot! If states contains BOOTM_STATE_OS_GO - * then the intent is to boot an OS, so this function will not return - * unless the image type is standalone. - */ -static int do_bootm_states(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[], int states, bootm_headers_t *images, - int boot_progress) -{ - boot_os_fn *boot_fn; - ulong iflag = 0; - int ret = 0, need_boot_fn; - - images->state |= states; - - /* - * Work through the states and see how far we get. We stop on - * any error. - */ - if (states & BOOTM_STATE_START) - ret = bootm_start(cmdtp, flag, argc, argv); - - if (!ret && (states & BOOTM_STATE_FINDOS)) - ret = bootm_find_os(cmdtp, flag, argc, argv); - - if (!ret && (states & BOOTM_STATE_FINDOTHER)) { - ret = bootm_find_other(cmdtp, flag, argc, argv); - argc = 0; /* consume the args */ - } - - /* Load the OS */ - if (!ret && (states & BOOTM_STATE_LOADOS)) { - ulong load_end; - - iflag = bootm_disable_interrupts(); - ret = bootm_load_os(images, &load_end, 0); - if (ret == 0) - lmb_reserve(&images->lmb, images->os.load, - (load_end - images->os.load)); - else if (ret && ret != BOOTM_ERR_OVERLAP) - goto err; - else if (ret == BOOTM_ERR_OVERLAP) - ret = 0; -#if defined(CONFIG_SILENT_CONSOLE) && !defined(CONFIG_SILENT_U_BOOT_ONLY) - if (images->os.os == IH_OS_LINUX) - fixup_silent_linux(); -#endif - } - - /* Relocate the ramdisk */ -#ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH - if (!ret && (states & BOOTM_STATE_RAMDISK)) { - ulong rd_len = images->rd_end - images->rd_start; - - ret = boot_ramdisk_high(&images->lmb, images->rd_start, - rd_len, &images->initrd_start, &images->initrd_end); - if (!ret) { - setenv_hex("initrd_start", images->initrd_start); - setenv_hex("initrd_end", images->initrd_end); - } - } -#endif -#if defined(CONFIG_OF_LIBFDT) && defined(CONFIG_LMB) - if (!ret && (states & BOOTM_STATE_FDT)) { - boot_fdt_add_mem_rsv_regions(&images->lmb, images->ft_addr); - ret = boot_relocate_fdt(&images->lmb, &images->ft_addr, - &images->ft_len); - } -#endif - - /* From now on, we need the OS boot function */ - if (ret) - return ret; - boot_fn = boot_os[images->os.os]; - need_boot_fn = states & (BOOTM_STATE_OS_CMDLINE | - BOOTM_STATE_OS_BD_T | BOOTM_STATE_OS_PREP | - BOOTM_STATE_OS_FAKE_GO | BOOTM_STATE_OS_GO); - if (boot_fn == NULL && need_boot_fn) { - if (iflag) - enable_interrupts(); - printf("ERROR: booting os '%s' (%d) is not supported\n", - genimg_get_os_name(images->os.os), images->os.os); - bootstage_error(BOOTSTAGE_ID_CHECK_BOOT_OS); - return 1; - } - - /* Call various other states that are not generally used */ - if (!ret && (states & BOOTM_STATE_OS_CMDLINE)) - ret = boot_fn(BOOTM_STATE_OS_CMDLINE, argc, argv, images); - if (!ret && (states & BOOTM_STATE_OS_BD_T)) - ret = boot_fn(BOOTM_STATE_OS_BD_T, argc, argv, images); - if (!ret && (states & BOOTM_STATE_OS_PREP)) - ret = boot_fn(BOOTM_STATE_OS_PREP, argc, argv, images); - -#ifdef CONFIG_TRACE - /* Pretend to run the OS, then run a user command */ - if (!ret && (states & BOOTM_STATE_OS_FAKE_GO)) { - char *cmd_list = getenv("fakegocmd"); - - ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_FAKE_GO, - images, boot_fn); - if (!ret && cmd_list) - ret = run_command_list(cmd_list, -1, flag); - } -#endif - - /* Check for unsupported subcommand. */ - if (ret) { - puts("subcommand not supported\n"); - return ret; - } - - /* Now run the OS! We hope this doesn't return */ - if (!ret && (states & BOOTM_STATE_OS_GO)) - ret = boot_selected_os(argc, argv, BOOTM_STATE_OS_GO, - images, boot_fn); - - /* Deal with any fallout */ -err: - if (iflag) - enable_interrupts(); - - if (ret == BOOTM_ERR_UNIMPLEMENTED) - bootstage_error(BOOTSTAGE_ID_DECOMP_UNIMPL); - else if (ret == BOOTM_ERR_RESET) - do_reset(cmdtp, flag, argc, argv); - - return ret; -} - static int do_bootm_subcommand(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { @@ -793,11 +99,6 @@ int do_bootm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) if (!relocated) { int i; - /* relocate boot function table */ - for (i = 0; i < ARRAY_SIZE(boot_os); i++) - if (boot_os[i] != NULL) - boot_os[i] += gd->reloc_off; - /* relocate names of sub-command table */ for (i = 0; i < ARRAY_SIZE(cmd_bootm_sub); i++) cmd_bootm_sub[i].name += gd->reloc_off; @@ -849,196 +150,6 @@ int bootm_maybe_autostart(cmd_tbl_t *cmdtp, const char *cmd) return 0; } -#if defined(CONFIG_IMAGE_FORMAT_LEGACY) -/** - * image_get_kernel - verify legacy format kernel image - * @img_addr: in RAM address of the legacy format image to be verified - * @verify: data CRC verification flag - * - * image_get_kernel() verifies legacy image integrity and returns pointer to - * legacy image header if image verification was completed successfully. - * - * returns: - * pointer to a legacy image header if valid image was found - * otherwise return NULL - */ -static image_header_t *image_get_kernel(ulong img_addr, int verify) -{ - image_header_t *hdr = (image_header_t *)img_addr; - - if (!image_check_magic(hdr)) { - puts("Bad Magic Number\n"); - bootstage_error(BOOTSTAGE_ID_CHECK_MAGIC); - return NULL; - } - bootstage_mark(BOOTSTAGE_ID_CHECK_HEADER); - - if (!image_check_hcrc(hdr)) { - puts("Bad Header Checksum\n"); - bootstage_error(BOOTSTAGE_ID_CHECK_HEADER); - return NULL; - } - - bootstage_mark(BOOTSTAGE_ID_CHECK_CHECKSUM); - image_print_contents(hdr); - - if (verify) { - puts(" Verifying Checksum ... "); - if (!image_check_dcrc(hdr)) { - printf("Bad Data CRC\n"); - bootstage_error(BOOTSTAGE_ID_CHECK_CHECKSUM); - return NULL; - } - puts("OK\n"); - } - bootstage_mark(BOOTSTAGE_ID_CHECK_ARCH); - - if (!image_check_target_arch(hdr)) { - printf("Unsupported Architecture 0x%x\n", image_get_arch(hdr)); - bootstage_error(BOOTSTAGE_ID_CHECK_ARCH); - return NULL; - } - return hdr; -} -#endif - -/** - * boot_get_kernel - find kernel image - * @os_data: pointer to a ulong variable, will hold os data start address - * @os_len: pointer to a ulong variable, will hold os data length - * - * boot_get_kernel() tries to find a kernel image, verifies its integrity - * and locates kernel data. - * - * returns: - * pointer to image header if valid image was found, plus kernel start - * address and length, otherwise NULL - */ -static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, - char * const argv[], bootm_headers_t *images, ulong *os_data, - ulong *os_len) -{ -#if defined(CONFIG_IMAGE_FORMAT_LEGACY) - image_header_t *hdr; -#endif - ulong img_addr; - const void *buf; -#if defined(CONFIG_FIT) - const char *fit_uname_config = NULL; - const char *fit_uname_kernel = NULL; - int os_noffset; -#endif - - /* find out kernel image address */ - if (argc < 1) { - img_addr = load_addr; - debug("* kernel: default image load address = 0x%08lx\n", - load_addr); -#if defined(CONFIG_FIT) - } else if (fit_parse_conf(argv[0], load_addr, &img_addr, - &fit_uname_config)) { - debug("* kernel: config '%s' from image at 0x%08lx\n", - fit_uname_config, img_addr); - } else if (fit_parse_subimage(argv[0], load_addr, &img_addr, - &fit_uname_kernel)) { - debug("* kernel: subimage '%s' from image at 0x%08lx\n", - fit_uname_kernel, img_addr); -#endif - } else { - img_addr = simple_strtoul(argv[0], NULL, 16); - debug("* kernel: cmdline image address = 0x%08lx\n", img_addr); - } - - bootstage_mark(BOOTSTAGE_ID_CHECK_MAGIC); - - /* copy from dataflash if needed */ - img_addr = genimg_get_image(img_addr); - - /* check image type, for FIT images get FIT kernel node */ - *os_data = *os_len = 0; - buf = map_sysmem(img_addr, 0); - switch (genimg_get_format(buf)) { -#if defined(CONFIG_IMAGE_FORMAT_LEGACY) - case IMAGE_FORMAT_LEGACY: - printf("## Booting kernel from Legacy Image at %08lx ...\n", - img_addr); - hdr = image_get_kernel(img_addr, images->verify); - if (!hdr) - return NULL; - bootstage_mark(BOOTSTAGE_ID_CHECK_IMAGETYPE); - - /* get os_data and os_len */ - switch (image_get_type(hdr)) { - case IH_TYPE_KERNEL: - case IH_TYPE_KERNEL_NOLOAD: - *os_data = image_get_data(hdr); - *os_len = image_get_data_size(hdr); - break; - case IH_TYPE_MULTI: - image_multi_getimg(hdr, 0, os_data, os_len); - break; - case IH_TYPE_STANDALONE: - *os_data = image_get_data(hdr); - *os_len = image_get_data_size(hdr); - break; - default: - printf("Wrong Image Type for %s command\n", - cmdtp->name); - bootstage_error(BOOTSTAGE_ID_CHECK_IMAGETYPE); - return NULL; - } - - /* - * copy image header to allow for image overwrites during - * kernel decompression. - */ - memmove(&images->legacy_hdr_os_copy, hdr, - sizeof(image_header_t)); - - /* save pointer to image header */ - images->legacy_hdr_os = hdr; - - images->legacy_hdr_valid = 1; - bootstage_mark(BOOTSTAGE_ID_DECOMP_IMAGE); - break; -#endif -#if defined(CONFIG_FIT) - case IMAGE_FORMAT_FIT: - os_noffset = fit_image_load(images, FIT_KERNEL_PROP, - img_addr, - &fit_uname_kernel, &fit_uname_config, - IH_ARCH_DEFAULT, IH_TYPE_KERNEL, - BOOTSTAGE_ID_FIT_KERNEL_START, - FIT_LOAD_IGNORED, os_data, os_len); - if (os_noffset < 0) - return NULL; - - images->fit_hdr_os = map_sysmem(img_addr, 0); - images->fit_uname_os = fit_uname_kernel; - images->fit_uname_cfg = fit_uname_config; - images->fit_noffset_os = os_noffset; - break; -#endif -#ifdef CONFIG_ANDROID_BOOT_IMAGE - case IMAGE_FORMAT_ANDROID: - printf("## Booting Android Image at 0x%08lx ...\n", img_addr); - if (android_image_get_kernel((void *)img_addr, images->verify, - os_data, os_len)) - return NULL; - break; -#endif - default: - printf("Wrong Image Format for %s command\n", cmdtp->name); - bootstage_error(BOOTSTAGE_ID_FIT_KERNEL_INFO); - return NULL; - } - - debug(" kernel data at 0x%08lx, len = 0x%08lx (%ld)\n", - *os_data, *os_len, *os_len); - - return buf; -} - #ifdef CONFIG_SYS_LONGHELP static char bootm_help_text[] = "[addr [arg ...]]\n - boot application image stored in memory\n" @@ -1420,441 +531,6 @@ U_BOOT_CMD( ); #endif -/*******************************************************************/ -/* helper routines */ -/*******************************************************************/ -#if defined(CONFIG_SILENT_CONSOLE) && !defined(CONFIG_SILENT_U_BOOT_ONLY) - -#define CONSOLE_ARG "console=" -#define CONSOLE_ARG_LEN (sizeof(CONSOLE_ARG) - 1) - -static void fixup_silent_linux(void) -{ - char *buf; - const char *env_val; - char *cmdline = getenv("bootargs"); - int want_silent; - - /* - * Only fix cmdline when requested. The environment variable can be: - * - * no - we never fixup - * yes - we always fixup - * unset - we rely on the console silent flag - */ - want_silent = getenv_yesno("silent_linux"); - if (want_silent == 0) - return; - else if (want_silent == -1 && !(gd->flags & GD_FLG_SILENT)) - return; - - debug("before silent fix-up: %s\n", cmdline); - if (cmdline && (cmdline[0] != '\0')) { - char *start = strstr(cmdline, CONSOLE_ARG); - - /* Allocate space for maximum possible new command line */ - buf = malloc(strlen(cmdline) + 1 + CONSOLE_ARG_LEN + 1); - if (!buf) { - debug("%s: out of memory\n", __func__); - return; - } - - if (start) { - char *end = strchr(start, ' '); - int num_start_bytes = start - cmdline + CONSOLE_ARG_LEN; - - strncpy(buf, cmdline, num_start_bytes); - if (end) - strcpy(buf + num_start_bytes, end); - else - buf[num_start_bytes] = '\0'; - } else { - sprintf(buf, "%s %s", cmdline, CONSOLE_ARG); - } - env_val = buf; - } else { - buf = NULL; - env_val = CONSOLE_ARG; - } - - setenv("bootargs", env_val); - debug("after silent fix-up: %s\n", env_val); - free(buf); -} -#endif /* CONFIG_SILENT_CONSOLE */ - -#if defined(CONFIG_BOOTM_NETBSD) || defined(CONFIG_BOOTM_PLAN9) -static void copy_args(char *dest, int argc, char * const argv[], char delim) -{ - int i; - - for (i = 0; i < argc; i++) { - if (i > 0) - *dest++ = delim; - strcpy(dest, argv[i]); - dest += strlen(argv[i]); - } -} -#endif - -/*******************************************************************/ -/* OS booting routines */ -/*******************************************************************/ - -#ifdef CONFIG_BOOTM_NETBSD -static int do_bootm_netbsd(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - void (*loader)(bd_t *, image_header_t *, char *, char *); - image_header_t *os_hdr, *hdr; - ulong kernel_data, kernel_len; - char *consdev; - char *cmdline; - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("NetBSD"); - return 1; - } -#endif - hdr = images->legacy_hdr_os; - - /* - * Booting a (NetBSD) kernel image - * - * This process is pretty similar to a standalone application: - * The (first part of an multi-) image must be a stage-2 loader, - * which in turn is responsible for loading & invoking the actual - * kernel. The only differences are the parameters being passed: - * besides the board info strucure, the loader expects a command - * line, the name of the console device, and (optionally) the - * address of the original image header. - */ - os_hdr = NULL; - if (image_check_type(&images->legacy_hdr_os_copy, IH_TYPE_MULTI)) { - image_multi_getimg(hdr, 1, &kernel_data, &kernel_len); - if (kernel_len) - os_hdr = hdr; - } - - consdev = ""; -#if defined(CONFIG_8xx_CONS_SMC1) - consdev = "smc1"; -#elif defined(CONFIG_8xx_CONS_SMC2) - consdev = "smc2"; -#elif defined(CONFIG_8xx_CONS_SCC2) - consdev = "scc2"; -#elif defined(CONFIG_8xx_CONS_SCC3) - consdev = "scc3"; -#endif - - if (argc > 0) { - ulong len; - int i; - - for (i = 0, len = 0; i < argc; i += 1) - len += strlen(argv[i]) + 1; - cmdline = malloc(len); - copy_args(cmdline, argc, argv, ' '); - } else if ((cmdline = getenv("bootargs")) == NULL) { - cmdline = ""; - } - - loader = (void (*)(bd_t *, image_header_t *, char *, char *))images->ep; - - printf("## Transferring control to NetBSD stage-2 loader " - "(at address %08lx) ...\n", - (ulong)loader); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - - /* - * NetBSD Stage-2 Loader Parameters: - * arg[0]: pointer to board info data - * arg[1]: image load address - * arg[2]: char pointer to the console device to use - * arg[3]: char pointer to the boot arguments - */ - (*loader)(gd->bd, os_hdr, consdev, cmdline); - - return 1; -} -#endif /* CONFIG_BOOTM_NETBSD*/ - -#ifdef CONFIG_LYNXKDI -static int do_bootm_lynxkdi(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - image_header_t *hdr = &images->legacy_hdr_os_copy; - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("Lynx"); - return 1; - } -#endif - - lynxkdi_boot((image_header_t *)hdr); - - return 1; -} -#endif /* CONFIG_LYNXKDI */ - -#ifdef CONFIG_BOOTM_RTEMS -static int do_bootm_rtems(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - void (*entry_point)(bd_t *); - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("RTEMS"); - return 1; - } -#endif - - entry_point = (void (*)(bd_t *))images->ep; - - printf("## Transferring control to RTEMS (at address %08lx) ...\n", - (ulong)entry_point); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - - /* - * RTEMS Parameters: - * r3: ptr to board info data - */ - (*entry_point)(gd->bd); - - return 1; -} -#endif /* CONFIG_BOOTM_RTEMS */ - -#if defined(CONFIG_BOOTM_OSE) -static int do_bootm_ose(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - void (*entry_point)(void); - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("OSE"); - return 1; - } -#endif - - entry_point = (void (*)(void))images->ep; - - printf("## Transferring control to OSE (at address %08lx) ...\n", - (ulong)entry_point); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - - /* - * OSE Parameters: - * None - */ - (*entry_point)(); - - return 1; -} -#endif /* CONFIG_BOOTM_OSE */ - -#if defined(CONFIG_BOOTM_PLAN9) -static int do_bootm_plan9(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - void (*entry_point)(void); - char *s; - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("Plan 9"); - return 1; - } -#endif - - /* See README.plan9 */ - s = getenv("confaddr"); - if (s != NULL) { - char *confaddr = (char *)simple_strtoul(s, NULL, 16); - - if (argc > 0) { - copy_args(confaddr, argc, argv, '\n'); - } else { - s = getenv("bootargs"); - if (s != NULL) - strcpy(confaddr, s); - } - } - - entry_point = (void (*)(void))images->ep; - - printf("## Transferring control to Plan 9 (at address %08lx) ...\n", - (ulong)entry_point); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - - /* - * Plan 9 Parameters: - * None - */ - (*entry_point)(); - - return 1; -} -#endif /* CONFIG_BOOTM_PLAN9 */ - -#if defined(CONFIG_BOOTM_VXWORKS) && \ - (defined(CONFIG_PPC) || defined(CONFIG_ARM)) - -void do_bootvx_fdt(bootm_headers_t *images) -{ -#if defined(CONFIG_OF_LIBFDT) - int ret; - char *bootline; - ulong of_size = images->ft_len; - char **of_flat_tree = &images->ft_addr; - struct lmb *lmb = &images->lmb; - - if (*of_flat_tree) { - boot_fdt_add_mem_rsv_regions(lmb, *of_flat_tree); - - ret = boot_relocate_fdt(lmb, of_flat_tree, &of_size); - if (ret) - return; - - ret = fdt_add_subnode(*of_flat_tree, 0, "chosen"); - if ((ret >= 0 || ret == -FDT_ERR_EXISTS)) { - bootline = getenv("bootargs"); - if (bootline) { - ret = fdt_find_and_setprop(*of_flat_tree, - "/chosen", "bootargs", - bootline, - strlen(bootline) + 1, 1); - if (ret < 0) { - printf("## ERROR: %s : %s\n", __func__, - fdt_strerror(ret)); - return; - } - } - } else { - printf("## ERROR: %s : %s\n", __func__, - fdt_strerror(ret)); - return; - } - } -#endif - - boot_prep_vxworks(images); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - -#if defined(CONFIG_OF_LIBFDT) - printf("## Starting vxWorks at 0x%08lx, device tree at 0x%08lx ...\n", - (ulong)images->ep, (ulong)*of_flat_tree); -#else - printf("## Starting vxWorks at 0x%08lx\n", (ulong)images->ep); -#endif - - boot_jump_vxworks(images); - - puts("## vxWorks terminated\n"); -} - -static int do_bootm_vxworks(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("VxWorks"); - return 1; - } -#endif - - do_bootvx_fdt(images); - - return 1; -} -#endif - -#if defined(CONFIG_CMD_ELF) -static int do_bootm_qnxelf(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - char *local_args[2]; - char str[16]; - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("QNX"); - return 1; - } -#endif - - sprintf(str, "%lx", images->ep); /* write entry-point into string */ - local_args[0] = argv[0]; - local_args[1] = str; /* and provide it via the arguments */ - do_bootelf(NULL, 0, 2, local_args); - - return 1; -} -#endif - -#ifdef CONFIG_INTEGRITY -static int do_bootm_integrity(int flag, int argc, char * const argv[], - bootm_headers_t *images) -{ - void (*entry_point)(void); - - if (flag != BOOTM_STATE_OS_GO) - return 0; - -#if defined(CONFIG_FIT) - if (!images->legacy_hdr_valid) { - fit_unsupported_reset("INTEGRITY"); - return 1; - } -#endif - - entry_point = (void (*)(void))images->ep; - - printf("## Transferring control to INTEGRITY (at address %08lx) ...\n", - (ulong)entry_point); - - bootstage_mark(BOOTSTAGE_ID_RUN_OS); - - /* - * INTEGRITY Parameters: - * None - */ - (*entry_point)(); - - return 1; -} -#endif - #ifdef CONFIG_CMD_BOOTZ int __weak bootz_setup(ulong image, ulong *start, ulong *end) @@ -1898,14 +574,9 @@ static int bootz_start(cmd_tbl_t *cmdtp, int flag, int argc, * Handle the BOOTM_STATE_FINDOTHER state ourselves as we do not * have a header that provide this informaiton. */ - if (bootm_find_ramdisk(flag, argc, argv)) + if (bootm_find_ramdisk_fdt(flag, argc, argv)) return 1; -#if defined(CONFIG_OF_LIBFDT) - if (bootm_find_fdt(flag, argc, argv)) - return 1; -#endif - return 0; } -- cgit v1.1 From 126cc864206e0a06635a4bf49b75de8d5a4a80d7 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:47 -0600 Subject: image: Remove the fit_load_image() property parameter This can be obtained by looking up the image type, so is redundant. It is better to centralise this lookup to avoid errors. Signed-off-by: Simon Glass --- common/bootm.c | 3 +-- common/image-fdt.c | 1 - common/image-fit.c | 29 ++++++++++++++++++++++++++++- common/image.c | 2 +- 4 files changed, 30 insertions(+), 5 deletions(-) (limited to 'common') diff --git a/common/bootm.c b/common/bootm.c index 27a7f02..338f647 100644 --- a/common/bootm.c +++ b/common/bootm.c @@ -776,8 +776,7 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, #endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: - os_noffset = fit_image_load(images, FIT_KERNEL_PROP, - img_addr, + os_noffset = fit_image_load(images, img_addr, &fit_uname_kernel, &fit_uname_config, IH_ARCH_DEFAULT, IH_TYPE_KERNEL, BOOTSTAGE_ID_FIT_KERNEL_START, diff --git a/common/image-fdt.c b/common/image-fdt.c index 27a8a44..9fc7481 100644 --- a/common/image-fdt.c +++ b/common/image-fdt.c @@ -355,7 +355,6 @@ int boot_get_fdt(int flag, int argc, char * const argv[], uint8_t arch, ulong load, len; fdt_noffset = fit_image_load(images, - FIT_FDT_PROP, fdt_addr, &fit_uname_fdt, &fit_uname_config, arch, IH_TYPE_FLATDT, diff --git a/common/image-fit.c b/common/image-fit.c index 40c7e27..c0d7b8c 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -1477,7 +1477,32 @@ int fit_get_node_from_config(bootm_headers_t *images, const char *prop_name, return noffset; } -int fit_image_load(bootm_headers_t *images, const char *prop_name, ulong addr, +/** + * fit_get_image_type_property() - get property name for IH_TYPE_... + * + * @return the properly name where we expect to find the image in the + * config node + */ +static const char *fit_get_image_type_property(int type) +{ + /* + * This is sort-of available in the uimage_type[] table in image.c + * but we don't have access to the sohrt name, and "fdt" is different + * anyway. So let's just keep it here. + */ + switch (type) { + case IH_TYPE_FLATDT: + return FIT_FDT_PROP; + case IH_TYPE_KERNEL: + return FIT_KERNEL_PROP; + case IH_TYPE_RAMDISK: + return FIT_RAMDISK_PROP; + } + + return "unknown"; +} + +int fit_image_load(bootm_headers_t *images, ulong addr, const char **fit_unamep, const char **fit_uname_configp, int arch, int image_type, int bootstage_id, enum fit_load_op load_op, ulong *datap, ulong *lenp) @@ -1490,11 +1515,13 @@ int fit_image_load(bootm_headers_t *images, const char *prop_name, ulong addr, size_t size; int type_ok, os_ok; ulong load, data, len; + const char *prop_name; int ret; fit = map_sysmem(addr, 0); fit_uname = fit_unamep ? *fit_unamep : NULL; fit_uname_config = fit_uname_configp ? *fit_uname_configp : NULL; + prop_name = fit_get_image_type_property(image_type); printf("## Loading %s from FIT Image at %08lx ...\n", prop_name, addr); bootstage_mark(bootstage_id + BOOTSTAGE_SUB_FORMAT); diff --git a/common/image.c b/common/image.c index f33b175..828b0af 100644 --- a/common/image.c +++ b/common/image.c @@ -903,7 +903,7 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t *images, #endif #if defined(CONFIG_FIT) case IMAGE_FORMAT_FIT: - rd_noffset = fit_image_load(images, FIT_RAMDISK_PROP, + rd_noffset = fit_image_load(images, rd_addr, &fit_uname_ramdisk, &fit_uname_config, arch, IH_TYPE_RAMDISK, -- cgit v1.1 From 07c0cd71340e21c690b4921ced6790ea49adc4b4 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:48 -0600 Subject: bootm: Support android boot on sandbox A small change allows this to operate on sandbox. Signed-off-by: Simon Glass --- common/bootm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/bootm.c b/common/bootm.c index 338f647..1e66929 100644 --- a/common/bootm.c +++ b/common/bootm.c @@ -793,7 +793,7 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, #ifdef CONFIG_ANDROID_BOOT_IMAGE case IMAGE_FORMAT_ANDROID: printf("## Booting Android Image at 0x%08lx ...\n", img_addr); - if (android_image_get_kernel((void *)img_addr, images->verify, + if (android_image_get_kernel(buf, images->verify, os_data, os_len)) return NULL; break; -- cgit v1.1 From e3c83c0a1fce2be671d5d3297d90e9d0890f7b52 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:49 -0600 Subject: Fix small 'case' typo in image-fit.c This typo makes the comment confusing. Fix it. Signed-off-by: Simon Glass --- common/image-fit.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'common') diff --git a/common/image-fit.c b/common/image-fit.c index c0d7b8c..83fac9a 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -1637,7 +1637,7 @@ int fit_image_load(bootm_headers_t *images, ulong addr, /* * Work-around for eldk-4.2 which gives this warning if we try to - * case in the unmap_sysmem() call: + * cast in the unmap_sysmem() call: * warning: initialization discards qualifiers from pointer target type */ { -- cgit v1.1 From ea51a6282316f383fa04defa30ea15feb36d5d69 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:51 -0600 Subject: Allow compiling common/bootm.c on with HOSTCC We want to use some of the functionality in this file, so make it build on the host. Signed-off-by: Simon Glass --- common/bootm.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/bootm.c b/common/bootm.c index 1e66929..d83dded 100644 --- a/common/bootm.c +++ b/common/bootm.c @@ -5,10 +5,10 @@ * SPDX-License-Identifier: GPL-2.0+ */ +#ifndef USE_HOSTCC #include -#include +#include #include -#include #include #include #include @@ -17,12 +17,16 @@ #include #include #include - #if defined(CONFIG_CMD_USB) #include #endif +#else +#include "mkimage.h" +#endif -DECLARE_GLOBAL_DATA_PTR; +#include +#include +#include #ifndef CONFIG_SYS_BOOTM_LEN /* use 8MByte as default max gunzip size */ @@ -31,6 +35,10 @@ DECLARE_GLOBAL_DATA_PTR; #define IH_INITRD_ARCH IH_ARCH_DEFAULT +#ifndef USE_HOSTCC + +DECLARE_GLOBAL_DATA_PTR; + static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[], bootm_headers_t *images, ulong *os_data, ulong *os_len); @@ -809,3 +817,5 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, return buf; } + +#endif /* ndef USE_HOSTCC */ -- cgit v1.1 From 2b164f1cea69c7c583a26502d2a68d1c62eb0b5a Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:52 -0600 Subject: bootm: Move decompression code into its own function This makes it possible to decompress an image without it being a kernel and without intending to boot it (as it needed for host tools, for example). Signed-off-by: Simon Glass --- common/bootm.c | 75 +++++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 27 deletions(-) (limited to 'common') diff --git a/common/bootm.c b/common/bootm.c index d83dded..d93d3f3 100644 --- a/common/bootm.c +++ b/common/bootm.c @@ -245,32 +245,29 @@ static int bootm_find_other(cmd_tbl_t *cmdtp, int flag, int argc, return 0; } -static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, - int boot_progress) +/** + * decomp_image() - decompress the operating system + * + * @comp: Compression algorithm that is used (IH_COMP_...) + * @load: Destination load address in U-Boot memory + * @image_start Image start address (where we are decompressing from) + * @type: OS type (IH_OS_...) + * @load_bug: Place to decompress to + * @image_buf: Address to decompress from + * @return 0 if OK, -ve on error (BOOTM_ERR_...) + */ +static int decomp_image(int comp, ulong load, ulong image_start, int type, + void *load_buf, void *image_buf, ulong image_len, + ulong *load_end) { - image_info_t os = images->os; - uint8_t comp = os.comp; - ulong load = os.load; - ulong blob_start = os.start; - ulong blob_end = os.end; - ulong image_start = os.image_start; - ulong image_len = os.image_len; - __maybe_unused uint unc_len = CONFIG_SYS_BOOTM_LEN; - int no_overlap = 0; - void *load_buf, *image_buf; -#if defined(CONFIG_LZMA) || defined(CONFIG_LZO) - int ret; -#endif /* defined(CONFIG_LZMA) || defined(CONFIG_LZO) */ - - const char *type_name = genimg_get_type_name(os.type); + const char *type_name = genimg_get_type_name(type); + __attribute__((unused)) uint unc_len = CONFIG_SYS_BOOTM_LEN; - load_buf = map_sysmem(load, unc_len); - image_buf = map_sysmem(image_start, image_len); + *load_end = load; switch (comp) { case IH_COMP_NONE: if (load == image_start) { printf(" XIP %s ... ", type_name); - no_overlap = 1; } else { printf(" Loading %s ... ", type_name); memmove_wd(load_buf, image_buf, image_len, CHUNKSZ); @@ -282,8 +279,6 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, printf(" Uncompressing %s ... ", type_name); if (gunzip(load_buf, unc_len, image_buf, &image_len) != 0) { puts("GUNZIP: uncompress, out-of-mem or overwrite error - must RESET board to recover\n"); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); return BOOTM_ERR_RESET; } @@ -304,8 +299,6 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, if (i != BZ_OK) { printf("BUNZIP2: uncompress or overwrite error %d - must RESET board to recover\n", i); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); return BOOTM_ERR_RESET; } @@ -315,6 +308,8 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, #ifdef CONFIG_LZMA case IH_COMP_LZMA: { SizeT lzma_len = unc_len; + int ret; + printf(" Uncompressing %s ... ", type_name); ret = lzmaBuffToBuffDecompress(load_buf, &lzma_len, @@ -333,6 +328,7 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, #ifdef CONFIG_LZO case IH_COMP_LZO: { size_t size = unc_len; + int ret; printf(" Uncompressing %s ... ", type_name); @@ -340,8 +336,6 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, if (ret != LZO_E_OK) { printf("LZO: uncompress or overwrite error %d - must RESET board to recover\n", ret); - if (boot_progress) - bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); return BOOTM_ERR_RESET; } @@ -354,12 +348,39 @@ static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, return BOOTM_ERR_UNIMPLEMENTED; } + puts("OK\n"); + + return 0; +} + +static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, + int boot_progress) +{ + image_info_t os = images->os; + ulong load = os.load; + ulong blob_start = os.start; + ulong blob_end = os.end; + ulong image_start = os.image_start; + ulong image_len = os.image_len; + bool no_overlap; + void *load_buf, *image_buf; + int err; + + load_buf = map_sysmem(load, 0); + image_buf = map_sysmem(os.image_start, image_len); + err = decomp_image(os.comp, load, os.image_start, os.type, load_buf, + image_buf, image_len, load_end); + if (err) { + bootstage_error(BOOTSTAGE_ID_DECOMP_IMAGE); + return err; + } flush_cache(load, (*load_end - load) * sizeof(ulong)); - puts("OK\n"); debug(" kernel loaded at 0x%08lx, end = 0x%08lx\n", load, *load_end); bootstage_mark(BOOTSTAGE_ID_KERNEL_LOADED); + no_overlap = (os.comp == IH_COMP_NONE && load == image_start); + if (!no_overlap && (load < blob_end) && (*load_end > blob_start)) { debug("images.os.start = 0x%lX, images.os.end = 0x%lx\n", blob_start, blob_end); -- cgit v1.1 From ce1400f6949bbfec01fe381a844b14844cb3be12 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Thu, 12 Jun 2014 07:24:53 -0600 Subject: Enhance fit_check_sign to check all images At present this tool only checks the configuration signing. Have it also look at each of the images in the configuration and confirm that they verify. Signed-off-by: Simon Glass Acked-by: Heiko Schocher (v1) --- common/bootm.c | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ common/image-fit.c | 3 ++- 2 files changed, 73 insertions(+), 1 deletion(-) (limited to 'common') diff --git a/common/bootm.c b/common/bootm.c index d93d3f3..7ec2ed8 100644 --- a/common/bootm.c +++ b/common/bootm.c @@ -244,6 +244,7 @@ static int bootm_find_other(cmd_tbl_t *cmdtp, int flag, int argc, return 0; } +#endif /* USE_HOSTCC */ /** * decomp_image() - decompress the operating system @@ -353,6 +354,7 @@ static int decomp_image(int comp, ulong load, ulong image_start, int type, return 0; } +#ifndef USE_HOSTCC static int bootm_load_os(bootm_headers_t *images, unsigned long *load_end, int boot_progress) { @@ -838,5 +840,74 @@ static const void *boot_get_kernel(cmd_tbl_t *cmdtp, int flag, int argc, return buf; } +#else /* USE_HOSTCC */ + +void memmove_wd(void *to, void *from, size_t len, ulong chunksz) +{ + memmove(to, from, len); +} + +static int bootm_host_load_image(const void *fit, int req_image_type) +{ + const char *fit_uname_config = NULL; + ulong data, len; + bootm_headers_t images; + int noffset; + ulong load_end; + uint8_t image_type; + uint8_t imape_comp; + void *load_buf; + int ret; + + memset(&images, '\0', sizeof(images)); + images.verify = 1; + noffset = fit_image_load(&images, (ulong)fit, + NULL, &fit_uname_config, + IH_ARCH_DEFAULT, req_image_type, -1, + FIT_LOAD_IGNORED, &data, &len); + if (noffset < 0) + return noffset; + if (fit_image_get_type(fit, noffset, &image_type)) { + puts("Can't get image type!\n"); + return -EINVAL; + } + + if (fit_image_get_comp(fit, noffset, &imape_comp)) { + puts("Can't get image compression!\n"); + return -EINVAL; + } + + /* Allow the image to expand by a factor of 4, should be safe */ + load_buf = malloc((1 << 20) + len * 4); + ret = decomp_image(imape_comp, 0, data, image_type, load_buf, + (void *)data, len, &load_end); + free(load_buf); + if (ret && ret != BOOTM_ERR_UNIMPLEMENTED) + return ret; + + return 0; +} + +int bootm_host_load_images(const void *fit, int cfg_noffset) +{ + static uint8_t image_types[] = { + IH_TYPE_KERNEL, + IH_TYPE_FLATDT, + IH_TYPE_RAMDISK, + }; + int err = 0; + int i; + + for (i = 0; i < ARRAY_SIZE(image_types); i++) { + int ret; + + ret = bootm_host_load_image(fit, image_types[i]); + if (!err && ret && ret != -ENOENT) + err = ret; + } + + /* Return the first error we found */ + return err; +} #endif /* ndef USE_HOSTCC */ diff --git a/common/image-fit.c b/common/image-fit.c index 83fac9a..3311343 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -1591,12 +1591,13 @@ int fit_image_load(bootm_headers_t *images, ulong addr, } bootstage_mark(bootstage_id + BOOTSTAGE_SUB_CHECK_ARCH); +#ifndef USE_HOSTCC if (!fit_image_check_target_arch(fit, noffset)) { puts("Unsupported Architecture\n"); bootstage_error(bootstage_id + BOOTSTAGE_SUB_CHECK_ARCH); return -ENOEXEC; } - +#endif if (image_type == IH_TYPE_FLATDT && !fit_image_check_comp(fit, noffset, IH_COMP_NONE)) { puts("FDT image is compressed"); -- cgit v1.1 From 2b9912e6a7df7b1f60beb7942bd0e6fa5f9d0167 Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Thu, 12 Jun 2014 22:27:12 +0200 Subject: includes: move openssl headers to include/u-boot commit 18b06652cd "tools: include u-boot version of sha256.h" unconditionally forced the sha256.h from u-boot to be used for tools instead of the host version. This is fragile though as it will also include the host version. Therefore move it to include/u-boot to join u-boot/md5.h etc which were renamed for the same reason. cc: Simon Glass Signed-off-by: Jeroen Hofstee --- common/cmd_sha1sum.c | 2 +- common/hash.c | 4 ++-- common/image-fit.c | 4 ++-- common/image-sig.c | 4 ++-- common/image.c | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) (limited to 'common') diff --git a/common/cmd_sha1sum.c b/common/cmd_sha1sum.c index 644b9a0..783ea2e 100644 --- a/common/cmd_sha1sum.c +++ b/common/cmd_sha1sum.c @@ -11,7 +11,7 @@ #include #include #include -#include +#include int do_sha1sum(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { diff --git a/common/hash.c b/common/hash.c index 3d95378..12d6759 100644 --- a/common/hash.c +++ b/common/hash.c @@ -15,8 +15,8 @@ #include #include #include -#include -#include +#include +#include #include #include diff --git a/common/image-fit.c b/common/image-fit.c index 3311343..c61be65 100644 --- a/common/image-fit.c +++ b/common/image-fit.c @@ -21,10 +21,10 @@ DECLARE_GLOBAL_DATA_PTR; #endif /* !USE_HOSTCC*/ #include -#include -#include #include #include +#include +#include /*****************************************************************************/ /* New uImage format routines */ diff --git a/common/image-sig.c b/common/image-sig.c index 48788f9..8601eda 100644 --- a/common/image-sig.c +++ b/common/image-sig.c @@ -13,8 +13,8 @@ DECLARE_GLOBAL_DATA_PTR; #endif /* !USE_HOSTCC*/ #include -#include -#include +#include +#include #define IMAGE_MAX_HASHED_NODES 100 diff --git a/common/image.c b/common/image.c index 828b0af..11b3cf5 100644 --- a/common/image.c +++ b/common/image.c @@ -34,7 +34,7 @@ #endif #include -#include +#include #include #include -- cgit v1.1 From 9fb70f31fea14c7c1b5575cc71d562587d837ca8 Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Mon, 16 Jun 2014 00:10:42 +0200 Subject: cmd_md5sum.c: remove dead code / fix warning commit ecd729500 "Add parameter to md5sum to save the md5 sum" adds support to build a string to be saved in the env and tries to zero end it with str_ptr = '\0'; This does actually set the pointer to the end of the buffer itself to zero. Since the string was already zero terminated by the sprintf before it, just remove the line, preventing a clang warning. cc: Joe Hershberger Signed-off-by: Jeroen Hofstee --- common/cmd_md5sum.c | 1 - 1 file changed, 1 deletion(-) (limited to 'common') diff --git a/common/cmd_md5sum.c b/common/cmd_md5sum.c index ae0f62e..3ac8cc4 100644 --- a/common/cmd_md5sum.c +++ b/common/cmd_md5sum.c @@ -33,7 +33,6 @@ static void store_result(const u8 *sum, const char *dest) sprintf(str_ptr, "%02x", sum[i]); str_ptr += 2; } - str_ptr = '\0'; setenv(dest, str_output); } } -- cgit v1.1 From 9e546ee9c90fc0a888423fa3269020fe736df7a3 Mon Sep 17 00:00:00 2001 From: Jeroen Hofstee Date: Mon, 16 Jun 2014 00:17:33 +0200 Subject: cosmetic: autoboot: update old style GNU struct init Signed-off-by: Jeroen Hofstee --- common/autoboot.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/autoboot.c b/common/autoboot.c index dc24cae..30102a4 100644 --- a/common/autoboot.c +++ b/common/autoboot.c @@ -40,10 +40,10 @@ static int abortboot_keyed(int bootdelay) int retry; } delaykey[] = { - { str: getenv("bootdelaykey"), retry: 1 }, - { str: getenv("bootdelaykey2"), retry: 1 }, - { str: getenv("bootstopkey"), retry: 0 }, - { str: getenv("bootstopkey2"), retry: 0 }, + { .str = getenv("bootdelaykey"), .retry = 1 }, + { .str = getenv("bootdelaykey2"), .retry = 1 }, + { .str = getenv("bootstopkey"), .retry = 0 }, + { .str = getenv("bootstopkey2"), .retry = 0 }, }; char presskey[MAX_DELAY_STOP_STR]; -- cgit v1.1 From aa53233a15e22ae207436e4015a69d24f06c2703 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Wed, 11 Jun 2014 23:29:41 -0600 Subject: Add an I/O tracing feature When debugging drivers it is useful to see what I/O accesses were done and in what order. Even if the individual accesses are of little interest it can be useful to verify that the access pattern is consistent each time an operation is performed. In this case a checksum can be used to characterise the operation of a driver. The checksum can be compared across different runs of the operation to verify that the driver is working properly. In particular, when performing major refactoring of the driver, where the access pattern should not change, the checksum provides assurance that the refactoring work has not broken the driver. Add an I/O tracing feature and associated commands to provide this facility. It works by sneaking into the io.h heder for an architecture and redirecting I/O accesses through its tracing mechanism. For now no commands are provided to examine the trace buffer. The format is fairly simple, so 'md' is a reasonable substitute. Note: The checksum feature is only useful for I/O regions where the contents do not change outside of software control. Where this is not suitable you can fall back to manually comparing the addresses. It might be useful to enhance tracing to only checksum the accesses and not the data read/written. Signed-off-by: Simon Glass --- common/Makefile | 2 + common/cmd_iotrace.c | 73 ++++++++++++++++++++++ common/iotrace.c | 169 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 244 insertions(+) create mode 100644 common/cmd_iotrace.c create mode 100644 common/iotrace.c (limited to 'common') diff --git a/common/Makefile b/common/Makefile index f6cd980..de5cce8 100644 --- a/common/Makefile +++ b/common/Makefile @@ -114,6 +114,7 @@ obj-$(CONFIG_CMD_FUSE) += cmd_fuse.o obj-$(CONFIG_CMD_GETTIME) += cmd_gettime.o obj-$(CONFIG_CMD_GPIO) += cmd_gpio.o obj-$(CONFIG_CMD_I2C) += cmd_i2c.o +obj-$(CONFIG_CMD_IOTRACE) += cmd_iotrace.o obj-$(CONFIG_CMD_HASH) += cmd_hash.o obj-$(CONFIG_CMD_IDE) += cmd_ide.o obj-$(CONFIG_CMD_IMMAP) += cmd_immap.o @@ -261,6 +262,7 @@ obj-$(CONFIG_ANDROID_BOOT_IMAGE) += image-android.o obj-$(CONFIG_OF_LIBFDT) += image-fdt.o obj-$(CONFIG_FIT) += image-fit.o obj-$(CONFIG_FIT_SIGNATURE) += image-sig.o +obj-$(CONFIG_IO_TRACE) += iotrace.o obj-y += memsize.o obj-y += stdio.o diff --git a/common/cmd_iotrace.c b/common/cmd_iotrace.c new file mode 100644 index 0000000..f54276d --- /dev/null +++ b/common/cmd_iotrace.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2014 Google, Inc + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +static void do_print_stats(void) +{ + ulong start, size, offset, count; + + printf("iotrace is %sabled\n", iotrace_get_enabled() ? "en" : "dis"); + iotrace_get_buffer(&start, &size, &offset, &count); + printf("Start: %08lx\n", start); + printf("Size: %08lx\n", size); + printf("Offset: %08lx\n", offset); + printf("Output: %08lx\n", start + offset); + printf("Count: %08lx\n", count); + printf("CRC32: %08lx\n", (ulong)iotrace_get_checksum()); +} + +static int do_set_buffer(int argc, char * const argv[]) +{ + ulong addr = 0, size = 0; + + if (argc == 2) { + addr = simple_strtoul(*argv++, NULL, 16); + size = simple_strtoul(*argv++, NULL, 16); + } else if (argc != 0) { + return CMD_RET_USAGE; + } + + iotrace_set_buffer(addr, size); + + return 0; +} + +int do_iotrace(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + const char *cmd = argc < 2 ? NULL : argv[1]; + + if (!cmd) + return cmd_usage(cmdtp); + switch (*cmd) { + case 'b': + return do_set_buffer(argc - 2, argv + 2); + case 'p': + iotrace_set_enabled(0); + break; + case 'r': + iotrace_set_enabled(1); + break; + case 's': + do_print_stats(); + break; + default: + return CMD_RET_USAGE; + } + + return 0; +} + +U_BOOT_CMD( + iotrace, 4, 1, do_iotrace, + "iotrace utility commands", + "stats - display iotrace stats\n" + "iotrace buffer
- set iotrace buffer\n" + "iotrace pause - pause tracing\n" + "iotrace resume - resume tracing" +); diff --git a/common/iotrace.c b/common/iotrace.c new file mode 100644 index 0000000..ced426e --- /dev/null +++ b/common/iotrace.c @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2014 Google, Inc. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#define IOTRACE_IMPL + +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +/* Support up to the machine word length for now */ +typedef ulong iovalue_t; + +enum iotrace_flags { + IOT_8 = 0, + IOT_16, + IOT_32, + + IOT_READ = 0 << 3, + IOT_WRITE = 1 << 3, +}; + +/** + * struct iotrace_record - Holds a single I/O trace record + * + * @flags: I/O access type + * @addr: Address of access + * @value: Value written or read + */ +struct iotrace_record { + enum iotrace_flags flags; + phys_addr_t addr; + iovalue_t value; +}; + +/** + * struct iotrace - current trace status and checksum + * + * @start: Start address of iotrace buffer + * @size: Size of iotrace buffer in bytes + * @offset: Current write offset into iotrace buffer + * @crc32: Current value of CRC chceksum of trace records + * @enabled: true if enabled, false if disabled + */ +static struct iotrace { + ulong start; + ulong size; + ulong offset; + u32 crc32; + bool enabled; +} iotrace; + +static void add_record(int flags, const void *ptr, ulong value) +{ + struct iotrace_record srec, *rec = &srec; + + /* + * We don't support iotrace before relocation. Since the trace buffer + * is set up by a command, it can't be enabled at present. To change + * this we would need to set the iotrace buffer at build-time. See + * lib/trace.c for how this might be done if you are interested. + */ + if (!(gd->flags & GD_FLG_RELOC) || !iotrace.enabled) + return; + + /* Store it if there is room */ + if (iotrace.offset + sizeof(*rec) < iotrace.size) { + rec = (struct iotrace_record *)map_sysmem( + iotrace.start + iotrace.offset, + sizeof(value)); + } + + rec->flags = flags; + rec->addr = map_to_sysmem(ptr); + rec->value = value; + + /* Update our checksum */ + iotrace.crc32 = crc32(iotrace.crc32, (unsigned char *)rec, + sizeof(*rec)); + + iotrace.offset += sizeof(struct iotrace_record); +} + +u32 iotrace_readl(const void *ptr) +{ + u32 v; + + v = readl(ptr); + add_record(IOT_32 | IOT_READ, ptr, v); + + return v; +} + +void iotrace_writel(ulong value, const void *ptr) +{ + add_record(IOT_32 | IOT_WRITE, ptr, value); + writel(value, ptr); +} + +u16 iotrace_readw(const void *ptr) +{ + u32 v; + + v = readw(ptr); + add_record(IOT_16 | IOT_READ, ptr, v); + + return v; +} + +void iotrace_writew(ulong value, const void *ptr) +{ + add_record(IOT_16 | IOT_WRITE, ptr, value); + writew(value, ptr); +} + +u8 iotrace_readb(const void *ptr) +{ + u32 v; + + v = readb(ptr); + add_record(IOT_8 | IOT_READ, ptr, v); + + return v; +} + +void iotrace_writeb(ulong value, const void *ptr) +{ + add_record(IOT_8 | IOT_WRITE, ptr, value); + writeb(value, ptr); +} + +void iotrace_reset_checksum(void) +{ + iotrace.crc32 = 0; +} + +u32 iotrace_get_checksum(void) +{ + return iotrace.crc32; +} + +void iotrace_set_enabled(int enable) +{ + iotrace.enabled = enable; +} + +int iotrace_get_enabled(void) +{ + return iotrace.enabled; +} + +void iotrace_set_buffer(ulong start, ulong size) +{ + iotrace.start = start; + iotrace.size = size; + iotrace.offset = 0; + iotrace.crc32 = 0; +} + +void iotrace_get_buffer(ulong *start, ulong *size, ulong *offset, ulong *count) +{ + *start = iotrace.start; + *size = iotrace.size; + *offset = iotrace.offset; + *count = iotrace.offset / sizeof(struct iotrace_record); +} -- cgit v1.1 From 4d907025d6a530c0f3d2e869331e863c3e3cc3c2 Mon Sep 17 00:00:00 2001 From: Stephen Warren Date: Thu, 12 Jun 2014 10:28:32 -0600 Subject: sandbox: restore ability to access host fs through standard commands Commit 95fac6ab4589 "sandbox: Use os functions to read host device tree" removed the ability for get_device_and_partition() to handle the "host" device type, and redirect accesses to it to the host filesystem. This broke some unit tests that use this feature. So, revert that change. The code added back by this patch is slightly different to pacify checkpatch. However, we're then left with "host" being both: - A pseudo device that accesses the hosts real filesystem. - An emulated block device, which accesses "sectors" inside a file stored on the host. In order to resolve this discrepancy, rename the pseudo device from host to hostfs, and adjust the unit-tests for this change. The "help sb" output is modified to reflect this rename, and state where the host and hostfs devices should be used. Signed-off-by: Stephen Warren Tested-by: Josh Wu Acked-by: Simon Glass Tested-by: Simon Glass --- common/cmd_sandbox.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'common') diff --git a/common/cmd_sandbox.c b/common/cmd_sandbox.c index 00982b1..3d9fce7 100644 --- a/common/cmd_sandbox.c +++ b/common/cmd_sandbox.c @@ -114,11 +114,13 @@ static int do_sandbox(cmd_tbl_t *cmdtp, int flag, int argc, U_BOOT_CMD( sb, 8, 1, do_sandbox, "Miscellaneous sandbox commands", - "load host [ ] - " + "load hostfs - [ ] - " "load a file from host\n" - "sb ls host - list files on host\n" - "sb save host [] - " + "sb ls hostfs - - list files on host\n" + "sb save hostfs - [] - " "save a file to host\n" "sb bind [] - bind \"host\" device to file\n" - "sb info [] - show device binding & info" + "sb info [] - show device binding & info\n" + "sb commands use the \"hostfs\" device. The \"host\" device is used\n" + "with standard IO commands such as fatls or ext2load" ); -- cgit v1.1