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