These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / ipxe / src / core / exec.c
1 /*
2  * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>.
3  *
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.
8  *
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.
13  *
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., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  *
19  * You can also choose to distribute this program under the terms of
20  * the Unmodified Binary Distribution Licence (as given in the file
21  * COPYING.UBDL), provided that you have satisfied its requirements.
22  */
23
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25
26 #include <stdint.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <ctype.h>
31 #include <unistd.h>
32 #include <getopt.h>
33 #include <errno.h>
34 #include <assert.h>
35 #include <ipxe/tables.h>
36 #include <ipxe/command.h>
37 #include <ipxe/parseopt.h>
38 #include <ipxe/settings.h>
39 #include <ipxe/console.h>
40 #include <ipxe/keys.h>
41 #include <ipxe/process.h>
42 #include <ipxe/nap.h>
43 #include <ipxe/shell.h>
44
45 /** @file
46  *
47  * Command execution
48  *
49  */
50
51 /** Shell stop state */
52 static int stop_state;
53
54 /**
55  * Execute command
56  *
57  * @v command           Command name
58  * @v argv              Argument list
59  * @ret rc              Return status code
60  *
61  * Execute the named command.  Unlike a traditional POSIX execv(),
62  * this function returns the exit status of the command.
63  */
64 int execv ( const char *command, char * const argv[] ) {
65         struct command *cmd;
66         int argc;
67         int rc;
68
69         /* Count number of arguments */
70         for ( argc = 0 ; argv[argc] ; argc++ ) {}
71
72         /* An empty command is deemed to do nothing, successfully */
73         if ( command == NULL ) {
74                 rc = 0;
75                 goto done;
76         }
77
78         /* Sanity checks */
79         if ( argc == 0 ) {
80                 DBG ( "%s: empty argument list\n", command );
81                 rc = -EINVAL;
82                 goto done;
83         }
84
85         /* Reset getopt() library ready for use by the command.  This
86          * is an artefact of the POSIX getopt() API within the context
87          * of Etherboot; see the documentation for reset_getopt() for
88          * details.
89          */
90         reset_getopt();
91
92         /* Hand off to command implementation */
93         for_each_table_entry ( cmd, COMMANDS ) {
94                 if ( strcmp ( command, cmd->name ) == 0 ) {
95                         rc = cmd->exec ( argc, ( char ** ) argv );
96                         goto done;
97                 }
98         }
99
100         printf ( "%s: command not found\n", command );
101         rc = -ENOEXEC;
102
103  done:
104         /* Store error number, if an error occurred */
105         if ( rc ) {
106                 errno = rc;
107                 if ( errno < 0 )
108                         errno = -errno;
109         }
110
111         return rc;
112 }
113
114 /**
115  * Split command line into tokens
116  *
117  * @v command           Command line
118  * @v tokens            Token list to populate, or NULL
119  * @ret count           Number of tokens
120  *
121  * Splits the command line into whitespace-delimited tokens.  If @c
122  * tokens is non-NULL, any whitespace in the command line will be
123  * replaced with NULs.
124  */
125 static int split_command ( char *command, char **tokens ) {
126         int count = 0;
127
128         while ( 1 ) {
129                 /* Skip over any whitespace / convert to NUL */
130                 while ( isspace ( *command ) ) {
131                         if ( tokens )
132                                 *command = '\0';
133                         command++;
134                 }
135                 /* Check for end of line */
136                 if ( ! *command )
137                         break;
138                 /* We have found the start of the next argument */
139                 if ( tokens )
140                         tokens[count] = command;
141                 count++;
142                 /* Skip to start of next whitespace, if any */
143                 while ( *command && ! isspace ( *command ) ) {
144                         command++;
145                 }
146         }
147         return count;
148 }
149
150 /**
151  * Process next command only if previous command succeeded
152  *
153  * @v rc                Status of previous command
154  * @ret process         Process next command
155  */
156 static int process_on_success ( int rc ) {
157         return ( rc == 0 );
158 }
159
160 /**
161  * Process next command only if previous command failed
162  *
163  * @v rc                Status of previous command
164  * @ret process         Process next command
165  */
166 static int process_on_failure ( int rc ) {
167         return ( rc != 0 );
168 }
169
170 /**
171  * Process next command regardless of status from previous command
172  *
173  * @v rc                Status of previous command
174  * @ret process         Process next command
175  */
176 static int process_always ( int rc __unused ) {
177         return 1;
178 }
179
180 /**
181  * Find command terminator
182  *
183  * @v tokens            Token list
184  * @ret process_next    "Should next command be processed?" function
185  * @ret argc            Argument count
186  */
187 static int command_terminator ( char **tokens,
188                                 int ( **process_next ) ( int rc ) ) {
189         unsigned int i;
190
191         /* Find first terminating token */
192         for ( i = 0 ; tokens[i] ; i++ ) {
193                 if ( tokens[i][0] == '#' ) {
194                         /* Start of a comment */
195                         break;
196                 } else if ( strcmp ( tokens[i], "||" ) == 0 ) {
197                         /* Short-circuit logical OR */
198                         *process_next = process_on_failure;
199                         return i;
200                 } else if ( strcmp ( tokens[i], "&&" ) == 0 ) {
201                         /* Short-circuit logical AND */
202                         *process_next = process_on_success;
203                         return i;
204                 } else if ( strcmp ( tokens[i], ";" ) == 0 ) {
205                         /* Process next command unconditionally */
206                         *process_next = process_always;
207                         return i;
208                 }
209         }
210
211         /* End of token list */
212         *process_next = NULL;
213         return i;
214 }
215
216 /**
217  * Set shell stop state
218  *
219  * @v stop              Shell stop state
220  */
221 void shell_stop ( int stop ) {
222         stop_state = stop;
223 }
224
225 /**
226  * Test and consume shell stop state
227  *
228  * @v stop              Shell stop state to consume
229  * @v stopped           Shell had been stopped
230  */
231 int shell_stopped ( int stop ) {
232         int stopped;
233
234         /* Test to see if we need to stop */
235         stopped = ( stop_state >= stop );
236
237         /* Consume stop state */
238         if ( stop_state <= stop )
239                 stop_state = 0;
240
241         return stopped;
242 }
243
244 /**
245  * Expand settings within a token list
246  *
247  * @v argc              Argument count
248  * @v tokens            Token list
249  * @v argv              Argument list to fill in
250  * @ret rc              Return status code
251  */
252 static int expand_tokens ( int argc, char **tokens, char **argv ) {
253         int i;
254
255         /* Expand each token in turn */
256         for ( i = 0 ; i < argc ; i++ ) {
257                 argv[i] = expand_settings ( tokens[i] );
258                 if ( ! argv[i] )
259                         goto err_expand_settings;
260         }
261
262         return 0;
263
264  err_expand_settings:
265         assert ( argv[i] == NULL );
266         for ( ; i >= 0 ; i-- )
267                 free ( argv[i] );
268         return -ENOMEM;
269 }
270
271 /**
272  * Free an expanded token list
273  *
274  * @v argv              Argument list
275  */
276 static void free_tokens ( char **argv ) {
277
278         /* Free each expanded argument */
279         while ( *argv )
280                 free ( *(argv++) );
281 }
282
283 /**
284  * Execute command line
285  *
286  * @v command           Command line
287  * @ret rc              Return status code
288  *
289  * Execute the named command and arguments.
290  */
291 int system ( const char *command ) {
292         int count = split_command ( ( char * ) command, NULL );
293         char *all_tokens[ count + 1 ];
294         int ( * process_next ) ( int rc );
295         char *command_copy;
296         char **tokens;
297         int argc;
298         int process;
299         int rc = 0;
300
301         /* Create modifiable copy of command */
302         command_copy = strdup ( command );
303         if ( ! command_copy )
304                 return -ENOMEM;
305
306         /* Split command into tokens */
307         split_command ( command_copy, all_tokens );
308         all_tokens[count] = NULL;
309
310         /* Process individual commands */
311         process = 1;
312         for ( tokens = all_tokens ; ; tokens += ( argc + 1 ) ) {
313
314                 /* Find command terminator */
315                 argc = command_terminator ( tokens, &process_next );
316
317                 /* Expand tokens and execute command */
318                 if ( process ) {
319                         char *argv[ argc + 1 ];
320
321                         /* Expand tokens */
322                         if ( ( rc = expand_tokens ( argc, tokens, argv ) ) != 0)
323                                 break;
324                         argv[argc] = NULL;
325
326                         /* Execute command */
327                         rc = execv ( argv[0], argv );
328
329                         /* Free tokens */
330                         free_tokens ( argv );
331                 }
332
333                 /* Stop processing, if applicable */
334                 if ( shell_stopped ( SHELL_STOP_COMMAND ) )
335                         break;
336
337                 /* Stop processing if we have reached the end of the
338                  * command.
339                  */
340                 if ( ! process_next )
341                         break;
342
343                 /* Determine whether or not to process next command */
344                 process = process_next ( rc );
345         }
346
347         /* Free modified copy of command */
348         free ( command_copy );
349
350         return rc;
351 }
352
353 /**
354  * Concatenate arguments
355  *
356  * @v args              Argument list (NULL-terminated)
357  * @ret string          Concatenated arguments
358  *
359  * The returned string is allocated with malloc().  The caller is
360  * responsible for eventually free()ing this string.
361  */
362 char * concat_args ( char **args ) {
363         char **arg;
364         size_t len;
365         char *string;
366         char *ptr;
367
368         /* Calculate total string length */
369         len = 1 /* NUL */;
370         for ( arg = args ; *arg ; arg++ )
371                 len += ( 1 /* possible space */ + strlen ( *arg ) );
372
373         /* Allocate string */
374         string = zalloc ( len );
375         if ( ! string )
376                 return NULL;
377
378         /* Populate string */
379         ptr = string;
380         for ( arg = args ; *arg ; arg++ ) {
381                 ptr += sprintf ( ptr, "%s%s",
382                                  ( ( arg == args ) ? "" : " " ), *arg );
383         }
384         assert ( ptr < ( string + len ) );
385
386         return string;
387 }
388
389 /** "echo" options */
390 struct echo_options {
391         /** Do not print trailing newline */
392         int no_newline;
393 };
394
395 /** "echo" option list */
396 static struct option_descriptor echo_opts[] = {
397         OPTION_DESC ( "n", 'n', no_argument,
398                       struct echo_options, no_newline, parse_flag ),
399 };
400
401 /** "echo" command descriptor */
402 static struct command_descriptor echo_cmd =
403         COMMAND_DESC ( struct echo_options, echo_opts, 0, MAX_ARGUMENTS,
404                        "[...]" );
405
406 /**
407  * "echo" command
408  *
409  * @v argc              Argument count
410  * @v argv              Argument list
411  * @ret rc              Return status code
412  */
413 static int echo_exec ( int argc, char **argv ) {
414         struct echo_options opts;
415         char *text;
416         int rc;
417
418         /* Parse options */
419         if ( ( rc = parse_options ( argc, argv, &echo_cmd, &opts ) ) != 0 )
420                 return rc;
421
422         /* Parse text */
423         text = concat_args ( &argv[optind] );
424         if ( ! text )
425                 return -ENOMEM;
426
427         /* Print text */
428         printf ( "%s%s", text, ( opts.no_newline ? "" : "\n" ) );
429
430         free ( text );
431         return 0;
432 }
433
434 /** "echo" command */
435 struct command echo_command __command = {
436         .name = "echo",
437         .exec = echo_exec,
438 };
439
440 /** "exit" options */
441 struct exit_options {};
442
443 /** "exit" option list */
444 static struct option_descriptor exit_opts[] = {};
445
446 /** "exit" command descriptor */
447 static struct command_descriptor exit_cmd =
448         COMMAND_DESC ( struct exit_options, exit_opts, 0, 1, "[<status>]" );
449
450 /**
451  * "exit" command
452  *
453  * @v argc              Argument count
454  * @v argv              Argument list
455  * @ret rc              Return status code
456  */
457 static int exit_exec ( int argc, char **argv ) {
458         struct exit_options opts;
459         unsigned int exit_code = 0;
460         int rc;
461
462         /* Parse options */
463         if ( ( rc = parse_options ( argc, argv, &exit_cmd, &opts ) ) != 0 )
464                 return rc;
465
466         /* Parse exit status, if present */
467         if ( optind != argc ) {
468                 if ( ( rc = parse_integer ( argv[optind], &exit_code ) ) != 0 )
469                         return rc;
470         }
471
472         /* Stop shell processing */
473         shell_stop ( SHELL_STOP_COMMAND_SEQUENCE );
474
475         return exit_code;
476 }
477
478 /** "exit" command */
479 struct command exit_command __command = {
480         .name = "exit",
481         .exec = exit_exec,
482 };
483
484 /** "isset" options */
485 struct isset_options {};
486
487 /** "isset" option list */
488 static struct option_descriptor isset_opts[] = {};
489
490 /** "isset" command descriptor */
491 static struct command_descriptor isset_cmd =
492         COMMAND_DESC ( struct isset_options, isset_opts, 1, 1, "<value>" );
493
494 /**
495  * "isset" command
496  *
497  * @v argc              Argument count
498  * @v argv              Argument list
499  * @ret rc              Return status code
500  */
501 static int isset_exec ( int argc, char **argv ) {
502         struct isset_options opts;
503         int rc;
504
505         /* Parse options */
506         if ( ( rc = parse_options ( argc, argv, &isset_cmd, &opts ) ) != 0 )
507                 return rc;
508
509         /* Return success iff argument is non-empty */
510         return ( argv[optind][0] ? 0 : -ENOENT );
511 }
512
513 /** "isset" command */
514 struct command isset_command __command = {
515         .name = "isset",
516         .exec = isset_exec,
517 };
518
519 /** "iseq" options */
520 struct iseq_options {};
521
522 /** "iseq" option list */
523 static struct option_descriptor iseq_opts[] = {};
524
525 /** "iseq" command descriptor */
526 static struct command_descriptor iseq_cmd =
527         COMMAND_DESC ( struct iseq_options, iseq_opts, 2, 2,
528                        "<value1> <value2>" );
529
530 /**
531  * "iseq" command
532  *
533  * @v argc              Argument count
534  * @v argv              Argument list
535  * @ret rc              Return status code
536  */
537 static int iseq_exec ( int argc, char **argv ) {
538         struct iseq_options opts;
539         int rc;
540
541         /* Parse options */
542         if ( ( rc = parse_options ( argc, argv, &iseq_cmd, &opts ) ) != 0 )
543                 return rc;
544
545         /* Return success iff arguments are equal */
546         return ( ( strcmp ( argv[optind], argv[ optind + 1 ] ) == 0 ) ?
547                  0 : -ERANGE );
548 }
549
550 /** "iseq" command */
551 struct command iseq_command __command = {
552         .name = "iseq",
553         .exec = iseq_exec,
554 };
555
556 /** "sleep" options */
557 struct sleep_options {};
558
559 /** "sleep" option list */
560 static struct option_descriptor sleep_opts[] = {};
561
562 /** "sleep" command descriptor */
563 static struct command_descriptor sleep_cmd =
564         COMMAND_DESC ( struct sleep_options, sleep_opts, 1, 1, "<seconds>" );
565
566 /**
567  * "sleep" command
568  *
569  * @v argc              Argument count
570  * @v argv              Argument list
571  * @ret rc              Return status code
572  */
573 static int sleep_exec ( int argc, char **argv ) {
574         struct sleep_options opts;
575         unsigned int seconds;
576         unsigned long start;
577         unsigned long delay;
578         int rc;
579
580         /* Parse options */
581         if ( ( rc = parse_options ( argc, argv, &sleep_cmd, &opts ) ) != 0 )
582                 return rc;
583
584         /* Parse number of seconds */
585         if ( ( rc = parse_integer ( argv[optind], &seconds ) ) != 0 )
586                 return rc;
587
588         /* Delay for specified number of seconds */
589         start = currticks();
590         delay = ( seconds * TICKS_PER_SEC );
591         while ( ( currticks() - start ) <= delay ) {
592                 step();
593                 if ( iskey() && ( getchar() == CTRL_C ) )
594                         return -ECANCELED;
595                 cpu_nap();
596         }
597
598         return 0;
599 }
600
601 /** "sleep" command */
602 struct command sleep_command __command = {
603         .name = "sleep",
604         .exec = sleep_exec,
605 };