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