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