2 * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include <gpxe/tables.h>
28 #include <gpxe/command.h>
36 static struct command commands[0] __table_start ( commands );
37 static struct command commands_end[0] __table_end ( commands );
39 /* Avoid dragging in getopt.o unless a command really uses it */
46 * @v command Command name
47 * @v argv Argument list
48 * @ret rc Command exit status
50 * Execute the named command. Unlike a traditional POSIX execv(),
51 * this function returns the exit status of the command.
53 int execv ( const char *command, char * const argv[] ) {
57 /* Count number of arguments */
58 for ( argc = 0 ; argv[argc] ; argc++ ) {}
62 DBG ( "No command\n" );
66 DBG ( "%s: empty argument list\n", command );
70 /* Reset getopt() library ready for use by the command. This
71 * is an artefact of the POSIX getopt() API within the context
72 * of Etherboot; see the documentation for reset_getopt() for
77 /* Hand off to command implementation */
78 for ( cmd = commands ; cmd < commands_end ; cmd++ ) {
79 if ( strcmp ( command, cmd->name ) == 0 )
80 return cmd->exec ( argc, ( char ** ) argv );
83 printf ( "%s: command not found\n", command );
88 * Split command line into argv array
90 * @v args Command line
91 * @v argv Argument array to populate, or NULL
92 * @ret argc Argument count
94 * Splits the command line into whitespace-delimited arguments. If @c
95 * argv is non-NULL, any whitespace in the command line will be
98 static int split_args ( char *args, char * argv[] ) {
102 /* Skip over any whitespace / convert to NUL */
103 while ( *args == ' ' ) {
108 /* Check for end of line */
111 /* We have found the start of the next argument */
115 /* Skip to start of next whitespace, if any */
116 while ( *args && ( *args != ' ' ) ) {
124 * Execute command line
126 * @v command Command line
127 * @ret rc Command exit status
129 * Execute the named command and arguments.
131 int system ( const char *command ) {
136 /* Obtain temporary modifiable copy of command line */
137 args = strdup ( command );
141 /* Count arguments */
142 argc = split_args ( args, NULL );
144 /* Create argv array and execute command */
146 char * argv[argc + 1];
148 split_args ( args, argv );
150 rc = execv ( argv[0], argv );