5e04573e0c66145bf6d3d3a62d6e9e6b5a2c259f
[external/binutils.git] / sim / common / sim-options.c
1 /* Simulator option handling.
2    Copyright (C) 1996-2015 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.
4
5 This file is part of GDB, the GNU debugger.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "sim-main.h"
21 #ifdef HAVE_STRING_H
22 #include <string.h>
23 #else
24 #ifdef HAVE_STRINGS_H
25 #include <strings.h>
26 #endif
27 #endif
28 #ifdef HAVE_STDLIB_H
29 #include <stdlib.h>
30 #endif
31 #include <ctype.h>
32 #include "libiberty.h"
33 #include "sim-options.h"
34 #include "sim-io.h"
35 #include "sim-assert.h"
36 #include "version.h"
37
38 #include "bfd.h"
39
40 /* Add a set of options to the simulator.
41    TABLE is an array of OPTIONS terminated by a NULL `opt.name' entry.
42    This is intended to be called by modules in their `install' handler.  */
43
44 SIM_RC
45 sim_add_option_table (SIM_DESC sd, sim_cpu *cpu, const OPTION *table)
46 {
47   struct option_list *ol = ((struct option_list *)
48                             xmalloc (sizeof (struct option_list)));
49
50   /* Note: The list is constructed in the reverse order we're called so
51      later calls will override earlier ones (in case that ever happens).
52      This is the intended behaviour.  */
53
54   if (cpu)
55     {
56       ol->next = CPU_OPTIONS (cpu);
57       ol->options = table;
58       CPU_OPTIONS (cpu) = ol;
59     }
60   else
61     {
62       ol->next = STATE_OPTIONS (sd);
63       ol->options = table;
64       STATE_OPTIONS (sd) = ol;
65     }
66
67   return SIM_RC_OK;
68 }
69
70 /* Standard option table.
71    Modules may specify additional ones.
72    The caller of sim_parse_args may also specify additional options
73    by calling sim_add_option_table first.  */
74
75 static DECLARE_OPTION_HANDLER (standard_option_handler);
76
77 /* FIXME: We shouldn't print in --help output options that aren't usable.
78    Some fine tuning will be necessary.  One can either move less general
79    options to another table or use a HAVE_FOO macro to ifdef out unavailable
80    options.  */
81
82 /* ??? One might want to conditionally compile out the entries that
83    aren't enabled.  There's a distinction, however, between options a
84    simulator can't support and options that haven't been configured in.
85    Certainly options a simulator can't support shouldn't appear in the
86    output of --help.  Whether the same thing applies to options that haven't
87    been configured in or not isn't something I can get worked up over.
88    [Note that conditionally compiling them out might simply involve moving
89    the option to another table.]
90    If you decide to conditionally compile them out as well, delete this
91    comment and add a comment saying that that is the rule.  */
92
93 typedef enum {
94   OPTION_DEBUG_INSN = OPTION_START,
95   OPTION_DEBUG_FILE,
96   OPTION_DO_COMMAND,
97   OPTION_ARCHITECTURE,
98   OPTION_TARGET,
99   OPTION_ARCHITECTURE_INFO,
100   OPTION_ENVIRONMENT,
101   OPTION_ALIGNMENT,
102   OPTION_VERBOSE,
103   OPTION_ENDIAN,
104   OPTION_DEBUG,
105   OPTION_HELP,
106   OPTION_VERSION,
107 #ifdef SIM_H8300 /* FIXME: Should be movable to h8300 dir.  */
108   OPTION_H8300H,
109   OPTION_H8300S,
110   OPTION_H8300SX,
111 #endif
112   OPTION_LOAD_LMA,
113   OPTION_LOAD_VMA,
114   OPTION_SYSROOT
115 } STANDARD_OPTIONS;
116
117 static const OPTION standard_options[] =
118 {
119   { {"verbose", no_argument, NULL, OPTION_VERBOSE},
120       'v', NULL, "Verbose output",
121       standard_option_handler, NULL },
122
123   { {"endian", required_argument, NULL, OPTION_ENDIAN},
124       'E', "big|little", "Set endianness",
125       standard_option_handler, NULL },
126
127 #ifdef SIM_HAVE_ENVIRONMENT
128   /* This option isn't supported unless all choices are supported in keeping
129      with the goal of not printing in --help output things the simulator can't
130      do [as opposed to things that just haven't been configured in].  */
131   { {"environment", required_argument, NULL, OPTION_ENVIRONMENT},
132       '\0', "user|virtual|operating", "Set running environment",
133       standard_option_handler },
134 #endif
135
136   { {"alignment", required_argument, NULL, OPTION_ALIGNMENT},
137       '\0', "strict|nonstrict|forced", "Set memory access alignment",
138       standard_option_handler },
139
140   { {"debug", no_argument, NULL, OPTION_DEBUG},
141       'D', NULL, "Print debugging messages",
142       standard_option_handler },
143   { {"debug-insn", no_argument, NULL, OPTION_DEBUG_INSN},
144       '\0', NULL, "Print instruction debugging messages",
145       standard_option_handler },
146   { {"debug-file", required_argument, NULL, OPTION_DEBUG_FILE},
147       '\0', "FILE NAME", "Specify debugging output file",
148       standard_option_handler },
149
150 #ifdef SIM_H8300 /* FIXME: Should be movable to h8300 dir.  */
151   { {"h8300h", no_argument, NULL, OPTION_H8300H},
152       'h', NULL, "Indicate the CPU is H8/300H",
153       standard_option_handler },
154   { {"h8300s", no_argument, NULL, OPTION_H8300S},
155       'S', NULL, "Indicate the CPU is H8S",
156       standard_option_handler },
157   { {"h8300sx", no_argument, NULL, OPTION_H8300SX},
158       'x', NULL, "Indicate the CPU is H8SX",
159       standard_option_handler },
160 #endif
161
162   { {"do-command", required_argument, NULL, OPTION_DO_COMMAND},
163       '\0', "COMMAND", ""/*undocumented*/,
164       standard_option_handler },
165
166   { {"help", no_argument, NULL, OPTION_HELP},
167       'H', NULL, "Print help information",
168       standard_option_handler },
169   { {"version", no_argument, NULL, OPTION_VERSION},
170       '\0', NULL, "Print version information",
171       standard_option_handler },
172
173   { {"architecture", required_argument, NULL, OPTION_ARCHITECTURE},
174       '\0', "MACHINE", "Specify the architecture to use",
175       standard_option_handler },
176   { {"architecture-info", no_argument, NULL, OPTION_ARCHITECTURE_INFO},
177       '\0', NULL, "List supported architectures",
178       standard_option_handler },
179   { {"info-architecture", no_argument, NULL, OPTION_ARCHITECTURE_INFO},
180       '\0', NULL, NULL,
181       standard_option_handler },
182
183   { {"target", required_argument, NULL, OPTION_TARGET},
184       '\0', "BFDNAME", "Specify the object-code format for the object files",
185       standard_option_handler },
186
187 #ifdef SIM_HANDLES_LMA
188   { {"load-lma", no_argument, NULL, OPTION_LOAD_LMA},
189       '\0', NULL,
190 #if SIM_HANDLES_LMA
191     "Use VMA or LMA addresses when loading image (default LMA)",
192 #else
193     "Use VMA or LMA addresses when loading image (default VMA)",
194 #endif
195       standard_option_handler, "load-{lma,vma}" },
196   { {"load-vma", no_argument, NULL, OPTION_LOAD_VMA},
197       '\0', NULL, "", standard_option_handler,  "" },
198 #endif
199
200   { {"sysroot", required_argument, NULL, OPTION_SYSROOT},
201       '\0', "SYSROOT",
202     "Root for system calls with absolute file-names and cwd at start",
203       standard_option_handler, NULL },
204
205   { {NULL, no_argument, NULL, 0}, '\0', NULL, NULL, NULL, NULL }
206 };
207
208 static SIM_RC
209 standard_option_handler (SIM_DESC sd, sim_cpu *cpu, int opt,
210                          char *arg, int is_command)
211 {
212   int i,n;
213
214   switch ((STANDARD_OPTIONS) opt)
215     {
216     case OPTION_VERBOSE:
217       STATE_VERBOSE_P (sd) = 1;
218       break;
219
220     case OPTION_ENDIAN:
221       if (strcmp (arg, "big") == 0)
222         {
223           if (WITH_TARGET_BYTE_ORDER == LITTLE_ENDIAN)
224             {
225               sim_io_eprintf (sd, "Simulator compiled for little endian only.\n");
226               return SIM_RC_FAIL;
227             }
228           /* FIXME:wip: Need to set something in STATE_CONFIG.  */
229           current_target_byte_order = BIG_ENDIAN;
230         }
231       else if (strcmp (arg, "little") == 0)
232         {
233           if (WITH_TARGET_BYTE_ORDER == BIG_ENDIAN)
234             {
235               sim_io_eprintf (sd, "Simulator compiled for big endian only.\n");
236               return SIM_RC_FAIL;
237             }
238           /* FIXME:wip: Need to set something in STATE_CONFIG.  */
239           current_target_byte_order = LITTLE_ENDIAN;
240         }
241       else
242         {
243           sim_io_eprintf (sd, "Invalid endian specification `%s'\n", arg);
244           return SIM_RC_FAIL;
245         }
246       break;
247
248     case OPTION_ENVIRONMENT:
249       if (strcmp (arg, "user") == 0)
250         STATE_ENVIRONMENT (sd) = USER_ENVIRONMENT;
251       else if (strcmp (arg, "virtual") == 0)
252         STATE_ENVIRONMENT (sd) = VIRTUAL_ENVIRONMENT;
253       else if (strcmp (arg, "operating") == 0)
254         STATE_ENVIRONMENT (sd) = OPERATING_ENVIRONMENT;
255       else
256         {
257           sim_io_eprintf (sd, "Invalid environment specification `%s'\n", arg);
258           return SIM_RC_FAIL;
259         }
260       if (WITH_ENVIRONMENT != ALL_ENVIRONMENT
261           && WITH_ENVIRONMENT != STATE_ENVIRONMENT (sd))
262         {
263           const char *type;
264           switch (WITH_ENVIRONMENT)
265             {
266             case USER_ENVIRONMENT: type = "user"; break;
267             case VIRTUAL_ENVIRONMENT: type = "virtual"; break;
268             case OPERATING_ENVIRONMENT: type = "operating"; break;
269             }
270           sim_io_eprintf (sd, "Simulator compiled for the %s environment only.\n",
271                           type);
272           return SIM_RC_FAIL;
273         }
274       break;
275
276     case OPTION_ALIGNMENT:
277       if (strcmp (arg, "strict") == 0)
278         {
279           if (WITH_ALIGNMENT == 0 || WITH_ALIGNMENT == STRICT_ALIGNMENT)
280             {
281               current_alignment = STRICT_ALIGNMENT;
282               break;
283             }
284         }
285       else if (strcmp (arg, "nonstrict") == 0)
286         {
287           if (WITH_ALIGNMENT == 0 || WITH_ALIGNMENT == NONSTRICT_ALIGNMENT)
288             {
289               current_alignment = NONSTRICT_ALIGNMENT;
290               break;
291             }
292         }
293       else if (strcmp (arg, "forced") == 0)
294         {
295           if (WITH_ALIGNMENT == 0 || WITH_ALIGNMENT == FORCED_ALIGNMENT)
296             {
297               current_alignment = FORCED_ALIGNMENT;
298               break;
299             }
300         }
301       else
302         {
303           sim_io_eprintf (sd, "Invalid alignment specification `%s'\n", arg);
304           return SIM_RC_FAIL;
305         }
306       switch (WITH_ALIGNMENT)
307         {
308         case STRICT_ALIGNMENT:
309           sim_io_eprintf (sd, "Simulator compiled for strict alignment only.\n");
310           break;
311         case NONSTRICT_ALIGNMENT:
312           sim_io_eprintf (sd, "Simulator compiled for nonstrict alignment only.\n");
313           break;
314         case FORCED_ALIGNMENT:
315           sim_io_eprintf (sd, "Simulator compiled for forced alignment only.\n");
316           break;
317         }
318       return SIM_RC_FAIL;
319
320     case OPTION_DEBUG:
321       if (! WITH_DEBUG)
322         sim_io_eprintf (sd, "Debugging not compiled in, `-D' ignored\n");
323       else
324         {
325           for (n = 0; n < MAX_NR_PROCESSORS; ++n)
326             for (i = 0; i < MAX_DEBUG_VALUES; ++i)
327               CPU_DEBUG_FLAGS (STATE_CPU (sd, n))[i] = 1;
328         }
329       break;
330
331     case OPTION_DEBUG_INSN :
332       if (! WITH_DEBUG)
333         sim_io_eprintf (sd, "Debugging not compiled in, `--debug-insn' ignored\n");
334       else
335         {
336           for (n = 0; n < MAX_NR_PROCESSORS; ++n)
337             CPU_DEBUG_FLAGS (STATE_CPU (sd, n))[DEBUG_INSN_IDX] = 1;
338         }
339       break;
340
341     case OPTION_DEBUG_FILE :
342       if (! WITH_DEBUG)
343         sim_io_eprintf (sd, "Debugging not compiled in, `--debug-file' ignored\n");
344       else
345         {
346           FILE *f = fopen (arg, "w");
347
348           if (f == NULL)
349             {
350               sim_io_eprintf (sd, "Unable to open debug output file `%s'\n", arg);
351               return SIM_RC_FAIL;
352             }
353           for (n = 0; n < MAX_NR_PROCESSORS; ++n)
354             CPU_DEBUG_FILE (STATE_CPU (sd, n)) = f;
355         }
356       break;
357
358 #ifdef SIM_H8300 /* FIXME: Can be moved to h8300 dir.  */
359     case OPTION_H8300H:
360       set_h8300h (bfd_mach_h8300h);
361       break;
362     case OPTION_H8300S:
363       set_h8300h (bfd_mach_h8300s);
364       break;
365     case OPTION_H8300SX:
366       set_h8300h (bfd_mach_h8300sx);
367       break;
368 #endif
369
370     case OPTION_DO_COMMAND:
371       sim_do_command (sd, arg);
372       break;
373
374     case OPTION_ARCHITECTURE:
375       {
376         const struct bfd_arch_info *ap = bfd_scan_arch (arg);
377         if (ap == NULL)
378           {
379             sim_io_eprintf (sd, "Architecture `%s' unknown\n", arg);
380             return SIM_RC_FAIL;
381           }
382         STATE_ARCHITECTURE (sd) = ap;
383         break;
384       }
385
386     case OPTION_ARCHITECTURE_INFO:
387       {
388         const char **list = bfd_arch_list ();
389         const char **lp;
390         if (list == NULL)
391           abort ();
392         sim_io_printf (sd, "Possible architectures:");
393         for (lp = list; *lp != NULL; lp++)
394           sim_io_printf (sd, " %s", *lp);
395         sim_io_printf (sd, "\n");
396         free (list);
397         break;
398       }
399
400     case OPTION_TARGET:
401       {
402         STATE_TARGET (sd) = xstrdup (arg);
403         break;
404       }
405
406     case OPTION_LOAD_LMA:
407       {
408         STATE_LOAD_AT_LMA_P (sd) = 1;
409         break;
410       }
411
412     case OPTION_LOAD_VMA:
413       {
414         STATE_LOAD_AT_LMA_P (sd) = 0;
415         break;
416       }
417
418     case OPTION_HELP:
419       sim_print_help (sd, is_command);
420       if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
421         exit (0);
422       /* FIXME: 'twould be nice to do something similar if gdb.  */
423       break;
424
425     case OPTION_VERSION:
426       sim_io_printf (sd, "GNU simulator %s%s\n", PKGVERSION, version);
427       if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
428         exit (0);
429       break;
430
431     case OPTION_SYSROOT:
432       /* Don't leak memory in the odd event that there's lots of
433          --sysroot=... options.  We treat "" specially since this
434          is the statically initialized value and cannot free it.  */
435       if (simulator_sysroot[0] != '\0')
436         free (simulator_sysroot);
437       if (arg[0] != '\0')
438         simulator_sysroot = xstrdup (arg);
439       else
440         simulator_sysroot = "";
441       break;
442     }
443
444   return SIM_RC_OK;
445 }
446
447 /* Add the standard option list to the simulator.  */
448
449 SIM_RC
450 standard_install (SIM_DESC sd)
451 {
452   SIM_ASSERT (STATE_MAGIC (sd) == SIM_MAGIC_NUMBER);
453   if (sim_add_option_table (sd, NULL, standard_options) != SIM_RC_OK)
454     return SIM_RC_FAIL;
455 #ifdef SIM_HANDLES_LMA
456   STATE_LOAD_AT_LMA_P (sd) = SIM_HANDLES_LMA;
457 #endif
458   return SIM_RC_OK;
459 }
460
461 /* Return non-zero if arg is a duplicate argument.
462    If ARG is NULL, initialize.  */
463
464 #define ARG_HASH_SIZE 97
465 #define ARG_HASH(a) ((256 * (unsigned char) a[0] + (unsigned char) a[1]) % ARG_HASH_SIZE)
466
467 static int
468 dup_arg_p (const char *arg)
469 {
470   int hash;
471   static const char **arg_table = NULL;
472
473   if (arg == NULL)
474     {
475       if (arg_table == NULL)
476         arg_table = (const char **) xmalloc (ARG_HASH_SIZE * sizeof (char *));
477       memset (arg_table, 0, ARG_HASH_SIZE * sizeof (char *));
478       return 0;
479     }
480
481   hash = ARG_HASH (arg);
482   while (arg_table[hash] != NULL)
483     {
484       if (strcmp (arg, arg_table[hash]) == 0)
485         return 1;
486       /* We assume there won't be more than ARG_HASH_SIZE arguments so we
487          don't check if the table is full.  */
488       if (++hash == ARG_HASH_SIZE)
489         hash = 0;
490     }
491   arg_table[hash] = arg;
492   return 0;
493 }
494
495 /* Called by sim_open to parse the arguments.  */
496
497 SIM_RC
498 sim_parse_args (SIM_DESC sd, char **argv)
499 {
500   int c, i, argc, num_opts;
501   char *p, *short_options;
502   /* The `val' option struct entry is dynamically assigned for options that
503      only come in the long form.  ORIG_VAL is used to get the original value
504      back.  */
505   int *orig_val;
506   struct option *lp, *long_options;
507   const struct option_list *ol;
508   const OPTION *opt;
509   OPTION_HANDLER **handlers;
510   sim_cpu **opt_cpu;
511   SIM_RC result = SIM_RC_OK;
512
513   /* Count the number of arguments.  */
514   for (argc = 0; argv[argc] != NULL; ++argc)
515     continue;
516
517   /* Count the number of options.  */
518   num_opts = 0;
519   for (ol = STATE_OPTIONS (sd); ol != NULL; ol = ol->next)
520     for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
521       ++num_opts;
522   for (i = 0; i < MAX_NR_PROCESSORS; ++i)
523     for (ol = CPU_OPTIONS (STATE_CPU (sd, i)); ol != NULL; ol = ol->next)
524       for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
525         ++num_opts;
526
527   /* Initialize duplicate argument checker.  */
528   (void) dup_arg_p (NULL);
529
530   /* Build the option table for getopt.  */
531
532   long_options = NZALLOC (struct option, num_opts + 1);
533   lp = long_options;
534   short_options = NZALLOC (char, num_opts * 3 + 1);
535   p = short_options;
536   handlers = NZALLOC (OPTION_HANDLER *, OPTION_START + num_opts);
537   orig_val = NZALLOC (int, OPTION_START + num_opts);
538   opt_cpu = NZALLOC (sim_cpu *, OPTION_START + num_opts);
539
540   /* Set '+' as first char so argument permutation isn't done.  This
541      is done to stop getopt_long returning options that appear after
542      the target program.  Such options should be passed unchanged into
543      the program image. */
544   *p++ = '+';
545
546   for (i = OPTION_START, ol = STATE_OPTIONS (sd); ol != NULL; ol = ol->next)
547     for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
548       {
549         if (dup_arg_p (opt->opt.name))
550           continue;
551         if (opt->shortopt != 0)
552           {
553             *p++ = opt->shortopt;
554             if (opt->opt.has_arg == required_argument)
555               *p++ = ':';
556             else if (opt->opt.has_arg == optional_argument)
557               { *p++ = ':'; *p++ = ':'; }
558             handlers[(unsigned char) opt->shortopt] = opt->handler;
559             if (opt->opt.val != 0)
560               orig_val[(unsigned char) opt->shortopt] = opt->opt.val;
561             else
562               orig_val[(unsigned char) opt->shortopt] = opt->shortopt;
563           }
564         if (opt->opt.name != NULL)
565           {
566             *lp = opt->opt;
567             /* Dynamically assign `val' numbers for long options. */
568             lp->val = i++;
569             handlers[lp->val] = opt->handler;
570             orig_val[lp->val] = opt->opt.val;
571             opt_cpu[lp->val] = NULL;
572             ++lp;
573           }
574       }
575
576   for (c = 0; c < MAX_NR_PROCESSORS; ++c)
577     {
578       sim_cpu *cpu = STATE_CPU (sd, c);
579       for (ol = CPU_OPTIONS (cpu); ol != NULL; ol = ol->next)
580         for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
581           {
582 #if 0 /* Each option is prepended with --<cpuname>- so this greatly cuts down
583          on the need for dup_arg_p checking.  Maybe in the future it'll be
584          needed so this is just commented out, and not deleted.  */
585             if (dup_arg_p (opt->opt.name))
586               continue;
587 #endif
588             /* Don't allow short versions of cpu specific options for now.  */
589             if (opt->shortopt != 0)
590               {
591                 sim_io_eprintf (sd, "internal error, short cpu specific option");
592                 result = SIM_RC_FAIL;
593                 break;
594               }
595             if (opt->opt.name != NULL)
596               {
597                 char *name;
598                 *lp = opt->opt;
599                 /* Prepend --<cpuname>- to the option.  */
600                 if (asprintf (&name, "%s-%s", CPU_NAME (cpu), lp->name) < 0)
601                   {
602                     sim_io_eprintf (sd, "internal error, out of memory");
603                     result = SIM_RC_FAIL;
604                     break;
605                   }
606                 lp->name = name;
607                 /* Dynamically assign `val' numbers for long options. */
608                 lp->val = i++;
609                 handlers[lp->val] = opt->handler;
610                 orig_val[lp->val] = opt->opt.val;
611                 opt_cpu[lp->val] = cpu;
612                 ++lp;
613               }
614           }
615     }
616
617   /* Terminate the short and long option lists.  */
618   *p = 0;
619   lp->name = NULL;
620
621   /* Ensure getopt is initialized.  */
622   optind = 0;
623
624   while (1)
625     {
626       int longind, optc;
627
628       optc = getopt_long (argc, argv, short_options, long_options, &longind);
629       if (optc == -1)
630         {
631           if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
632             STATE_PROG_ARGV (sd) = dupargv (argv + optind);
633           break;
634         }
635       if (optc == '?')
636         {
637           result = SIM_RC_FAIL;
638           break;
639         }
640
641       if ((*handlers[optc]) (sd, opt_cpu[optc], orig_val[optc], optarg, 0/*!is_command*/) == SIM_RC_FAIL)
642         {
643           result = SIM_RC_FAIL;
644           break;
645         }
646     }
647
648   free (long_options);
649   free (short_options);
650   free (handlers);
651   free (opt_cpu);
652   free (orig_val);
653   return result;
654 }
655
656 /* Utility of sim_print_help to print a list of option tables.  */
657
658 static void
659 print_help (SIM_DESC sd, sim_cpu *cpu, const struct option_list *ol, int is_command)
660 {
661   const OPTION *opt;
662
663   for ( ; ol != NULL; ol = ol->next)
664     for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
665       {
666         const int indent = 30;
667         int comma, len;
668         const OPTION *o;
669
670         if (dup_arg_p (opt->opt.name))
671           continue;
672
673         if (opt->doc == NULL)
674           continue;
675
676         if (opt->doc_name != NULL && opt->doc_name [0] == '\0')
677           continue;
678
679         sim_io_printf (sd, "  ");
680
681         comma = 0;
682         len = 2;
683
684         /* list any short options (aliases) for the current OPT */
685         if (!is_command)
686           {
687             o = opt;
688             do
689               {
690                 if (o->shortopt != '\0')
691                   {
692                     sim_io_printf (sd, "%s-%c", comma ? ", " : "", o->shortopt);
693                     len += (comma ? 2 : 0) + 2;
694                     if (o->arg != NULL)
695                       {
696                         if (o->opt.has_arg == optional_argument)
697                           {
698                             sim_io_printf (sd, "[%s]", o->arg);
699                             len += 1 + strlen (o->arg) + 1;
700                           }
701                         else
702                           {
703                             sim_io_printf (sd, " %s", o->arg);
704                             len += 1 + strlen (o->arg);
705                           }
706                       }
707                     comma = 1;
708                   }
709                 ++o;
710               }
711             while (OPTION_VALID_P (o) && o->doc == NULL);
712           }
713
714         /* list any long options (aliases) for the current OPT */
715         o = opt;
716         do
717           {
718             const char *name;
719             const char *cpu_prefix = cpu ? CPU_NAME (cpu) : NULL;
720             if (o->doc_name != NULL)
721               name = o->doc_name;
722             else
723               name = o->opt.name;
724             if (name != NULL)
725               {
726                 sim_io_printf (sd, "%s%s%s%s%s",
727                                comma ? ", " : "",
728                                is_command ? "" : "--",
729                                cpu ? cpu_prefix : "",
730                                cpu ? "-" : "",
731                                name);
732                 len += ((comma ? 2 : 0)
733                         + (is_command ? 0 : 2)
734                         + strlen (name));
735                 if (o->arg != NULL)
736                   {
737                     if (o->opt.has_arg == optional_argument)
738                       {
739                         sim_io_printf (sd, "[=%s]", o->arg);
740                         len += 2 + strlen (o->arg) + 1;
741                       }
742                     else
743                       {
744                         sim_io_printf (sd, " %s", o->arg);
745                         len += 1 + strlen (o->arg);
746                       }
747                   }
748                 comma = 1;
749               }
750             ++o;
751           }
752         while (OPTION_VALID_P (o) && o->doc == NULL);
753
754         if (len >= indent)
755           {
756             sim_io_printf (sd, "\n%*s", indent, "");
757           }
758         else
759           sim_io_printf (sd, "%*s", indent - len, "");
760
761         /* print the description, word wrap long lines */
762         {
763           const char *chp = opt->doc;
764           unsigned doc_width = 80 - indent;
765           while (strlen (chp) >= doc_width) /* some slack */
766             {
767               const char *end = chp + doc_width - 1;
768               while (end > chp && !isspace (*end))
769                 end --;
770               if (end == chp)
771                 end = chp + doc_width - 1;
772               /* The cast should be ok - its distances between to
773                  points in a string.  */
774               sim_io_printf (sd, "%.*s\n%*s", (int) (end - chp), chp, indent,
775                              "");
776               chp = end;
777               while (isspace (*chp) && *chp != '\0')
778                 chp++;
779             }
780           sim_io_printf (sd, "%s\n", chp);
781         }
782       }
783 }
784
785 /* Print help messages for the options.  */
786
787 void
788 sim_print_help (SIM_DESC sd, int is_command)
789 {
790   if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
791     sim_io_printf (sd, "Usage: %s [options] program [program args]\n",
792                    STATE_MY_NAME (sd));
793
794   /* Initialize duplicate argument checker.  */
795   (void) dup_arg_p (NULL);
796
797   if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
798     sim_io_printf (sd, "Options:\n");
799   else
800     sim_io_printf (sd, "Commands:\n");
801
802   print_help (sd, NULL, STATE_OPTIONS (sd), is_command);
803   sim_io_printf (sd, "\n");
804
805   /* Print cpu-specific options.  */
806   {
807     int i;
808
809     for (i = 0; i < MAX_NR_PROCESSORS; ++i)
810       {
811         sim_cpu *cpu = STATE_CPU (sd, i);
812         if (CPU_OPTIONS (cpu) == NULL)
813           continue;
814         sim_io_printf (sd, "CPU %s specific options:\n", CPU_NAME (cpu));
815         print_help (sd, cpu, CPU_OPTIONS (cpu), is_command);
816         sim_io_printf (sd, "\n");
817       }
818   }
819
820   sim_io_printf (sd, "Note: Depending on the simulator configuration some %ss\n",
821                  STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE ? "option" : "command");
822   sim_io_printf (sd, "      may not be applicable\n");
823
824   if (STATE_OPEN_KIND (sd) == SIM_OPEN_STANDALONE)
825     {
826       sim_io_printf (sd, "\n");
827       sim_io_printf (sd, "program args    Arguments to pass to simulated program.\n");
828       sim_io_printf (sd, "                Note: Very few simulators support this.\n");
829     }
830 }
831
832 /* Utility of sim_args_command to find the closest match for a command.
833    Commands that have "-" in them can be specified as separate words.
834    e.g. sim memory-region 0x800000,0x4000
835    or   sim memory region 0x800000,0x4000
836    If CPU is non-null, use its option table list, otherwise use the main one.
837    *PARGI is where to start looking in ARGV.  It is updated to point past
838    the found option.  */
839
840 static const OPTION *
841 find_match (SIM_DESC sd, sim_cpu *cpu, char *argv[], int *pargi)
842 {
843   const struct option_list *ol;
844   const OPTION *opt;
845   /* most recent option match */
846   const OPTION *matching_opt = NULL;
847   int matching_argi = -1;
848
849   if (cpu)
850     ol = CPU_OPTIONS (cpu);
851   else
852     ol = STATE_OPTIONS (sd);
853
854   /* Skip passed elements specified by *PARGI.  */
855   argv += *pargi;
856
857   for ( ; ol != NULL; ol = ol->next)
858     for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
859       {
860         int argi = 0;
861         const char *name = opt->opt.name;
862         if (name == NULL)
863           continue;
864         while (argv [argi] != NULL
865                && strncmp (name, argv [argi], strlen (argv [argi])) == 0)
866           {
867             name = &name [strlen (argv[argi])];
868             if (name [0] == '-')
869               {
870                 /* leading match ...<a-b-c>-d-e-f - continue search */
871                 name ++; /* skip `-' */
872                 argi ++;
873                 continue;
874               }
875             else if (name [0] == '\0')
876               {
877                 /* exact match ...<a-b-c-d-e-f> - better than before? */
878                 if (argi > matching_argi)
879                   {
880                     matching_argi = argi;
881                     matching_opt = opt;
882                   }
883                 break;
884               }
885             else
886               break;
887           }
888       }
889
890   *pargi = matching_argi;
891   return matching_opt;
892 }
893
894 static char **
895 complete_option_list (char **ret, size_t *cnt, const struct option_list *ol,
896                       const char *text, const char *word)
897 {
898   const OPTION *opt = NULL;
899   int argi;
900   size_t len = strlen (word);
901
902   for ( ; ol != NULL; ol = ol->next)
903     for (opt = ol->options; OPTION_VALID_P (opt); ++opt)
904       {
905         const char *name = opt->opt.name;
906
907         /* A long option to match against?  */
908         if (!name)
909           continue;
910
911         /* Does this option actually match?  */
912         if (strncmp (name, word, len))
913           continue;
914
915         ret = xrealloc (ret, ++*cnt * sizeof (ret[0]));
916         ret[*cnt - 2] = xstrdup (name);
917       }
918
919   return ret;
920 }
921
922 /* All leading text is stored in @text, while the current word being
923    completed is stored in @word.  Trailing text of @word is not.  */
924
925 char **
926 sim_complete_command (SIM_DESC sd, const char *text, const char *word)
927 {
928   char **ret = NULL;
929   size_t cnt = 1;
930   sim_cpu *cpu;
931
932   /* Only complete first word for now.  */
933   if (text != word)
934     return ret;
935
936   cpu = STATE_CPU (sd, 0);
937   if (cpu)
938     ret = complete_option_list (ret, &cnt, CPU_OPTIONS (cpu), text, word);
939   ret = complete_option_list (ret, &cnt, STATE_OPTIONS (sd), text, word);
940
941   if (ret)
942     ret[cnt - 1] = NULL;
943   return ret;
944 }
945
946 SIM_RC
947 sim_args_command (SIM_DESC sd, const char *cmd)
948 {
949   /* something to do? */
950   if (cmd == NULL)
951     return SIM_RC_OK; /* FIXME - perhaps help would be better */
952
953   if (cmd [0] == '-')
954     {
955       /* user specified -<opt> ... form? */
956       char **argv = buildargv (cmd);
957       SIM_RC rc = sim_parse_args (sd, argv);
958       freeargv (argv);
959       return rc;
960     }
961   else
962     {
963       char **argv = buildargv (cmd);
964       const OPTION *matching_opt = NULL;
965       int matching_argi;
966       sim_cpu *cpu;
967
968       if (argv [0] == NULL)
969         {
970           freeargv (argv);
971           return SIM_RC_OK; /* FIXME - perhaps help would be better */
972         }
973
974       /* First check for a cpu selector.  */
975       {
976         char *cpu_name = xstrdup (argv[0]);
977         char *hyphen = strchr (cpu_name, '-');
978         if (hyphen)
979           *hyphen = 0;
980         cpu = sim_cpu_lookup (sd, cpu_name);
981         if (cpu)
982           {
983             /* If <cpuname>-<command>, point argv[0] at <command>.  */
984             if (hyphen)
985               {
986                 matching_argi = 0;
987                 argv[0] += hyphen - cpu_name + 1;
988               }
989             else
990               matching_argi = 1;
991             matching_opt = find_match (sd, cpu, argv, &matching_argi);
992             /* If hyphen found restore argv[0].  */
993             if (hyphen)
994               argv[0] -= hyphen - cpu_name + 1;
995           }
996         free (cpu_name);
997       }
998
999       /* If that failed, try the main table.  */
1000       if (matching_opt == NULL)
1001         {
1002           matching_argi = 0;
1003           matching_opt = find_match (sd, NULL, argv, &matching_argi);
1004         }
1005
1006       if (matching_opt != NULL)
1007         {
1008           switch (matching_opt->opt.has_arg)
1009             {
1010             case no_argument:
1011               if (argv [matching_argi + 1] == NULL)
1012                 matching_opt->handler (sd, cpu, matching_opt->opt.val,
1013                                        NULL, 1/*is_command*/);
1014               else
1015                 sim_io_eprintf (sd, "Command `%s' takes no arguments\n",
1016                                 matching_opt->opt.name);
1017               break;
1018             case optional_argument:
1019               if (argv [matching_argi + 1] == NULL)
1020                 matching_opt->handler (sd, cpu, matching_opt->opt.val,
1021                                        NULL, 1/*is_command*/);
1022               else if (argv [matching_argi + 2] == NULL)
1023                 matching_opt->handler (sd, cpu, matching_opt->opt.val,
1024                                        argv [matching_argi + 1], 1/*is_command*/);
1025               else
1026                 sim_io_eprintf (sd, "Command `%s' requires no more than one argument\n",
1027                                 matching_opt->opt.name);
1028               break;
1029             case required_argument:
1030               if (argv [matching_argi + 1] == NULL)
1031                 sim_io_eprintf (sd, "Command `%s' requires an argument\n",
1032                                 matching_opt->opt.name);
1033               else if (argv [matching_argi + 2] == NULL)
1034                 matching_opt->handler (sd, cpu, matching_opt->opt.val,
1035                                        argv [matching_argi + 1], 1/*is_command*/);
1036               else
1037                 sim_io_eprintf (sd, "Command `%s' requires only one argument\n",
1038                                 matching_opt->opt.name);
1039             }
1040           freeargv (argv);
1041           return SIM_RC_OK;
1042         }
1043
1044       freeargv (argv);
1045     }
1046
1047   /* didn't find anything that remotly matched */
1048   return SIM_RC_FAIL;
1049 }