Home | History | Annotate | Line # | Download | only in compile
compile.c revision 1.7.2.1
      1 /* General Compile and inject code
      2 
      3    Copyright (C) 2014-2023 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      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 "defs.h"
     21 #include "top.h"
     22 #include "ui-out.h"
     23 #include "command.h"
     24 #include "cli/cli-script.h"
     25 #include "cli/cli-utils.h"
     26 #include "cli/cli-option.h"
     27 #include "completer.h"
     28 #include "gdbcmd.h"
     29 #include "compile.h"
     30 #include "compile-internal.h"
     31 #include "compile-object-load.h"
     32 #include "compile-object-run.h"
     33 #include "language.h"
     34 #include "frame.h"
     35 #include "source.h"
     36 #include "block.h"
     37 #include "arch-utils.h"
     38 #include "gdbsupport/filestuff.h"
     39 #include "target.h"
     40 #include "osabi.h"
     41 #include "gdbsupport/gdb_wait.h"
     42 #include "valprint.h"
     43 #include "gdbsupport/gdb_optional.h"
     44 #include "gdbsupport/gdb_unlinker.h"
     45 #include "gdbsupport/pathstuff.h"
     46 #include "gdbsupport/scoped_ignore_signal.h"
     47 #include "gdbsupport/buildargv.h"
     48 
     49 
     50 
     52 /* Initial filename for temporary files.  */
     53 
     54 #define TMP_PREFIX "/tmp/gdbobj-"
     55 
     56 /* Hold "compile" commands.  */
     57 
     58 static struct cmd_list_element *compile_command_list;
     59 
     60 /* Debug flag for "compile" commands.  */
     61 
     62 bool compile_debug;
     63 
     64 /* Object of this type are stored in the compiler's symbol_err_map.  */
     65 
     66 struct symbol_error
     67 {
     68   /* The symbol.  */
     69 
     70   const struct symbol *sym;
     71 
     72   /* The error message to emit.  This is malloc'd and owned by the
     73      hash table.  */
     74 
     75   char *message;
     76 };
     77 
     78 /* Hash a type_map_instance.  */
     79 
     80 static hashval_t
     81 hash_type_map_instance (const void *p)
     82 {
     83   const struct type_map_instance *inst = (const struct type_map_instance *) p;
     84 
     85   return htab_hash_pointer (inst->type);
     86 }
     87 
     88 /* Check two type_map_instance objects for equality.  */
     89 
     90 static int
     91 eq_type_map_instance (const void *a, const void *b)
     92 {
     93   const struct type_map_instance *insta = (const struct type_map_instance *) a;
     94   const struct type_map_instance *instb = (const struct type_map_instance *) b;
     95 
     96   return insta->type == instb->type;
     97 }
     98 
     99 /* Hash function for struct symbol_error.  */
    100 
    101 static hashval_t
    102 hash_symbol_error (const void *a)
    103 {
    104   const struct symbol_error *se = (const struct symbol_error *) a;
    105 
    106   return htab_hash_pointer (se->sym);
    107 }
    108 
    109 /* Equality function for struct symbol_error.  */
    110 
    111 static int
    112 eq_symbol_error (const void *a, const void *b)
    113 {
    114   const struct symbol_error *sea = (const struct symbol_error *) a;
    115   const struct symbol_error *seb = (const struct symbol_error *) b;
    116 
    117   return sea->sym == seb->sym;
    118 }
    119 
    120 /* Deletion function for struct symbol_error.  */
    121 
    122 static void
    123 del_symbol_error (void *a)
    124 {
    125   struct symbol_error *se = (struct symbol_error *) a;
    126 
    127   xfree (se->message);
    128   xfree (se);
    129 }
    130 
    131 /* Constructor for compile_instance.  */
    132 
    133 compile_instance::compile_instance (struct gcc_base_context *gcc_fe,
    134 				    const char *options)
    135   : m_gcc_fe (gcc_fe), m_gcc_target_options (options),
    136     m_type_map (htab_create_alloc (10, hash_type_map_instance,
    137 				   eq_type_map_instance,
    138 				   xfree, xcalloc, xfree)),
    139     m_symbol_err_map (htab_create_alloc (10, hash_symbol_error,
    140 					 eq_symbol_error, del_symbol_error,
    141 					 xcalloc, xfree))
    142 {
    143 }
    144 
    145 /* See compile-internal.h.  */
    146 
    147 bool
    148 compile_instance::get_cached_type (struct type *type, gcc_type *ret) const
    149 {
    150   struct type_map_instance inst, *found;
    151 
    152   inst.type = type;
    153   found = (struct type_map_instance *) htab_find (m_type_map.get (), &inst);
    154   if (found != NULL)
    155     {
    156       *ret = found->gcc_type_handle;
    157       return true;
    158     }
    159 
    160   return false;
    161 }
    162 
    163 /* See compile-internal.h.  */
    164 
    165 void
    166 compile_instance::insert_type (struct type *type, gcc_type gcc_type)
    167 {
    168   struct type_map_instance inst, *add;
    169   void **slot;
    170 
    171   inst.type = type;
    172   inst.gcc_type_handle = gcc_type;
    173   slot = htab_find_slot (m_type_map.get (), &inst, INSERT);
    174 
    175   add = (struct type_map_instance *) *slot;
    176   /* The type might have already been inserted in order to handle
    177      recursive types.  */
    178   if (add != NULL && add->gcc_type_handle != gcc_type)
    179     error (_("Unexpected type id from GCC, check you use recent enough GCC."));
    180 
    181   if (add == NULL)
    182     {
    183       add = XNEW (struct type_map_instance);
    184       *add = inst;
    185       *slot = add;
    186     }
    187 }
    188 
    189 /* See compile-internal.h.  */
    190 
    191 void
    192 compile_instance::insert_symbol_error (const struct symbol *sym,
    193 				       const char *text)
    194 {
    195   struct symbol_error e;
    196   void **slot;
    197 
    198   e.sym = sym;
    199   slot = htab_find_slot (m_symbol_err_map.get (), &e, INSERT);
    200   if (*slot == NULL)
    201     {
    202       struct symbol_error *ep = XNEW (struct symbol_error);
    203 
    204       ep->sym = sym;
    205       ep->message = xstrdup (text);
    206       *slot = ep;
    207     }
    208 }
    209 
    210 /* See compile-internal.h.  */
    211 
    212 void
    213 compile_instance::error_symbol_once (const struct symbol *sym)
    214 {
    215   struct symbol_error search;
    216   struct symbol_error *err;
    217 
    218   if (m_symbol_err_map == NULL)
    219     return;
    220 
    221   search.sym = sym;
    222   err = (struct symbol_error *) htab_find (m_symbol_err_map.get (), &search);
    223   if (err == NULL || err->message == NULL)
    224     return;
    225 
    226   gdb::unique_xmalloc_ptr<char> message (err->message);
    227   err->message = NULL;
    228   error (_("%s"), message.get ());
    229 }
    230 
    231 /* Implement "show debug compile".  */
    232 
    233 static void
    234 show_compile_debug (struct ui_file *file, int from_tty,
    235 		    struct cmd_list_element *c, const char *value)
    236 {
    237   gdb_printf (file, _("Compile debugging is %s.\n"), value);
    238 }
    239 
    240 
    241 
    243 /* Options for the compile command.  */
    244 
    245 struct compile_options
    246 {
    247   /* For -raw.  */
    248   bool raw = false;
    249 };
    250 
    251 using compile_flag_option_def
    252   = gdb::option::flag_option_def<compile_options>;
    253 
    254 static const gdb::option::option_def compile_command_option_defs[] = {
    255 
    256   compile_flag_option_def {
    257     "raw",
    258     [] (compile_options *opts) { return &opts->raw; },
    259     N_("Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
    260   },
    261 
    262 };
    263 
    264 /* Create an option_def_group for the "compile" command's options,
    265    with OPTS as context.  */
    266 
    267 static gdb::option::option_def_group
    268 make_compile_options_def_group (compile_options *opts)
    269 {
    270   return {{compile_command_option_defs}, opts};
    271 }
    272 
    273 /* Handle the input from the 'compile file' command.  The "compile
    274    file" command is used to evaluate an expression contained in a file
    275    that may contain calls to the GCC compiler.  */
    276 
    277 static void
    278 compile_file_command (const char *args, int from_tty)
    279 {
    280   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    281 
    282   /* Check if a -raw option is provided.  */
    283 
    284   compile_options options;
    285 
    286   const gdb::option::option_def_group group
    287     = make_compile_options_def_group (&options);
    288   gdb::option::process_options
    289     (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR,
    290      group);
    291 
    292   enum compile_i_scope_types scope
    293     = options.raw ? COMPILE_I_RAW_SCOPE : COMPILE_I_SIMPLE_SCOPE;
    294 
    295   args = skip_spaces (args);
    296 
    297   /* After processing options, check whether we have a filename.  */
    298   if (args == nullptr || args[0] == '\0')
    299     error (_("You must provide a filename for this command."));
    300 
    301   args = skip_spaces (args);
    302   std::string abspath = gdb_abspath (args);
    303   std::string buffer = string_printf ("#include \"%s\"\n", abspath.c_str ());
    304   eval_compile_command (NULL, buffer.c_str (), scope, NULL);
    305 }
    306 
    307 /* Completer for the "compile file" command.  */
    308 
    309 static void
    310 compile_file_command_completer (struct cmd_list_element *ignore,
    311 				completion_tracker &tracker,
    312 				const char *text, const char *word)
    313 {
    314   const gdb::option::option_def_group group
    315     = make_compile_options_def_group (nullptr);
    316   if (gdb::option::complete_options
    317       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
    318     return;
    319 
    320   word = advance_to_filename_complete_word_point (tracker, text);
    321   filename_completer (ignore, tracker, text, word);
    322 }
    323 
    324 /* Handle the input from the 'compile code' command.  The
    325    "compile code" command is used to evaluate an expression that may
    326    contain calls to the GCC compiler.  The language expected in this
    327    compile command is the language currently set in GDB.  */
    328 
    329 static void
    330 compile_code_command (const char *args, int from_tty)
    331 {
    332   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    333 
    334   compile_options options;
    335 
    336   const gdb::option::option_def_group group
    337     = make_compile_options_def_group (&options);
    338   gdb::option::process_options
    339     (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
    340 
    341   enum compile_i_scope_types scope
    342     = options.raw ? COMPILE_I_RAW_SCOPE : COMPILE_I_SIMPLE_SCOPE;
    343 
    344   if (args && *args)
    345     eval_compile_command (NULL, args, scope, NULL);
    346   else
    347     {
    348       counted_command_line l = get_command_line (compile_control, "");
    349 
    350       l->control_u.compile.scope = scope;
    351       execute_control_command_untraced (l.get ());
    352     }
    353 }
    354 
    355 /* Completer for the "compile code" command.  */
    356 
    357 static void
    358 compile_code_command_completer (struct cmd_list_element *ignore,
    359 				completion_tracker &tracker,
    360 				const char *text, const char *word)
    361 {
    362   const gdb::option::option_def_group group
    363     = make_compile_options_def_group (nullptr);
    364   if (gdb::option::complete_options
    365       (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
    366     return;
    367 
    368   word = advance_to_expression_complete_word_point (tracker, text);
    369   symbol_completer (ignore, tracker, text, word);
    370 }
    371 
    372 /* Callback for compile_print_command.  */
    373 
    374 void
    375 compile_print_value (struct value *val, void *data_voidp)
    376 {
    377   const value_print_options *print_opts = (value_print_options *) data_voidp;
    378 
    379   print_value (val, *print_opts);
    380 }
    381 
    382 /* Handle the input from the 'compile print' command.  The "compile
    383    print" command is used to evaluate and print an expression that may
    384    contain calls to the GCC compiler.  The language expected in this
    385    compile command is the language currently set in GDB.  */
    386 
    387 static void
    388 compile_print_command (const char *arg, int from_tty)
    389 {
    390   enum compile_i_scope_types scope = COMPILE_I_PRINT_ADDRESS_SCOPE;
    391   value_print_options print_opts;
    392 
    393   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    394 
    395   get_user_print_options (&print_opts);
    396   /* Override global settings with explicit options, if any.  */
    397   auto group = make_value_print_options_def_group (&print_opts);
    398   gdb::option::process_options
    399     (&arg, gdb::option::PROCESS_OPTIONS_REQUIRE_DELIMITER, group);
    400 
    401   print_command_parse_format (&arg, "compile print", &print_opts);
    402 
    403   /* Passing &PRINT_OPTS as SCOPE_DATA is safe as do_module_cleanup
    404      will not touch the stale pointer if compile_object_run has
    405      already quit.  */
    406 
    407   if (arg && *arg)
    408     eval_compile_command (NULL, arg, scope, &print_opts);
    409   else
    410     {
    411       counted_command_line l = get_command_line (compile_control, "");
    412 
    413       l->control_u.compile.scope = scope;
    414       l->control_u.compile.scope_data = &print_opts;
    415       execute_control_command_untraced (l.get ());
    416     }
    417 }
    418 
    419 /* A cleanup function to remove a directory and all its contents.  */
    420 
    421 static void
    422 do_rmdir (void *arg)
    423 {
    424   const char *dir = (const char *) arg;
    425   char *zap;
    426   int wstat;
    427 
    428   gdb_assert (startswith (dir, TMP_PREFIX));
    429   zap = concat ("rm -rf ", dir, (char *) NULL);
    430   wstat = system (zap);
    431   if (wstat == -1 || !WIFEXITED (wstat) || WEXITSTATUS (wstat) != 0)
    432     warning (_("Could not remove temporary directory %s"), dir);
    433   XDELETEVEC (zap);
    434 }
    435 
    436 /* Return the name of the temporary directory to use for .o files, and
    437    arrange for the directory to be removed at shutdown.  */
    438 
    439 static const char *
    440 get_compile_file_tempdir (void)
    441 {
    442   static char *tempdir_name;
    443 
    444 #define TEMPLATE TMP_PREFIX "XXXXXX"
    445   char tname[sizeof (TEMPLATE)];
    446 
    447   if (tempdir_name != NULL)
    448     return tempdir_name;
    449 
    450   strcpy (tname, TEMPLATE);
    451 #undef TEMPLATE
    452   tempdir_name = mkdtemp (tname);
    453   if (tempdir_name == NULL)
    454     perror_with_name (_("Could not make temporary directory"));
    455 
    456   tempdir_name = xstrdup (tempdir_name);
    457   make_final_cleanup (do_rmdir, tempdir_name);
    458   return tempdir_name;
    459 }
    460 
    461 /* Compute the names of source and object files to use.  */
    462 
    463 static compile_file_names
    464 get_new_file_names ()
    465 {
    466   static int seq;
    467   const char *dir = get_compile_file_tempdir ();
    468 
    469   ++seq;
    470 
    471   return compile_file_names (string_printf ("%s%sout%d.c",
    472 					    dir, SLASH_STRING, seq),
    473 			     string_printf ("%s%sout%d.o",
    474 					    dir, SLASH_STRING, seq));
    475 }
    476 
    477 /* Get the block and PC at which to evaluate an expression.  */
    478 
    479 static const struct block *
    480 get_expr_block_and_pc (CORE_ADDR *pc)
    481 {
    482   const struct block *block = get_selected_block (pc);
    483 
    484   if (block == NULL)
    485     {
    486       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
    487 
    488       if (cursal.symtab)
    489 	block = cursal.symtab->compunit ()->blockvector ()->static_block ();
    490 
    491       if (block != NULL)
    492 	*pc = block->entry_pc ();
    493     }
    494   else
    495     *pc = block->entry_pc ();
    496 
    497   return block;
    498 }
    499 
    500 /* String for 'set compile-args' and 'show compile-args'.  */
    501 static std::string compile_args =
    502   /* Override flags possibly coming from DW_AT_producer.  */
    503   "-O0 -gdwarf-4"
    504   /* We use -fPIE Otherwise GDB would need to reserve space large enough for
    505      any object file in the inferior in advance to get the final address when
    506      to link the object file to and additionally the default system linker
    507      script would need to be modified so that one can specify there the
    508      absolute target address.
    509      -fPIC is not used at is would require from GDB to generate .got.  */
    510   " -fPIE"
    511   /* We want warnings, except for some commonly happening for GDB commands.  */
    512   " -Wall "
    513   " -Wno-unused-but-set-variable"
    514   " -Wno-unused-variable"
    515   /* Override CU's possible -fstack-protector-strong.  */
    516   " -fno-stack-protector";
    517 
    518 /* Parsed form of COMPILE_ARGS.  */
    519 static gdb_argv compile_args_argv;
    520 
    521 /* Implement 'set compile-args'.  */
    522 
    523 static void
    524 set_compile_args (const char *args, int from_tty, struct cmd_list_element *c)
    525 {
    526   compile_args_argv = gdb_argv (compile_args.c_str ());
    527 }
    528 
    529 /* Implement 'show compile-args'.  */
    530 
    531 static void
    532 show_compile_args (struct ui_file *file, int from_tty,
    533 		   struct cmd_list_element *c, const char *value)
    534 {
    535   gdb_printf (file, _("Compile command command-line arguments "
    536 		      "are \"%s\".\n"),
    537 	      value);
    538 }
    539 
    540 /* String for 'set compile-gcc' and 'show compile-gcc'.  */
    541 static std::string compile_gcc;
    542 
    543 /* Implement 'show compile-gcc'.  */
    544 
    545 static void
    546 show_compile_gcc (struct ui_file *file, int from_tty,
    547 		  struct cmd_list_element *c, const char *value)
    548 {
    549   gdb_printf (file, _("Compile command GCC driver filename is \"%s\".\n"),
    550 	      value);
    551 }
    552 
    553 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
    554    Return NULL otherwise.
    555 
    556    GCC already filters its command-line arguments only for the suitable ones to
    557    put into DW_AT_producer - see GCC function gen_producer_string.  */
    558 
    559 static const char *
    560 get_selected_pc_producer_options (void)
    561 {
    562   CORE_ADDR pc = get_frame_pc (get_selected_frame (NULL));
    563   struct compunit_symtab *symtab = find_pc_compunit_symtab (pc);
    564   const char *cs;
    565 
    566   if (symtab == NULL || symtab->producer () == NULL
    567       || !startswith (symtab->producer (), "GNU "))
    568     return NULL;
    569 
    570   cs = symtab->producer ();
    571   while (*cs != 0 && *cs != '-')
    572     cs = skip_spaces (skip_to_space (cs));
    573   if (*cs != '-')
    574     return NULL;
    575   return cs;
    576 }
    577 
    578 /* Filter out unwanted options from ARGV.  */
    579 
    580 static void
    581 filter_args (char **argv)
    582 {
    583   char **destv;
    584 
    585   for (destv = argv; *argv != NULL; argv++)
    586     {
    587       /* -fpreprocessed may get in commonly from ccache.  */
    588       if (strcmp (*argv, "-fpreprocessed") == 0)
    589 	{
    590 	  xfree (*argv);
    591 	  continue;
    592 	}
    593       *destv++ = *argv;
    594     }
    595   *destv = NULL;
    596 }
    597 
    598 /* Produce final vector of GCC compilation options.
    599 
    600    The first element of the combined argument vector are arguments
    601    relating to the target size ("-m64", "-m32" etc.).  These are
    602    sourced from the inferior's architecture.
    603 
    604    The second element of the combined argument vector are arguments
    605    stored in the inferior DW_AT_producer section.  If these are stored
    606    in the inferior (there is no guarantee that they are), they are
    607    added to the vector.
    608 
    609    The third element of the combined argument vector are argument
    610    supplied by the language implementation provided by
    611    compile-{lang}-support.  These contain language specific arguments.
    612 
    613    The final element of the combined argument vector are arguments
    614    supplied by the "set compile-args" command.  These are always
    615    appended last so as to override any of the arguments automatically
    616    generated above.  */
    617 
    618 static gdb_argv
    619 get_args (const compile_instance *compiler, struct gdbarch *gdbarch)
    620 {
    621   const char *cs_producer_options;
    622   gdb_argv result;
    623 
    624   std::string gcc_options = gdbarch_gcc_target_options (gdbarch);
    625 
    626   /* Make sure we have a non-empty set of options, otherwise GCC will
    627      error out trying to look for a filename that is an empty string.  */
    628   if (!gcc_options.empty ())
    629     result = gdb_argv (gcc_options.c_str ());
    630 
    631   cs_producer_options = get_selected_pc_producer_options ();
    632   if (cs_producer_options != NULL)
    633     {
    634       gdb_argv argv_producer (cs_producer_options);
    635       filter_args (argv_producer.get ());
    636 
    637       result.append (std::move (argv_producer));
    638     }
    639 
    640   result.append (gdb_argv (compiler->gcc_target_options ().c_str ()));
    641   result.append (compile_args_argv);
    642 
    643   return result;
    644 }
    645 
    646 /* A helper function suitable for use as the "print_callback" in the
    647    compiler object.  */
    648 
    649 static void
    650 print_callback (void *ignore, const char *message)
    651 {
    652   gdb_puts (message, gdb_stderr);
    653 }
    654 
    655 /* Process the compilation request.  On success it returns the object
    656    and source file names.  On an error condition, error () is
    657    called.  */
    658 
    659 static compile_file_names
    660 compile_to_object (struct command_line *cmd, const char *cmd_string,
    661 		   enum compile_i_scope_types scope)
    662 {
    663   const struct block *expr_block;
    664   CORE_ADDR trash_pc, expr_pc;
    665   int ok;
    666   struct gdbarch *gdbarch = get_current_arch ();
    667   std::string triplet_rx;
    668 
    669   if (!target_has_execution ())
    670     error (_("The program must be running for the compile command to "\
    671 	     "work."));
    672 
    673   expr_block = get_expr_block_and_pc (&trash_pc);
    674   expr_pc = get_frame_address_in_block (get_selected_frame (NULL));
    675 
    676   /* Set up instance and context for the compiler.  */
    677   std::unique_ptr<compile_instance> compiler
    678     = current_language->get_compile_instance ();
    679   if (compiler == nullptr)
    680     error (_("No compiler support for language %s."),
    681 	   current_language->name ());
    682   compiler->set_print_callback (print_callback, NULL);
    683   compiler->set_scope (scope);
    684   compiler->set_block (expr_block);
    685 
    686   /* From the provided expression, build a scope to pass to the
    687      compiler.  */
    688 
    689   string_file input_buf;
    690   const char *input;
    691 
    692   if (cmd != NULL)
    693     {
    694       struct command_line *iter;
    695 
    696       for (iter = cmd->body_list_0.get (); iter; iter = iter->next)
    697 	{
    698 	  input_buf.puts (iter->line);
    699 	  input_buf.puts ("\n");
    700 	}
    701 
    702       input = input_buf.c_str ();
    703     }
    704   else if (cmd_string != NULL)
    705     input = cmd_string;
    706   else
    707     error (_("Neither a simple expression, or a multi-line specified."));
    708 
    709   std::string code
    710     = current_language->compute_program (compiler.get (), input, gdbarch,
    711 					 expr_block, expr_pc);
    712   if (compile_debug)
    713     gdb_printf (gdb_stdlog, "debug output:\n\n%s", code.c_str ());
    714 
    715   compiler->set_verbose (compile_debug);
    716 
    717   if (!compile_gcc.empty ())
    718     {
    719       if (compiler->version () < GCC_FE_VERSION_1)
    720 	error (_("Command 'set compile-gcc' requires GCC version 6 or higher "
    721 		 "(libcc1 interface version 1 or higher)"));
    722 
    723       compiler->set_driver_filename (compile_gcc.c_str ());
    724     }
    725   else
    726     {
    727       const char *os_rx = osabi_triplet_regexp (gdbarch_osabi (gdbarch));
    728       const char *arch_rx = gdbarch_gnu_triplet_regexp (gdbarch);
    729 
    730       /* Allow triplets with or without vendor set.  */
    731       triplet_rx = std::string (arch_rx) + "(-[^-]*)?-";
    732       if (os_rx != nullptr)
    733 	triplet_rx += os_rx;
    734       compiler->set_triplet_regexp (triplet_rx.c_str ());
    735     }
    736 
    737   /* Set compiler command-line arguments.  */
    738   gdb_argv argv_holder = get_args (compiler.get (), gdbarch);
    739   int argc = argv_holder.count ();
    740   char **argv = argv_holder.get ();
    741 
    742   gdb::unique_xmalloc_ptr<char> error_message
    743     = compiler->set_arguments (argc, argv, triplet_rx.c_str ());
    744 
    745   if (error_message != NULL)
    746     error ("%s", error_message.get ());
    747 
    748   if (compile_debug)
    749     {
    750       int argi;
    751 
    752       gdb_printf (gdb_stdlog, "Passing %d compiler options:\n", argc);
    753       for (argi = 0; argi < argc; argi++)
    754 	gdb_printf (gdb_stdlog, "Compiler option %d: <%s>\n",
    755 		    argi, argv[argi]);
    756     }
    757 
    758   compile_file_names fnames = get_new_file_names ();
    759 
    760   gdb::optional<gdb::unlinker> source_remover;
    761 
    762   {
    763     gdb_file_up src = gdb_fopen_cloexec (fnames.source_file (), "w");
    764     if (src == NULL)
    765       perror_with_name (_("Could not open source file for writing"));
    766 
    767     source_remover.emplace (fnames.source_file ());
    768 
    769     if (fputs (code.c_str (), src.get ()) == EOF)
    770       perror_with_name (_("Could not write to source file"));
    771   }
    772 
    773   if (compile_debug)
    774     gdb_printf (gdb_stdlog, "source file produced: %s\n\n",
    775 		fnames.source_file ());
    776 
    777   /* If we don't do this, then GDB simply exits
    778      when the compiler dies.  */
    779   scoped_ignore_sigpipe ignore_sigpipe;
    780 
    781   /* Call the compiler and start the compilation process.  */
    782   compiler->set_source_file (fnames.source_file ());
    783   ok = compiler->compile (fnames.object_file (), compile_debug);
    784   if (!ok)
    785     error (_("Compilation failed."));
    786 
    787   if (compile_debug)
    788     gdb_printf (gdb_stdlog, "object file produced: %s\n\n",
    789 		fnames.object_file ());
    790 
    791   /* Keep the source file.  */
    792   source_remover->keep ();
    793   return fnames;
    794 }
    795 
    796 /* The "compile" prefix command.  */
    797 
    798 static void
    799 compile_command (const char *args, int from_tty)
    800 {
    801   /* If a sub-command is not specified to the compile prefix command,
    802      assume it is a direct code compilation.  */
    803   compile_code_command (args, from_tty);
    804 }
    805 
    806 /* See compile.h.  */
    807 
    808 void
    809 eval_compile_command (struct command_line *cmd, const char *cmd_string,
    810 		      enum compile_i_scope_types scope, void *scope_data)
    811 {
    812   compile_file_names fnames = compile_to_object (cmd, cmd_string, scope);
    813 
    814   gdb::unlinker object_remover (fnames.object_file ());
    815   gdb::unlinker source_remover (fnames.source_file ());
    816 
    817   compile_module_up compile_module = compile_object_load (fnames, scope,
    818 							  scope_data);
    819   if (compile_module == NULL)
    820     {
    821       gdb_assert (scope == COMPILE_I_PRINT_ADDRESS_SCOPE);
    822       eval_compile_command (cmd, cmd_string,
    823 			    COMPILE_I_PRINT_VALUE_SCOPE, scope_data);
    824       return;
    825     }
    826 
    827   /* Keep the files.  */
    828   source_remover.keep ();
    829   object_remover.keep ();
    830 
    831   compile_object_run (std::move (compile_module));
    832 }
    833 
    834 /* See compile/compile-internal.h.  */
    835 
    836 std::string
    837 compile_register_name_mangled (struct gdbarch *gdbarch, int regnum)
    838 {
    839   const char *regname = gdbarch_register_name (gdbarch, regnum);
    840 
    841   return string_printf ("__%s", regname);
    842 }
    843 
    844 /* See compile/compile-internal.h.  */
    845 
    846 int
    847 compile_register_name_demangle (struct gdbarch *gdbarch,
    848 				 const char *regname)
    849 {
    850   int regnum;
    851 
    852   if (regname[0] != '_' || regname[1] != '_')
    853     error (_("Invalid register name \"%s\"."), regname);
    854   regname += 2;
    855 
    856   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
    857     if (strcmp (regname, gdbarch_register_name (gdbarch, regnum)) == 0)
    858       return regnum;
    859 
    860   error (_("Cannot find gdbarch register \"%s\"."), regname);
    861 }
    862 
    863 /* Forwards to the plug-in.  */
    864 
    865 #define FORWARD(OP,...) (m_gcc_fe->ops->OP (m_gcc_fe, ##__VA_ARGS__))
    866 
    867 /* See compile-internal.h.  */
    868 
    869 void
    870 compile_instance::set_print_callback
    871   (void (*print_function) (void *, const char *), void *datum)
    872 {
    873   FORWARD (set_print_callback, print_function, datum);
    874 }
    875 
    876 /* See compile-internal.h.  */
    877 
    878 unsigned int
    879 compile_instance::version () const
    880 {
    881   return m_gcc_fe->ops->version;
    882 }
    883 
    884 /* See compile-internal.h.  */
    885 
    886 void
    887 compile_instance::set_verbose (int level)
    888 {
    889   if (version () >= GCC_FE_VERSION_1)
    890     FORWARD (set_verbose, level);
    891 }
    892 
    893 /* See compile-internal.h.  */
    894 
    895 void
    896 compile_instance::set_driver_filename (const char *filename)
    897 {
    898   if (version () >= GCC_FE_VERSION_1)
    899     FORWARD (set_driver_filename, filename);
    900 }
    901 
    902 /* See compile-internal.h.  */
    903 
    904 void
    905 compile_instance::set_triplet_regexp (const char *regexp)
    906 {
    907   if (version () >= GCC_FE_VERSION_1)
    908     FORWARD (set_triplet_regexp, regexp);
    909 }
    910 
    911 /* See compile-internal.h.  */
    912 
    913 gdb::unique_xmalloc_ptr<char>
    914 compile_instance::set_arguments (int argc, char **argv, const char *regexp)
    915 {
    916   if (version () >= GCC_FE_VERSION_1)
    917     return gdb::unique_xmalloc_ptr<char> (FORWARD (set_arguments, argc, argv));
    918   else
    919     return gdb::unique_xmalloc_ptr<char> (FORWARD (set_arguments_v0, regexp,
    920 						   argc, argv));
    921 }
    922 
    923 /* See compile-internal.h.  */
    924 
    925 void
    926 compile_instance::set_source_file (const char *filename)
    927 {
    928   FORWARD (set_source_file, filename);
    929 }
    930 
    931 /* See compile-internal.h.  */
    932 
    933 bool
    934 compile_instance::compile (const char *filename, int verbose_level)
    935 {
    936   if (version () >= GCC_FE_VERSION_1)
    937     return FORWARD (compile, filename);
    938   else
    939     return FORWARD (compile_v0, filename, verbose_level);
    940 }
    941 
    942 #undef FORWARD
    943 
    944 /* See compile.h.  */
    945 cmd_list_element *compile_cmd_element = nullptr;
    946 
    947 void _initialize_compile ();
    948 void
    949 _initialize_compile ()
    950 {
    951   struct cmd_list_element *c = NULL;
    952 
    953   compile_cmd_element = add_prefix_cmd ("compile", class_obscure,
    954 					compile_command, _("\
    955 Command to compile source code and inject it into the inferior."),
    956 		  &compile_command_list, 1, &cmdlist);
    957   add_com_alias ("expression", compile_cmd_element, class_obscure, 0);
    958 
    959   const auto compile_opts = make_compile_options_def_group (nullptr);
    960 
    961   static const std::string compile_code_help
    962     = gdb::option::build_help (_("\
    963 Compile, inject, and execute code.\n\
    964 \n\
    965 Usage: compile code [OPTION]... [CODE]\n\
    966 \n\
    967 Options:\n\
    968 %OPTIONS%\n\
    969 \n\
    970 The source code may be specified as a simple one line expression, e.g.:\n\
    971 \n\
    972     compile code printf(\"Hello world\\n\");\n\
    973 \n\
    974 Alternatively, you can type a multiline expression by invoking\n\
    975 this command with no argument.  GDB will then prompt for the\n\
    976 expression interactively; type a line containing \"end\" to\n\
    977 indicate the end of the expression."),
    978 			       compile_opts);
    979 
    980   c = add_cmd ("code", class_obscure, compile_code_command,
    981 	       compile_code_help.c_str (),
    982 	       &compile_command_list);
    983   set_cmd_completer_handle_brkchars (c, compile_code_command_completer);
    984 
    985 static const std::string compile_file_help
    986     = gdb::option::build_help (_("\
    987 Evaluate a file containing source code.\n\
    988 \n\
    989 Usage: compile file [OPTION].. [FILENAME]\n\
    990 \n\
    991 Options:\n\
    992 %OPTIONS%"),
    993 			       compile_opts);
    994 
    995   c = add_cmd ("file", class_obscure, compile_file_command,
    996 	       compile_file_help.c_str (),
    997 	       &compile_command_list);
    998   set_cmd_completer_handle_brkchars (c, compile_file_command_completer);
    999 
   1000   const auto compile_print_opts = make_value_print_options_def_group (nullptr);
   1001 
   1002   static const std::string compile_print_help
   1003     = gdb::option::build_help (_("\
   1004 Evaluate EXPR by using the compiler and print result.\n\
   1005 \n\
   1006 Usage: compile print [[OPTION]... --] [/FMT] [EXPR]\n\
   1007 \n\
   1008 Options:\n\
   1009 %OPTIONS%\n\
   1010 \n\
   1011 Note: because this command accepts arbitrary expressions, if you\n\
   1012 specify any command option, you must use a double dash (\"--\")\n\
   1013 to mark the end of option processing.  E.g.: \"compile print -o -- myobj\".\n\
   1014 \n\
   1015 The expression may be specified on the same line as the command, e.g.:\n\
   1016 \n\
   1017     compile print i\n\
   1018 \n\
   1019 Alternatively, you can type a multiline expression by invoking\n\
   1020 this command with no argument.  GDB will then prompt for the\n\
   1021 expression interactively; type a line containing \"end\" to\n\
   1022 indicate the end of the expression.\n\
   1023 \n\
   1024 EXPR may be preceded with /FMT, where FMT is a format letter\n\
   1025 but no count or size letter (see \"x\" command)."),
   1026 			       compile_print_opts);
   1027 
   1028   c = add_cmd ("print", class_obscure, compile_print_command,
   1029 	       compile_print_help.c_str (),
   1030 	       &compile_command_list);
   1031   set_cmd_completer_handle_brkchars (c, print_command_completer);
   1032 
   1033   add_setshow_boolean_cmd ("compile", class_maintenance, &compile_debug, _("\
   1034 Set compile command debugging."), _("\
   1035 Show compile command debugging."), _("\
   1036 When on, compile command debugging is enabled."),
   1037 			   NULL, show_compile_debug,
   1038 			   &setdebuglist, &showdebuglist);
   1039 
   1040   add_setshow_string_cmd ("compile-args", class_support,
   1041 			  &compile_args,
   1042 			  _("Set compile command GCC command-line arguments."),
   1043 			  _("Show compile command GCC command-line arguments."),
   1044 			  _("\
   1045 Use options like -I (include file directory) or ABI settings.\n\
   1046 String quoting is parsed like in shell, for example:\n\
   1047   -mno-align-double \"-I/dir with a space/include\""),
   1048 			  set_compile_args, show_compile_args, &setlist, &showlist);
   1049 
   1050 
   1051   /* Initialize compile_args_argv.  */
   1052   set_compile_args (compile_args.c_str (), 0, NULL);
   1053 
   1054   add_setshow_optional_filename_cmd ("compile-gcc", class_support,
   1055 				     &compile_gcc,
   1056 				     _("Set compile command "
   1057 				       "GCC driver filename."),
   1058 				     _("Show compile command "
   1059 				       "GCC driver filename."),
   1060 				     _("\
   1061 It should be absolute filename of the gcc executable.\n\
   1062 If empty the default target triplet will be searched in $PATH."),
   1063 				     NULL, show_compile_gcc, &setlist,
   1064 				     &showlist);
   1065 }
   1066