compile.c revision 1.7 1 /* General Compile and inject code
2
3 Copyright (C) 2014-2020 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
47
48
50 /* Initial filename for temporary files. */
51
52 #define TMP_PREFIX "/tmp/gdbobj-"
53
54 /* Hold "compile" commands. */
55
56 static struct cmd_list_element *compile_command_list;
57
58 /* Debug flag for "compile" commands. */
59
60 bool compile_debug;
61
62 /* Object of this type are stored in the compiler's symbol_err_map. */
63
64 struct symbol_error
65 {
66 /* The symbol. */
67
68 const struct symbol *sym;
69
70 /* The error message to emit. This is malloc'd and owned by the
71 hash table. */
72
73 char *message;
74 };
75
76 /* Hash a type_map_instance. */
77
78 static hashval_t
79 hash_type_map_instance (const void *p)
80 {
81 const struct type_map_instance *inst = (const struct type_map_instance *) p;
82
83 return htab_hash_pointer (inst->type);
84 }
85
86 /* Check two type_map_instance objects for equality. */
87
88 static int
89 eq_type_map_instance (const void *a, const void *b)
90 {
91 const struct type_map_instance *insta = (const struct type_map_instance *) a;
92 const struct type_map_instance *instb = (const struct type_map_instance *) b;
93
94 return insta->type == instb->type;
95 }
96
97 /* Hash function for struct symbol_error. */
98
99 static hashval_t
100 hash_symbol_error (const void *a)
101 {
102 const struct symbol_error *se = (const struct symbol_error *) a;
103
104 return htab_hash_pointer (se->sym);
105 }
106
107 /* Equality function for struct symbol_error. */
108
109 static int
110 eq_symbol_error (const void *a, const void *b)
111 {
112 const struct symbol_error *sea = (const struct symbol_error *) a;
113 const struct symbol_error *seb = (const struct symbol_error *) b;
114
115 return sea->sym == seb->sym;
116 }
117
118 /* Deletion function for struct symbol_error. */
119
120 static void
121 del_symbol_error (void *a)
122 {
123 struct symbol_error *se = (struct symbol_error *) a;
124
125 xfree (se->message);
126 xfree (se);
127 }
128
129 /* Constructor for compile_instance. */
130
131 compile_instance::compile_instance (struct gcc_base_context *gcc_fe,
132 const char *options)
133 : m_gcc_fe (gcc_fe), m_gcc_target_options (options),
134 m_type_map (htab_create_alloc (10, hash_type_map_instance,
135 eq_type_map_instance,
136 xfree, xcalloc, xfree)),
137 m_symbol_err_map (htab_create_alloc (10, hash_symbol_error,
138 eq_symbol_error, del_symbol_error,
139 xcalloc, xfree))
140 {
141 }
142
143 /* See compile-internal.h. */
144
145 bool
146 compile_instance::get_cached_type (struct type *type, gcc_type *ret) const
147 {
148 struct type_map_instance inst, *found;
149
150 inst.type = type;
151 found = (struct type_map_instance *) htab_find (m_type_map.get (), &inst);
152 if (found != NULL)
153 {
154 *ret = found->gcc_type_handle;
155 return true;
156 }
157
158 return false;
159 }
160
161 /* See compile-internal.h. */
162
163 void
164 compile_instance::insert_type (struct type *type, gcc_type gcc_type)
165 {
166 struct type_map_instance inst, *add;
167 void **slot;
168
169 inst.type = type;
170 inst.gcc_type_handle = gcc_type;
171 slot = htab_find_slot (m_type_map.get (), &inst, INSERT);
172
173 add = (struct type_map_instance *) *slot;
174 /* The type might have already been inserted in order to handle
175 recursive types. */
176 if (add != NULL && add->gcc_type_handle != gcc_type)
177 error (_("Unexpected type id from GCC, check you use recent enough GCC."));
178
179 if (add == NULL)
180 {
181 add = XNEW (struct type_map_instance);
182 *add = inst;
183 *slot = add;
184 }
185 }
186
187 /* See compile-internal.h. */
188
189 void
190 compile_instance::insert_symbol_error (const struct symbol *sym,
191 const char *text)
192 {
193 struct symbol_error e;
194 void **slot;
195
196 e.sym = sym;
197 slot = htab_find_slot (m_symbol_err_map.get (), &e, INSERT);
198 if (*slot == NULL)
199 {
200 struct symbol_error *ep = XNEW (struct symbol_error);
201
202 ep->sym = sym;
203 ep->message = xstrdup (text);
204 *slot = ep;
205 }
206 }
207
208 /* See compile-internal.h. */
209
210 void
211 compile_instance::error_symbol_once (const struct symbol *sym)
212 {
213 struct symbol_error search;
214 struct symbol_error *err;
215
216 if (m_symbol_err_map == NULL)
217 return;
218
219 search.sym = sym;
220 err = (struct symbol_error *) htab_find (m_symbol_err_map.get (), &search);
221 if (err == NULL || err->message == NULL)
222 return;
223
224 gdb::unique_xmalloc_ptr<char> message (err->message);
225 err->message = NULL;
226 error (_("%s"), message.get ());
227 }
228
229 /* Implement "show debug compile". */
230
231 static void
232 show_compile_debug (struct ui_file *file, int from_tty,
233 struct cmd_list_element *c, const char *value)
234 {
235 fprintf_filtered (file, _("Compile debugging is %s.\n"), value);
236 }
237
238
239
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 (¤t_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 gdb::unique_xmalloc_ptr<char> abspath = gdb_abspath (args);
301 std::string buffer = string_printf ("#include \"%s\"\n", abspath.get ());
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 (¤t_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 (¤t_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 = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal.symtab),
488 STATIC_BLOCK);
489 if (block != NULL)
490 *pc = BLOCK_ENTRY_PC (block);
491 }
492 else
493 *pc = BLOCK_ENTRY_PC (block);
494
495 return block;
496 }
497
498 /* Call buildargv (via gdb_argv), set its result for S into *ARGVP but
499 calculate also the number of parsed arguments into *ARGCP. If
500 buildargv has returned NULL then *ARGCP is set to zero. */
501
502 static void
503 build_argc_argv (const char *s, int *argcp, char ***argvp)
504 {
505 gdb_argv args (s);
506
507 *argcp = args.count ();
508 *argvp = args.release ();
509 }
510
511 /* String for 'set compile-args' and 'show compile-args'. */
512 static char *compile_args;
513
514 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
515 static int compile_args_argc;
516 static char **compile_args_argv;
517
518 /* Implement 'set compile-args'. */
519
520 static void
521 set_compile_args (const char *args, int from_tty, struct cmd_list_element *c)
522 {
523 freeargv (compile_args_argv);
524 build_argc_argv (compile_args, &compile_args_argc, &compile_args_argv);
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 fprintf_filtered (file, _("Compile command command-line arguments "
534 "are \"%s\".\n"),
535 value);
536 }
537
538 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
539 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
540
541 static void
542 append_args (int *argcp, char ***argvp, int argc, char **argv)
543 {
544 int argi;
545
546 *argvp = XRESIZEVEC (char *, *argvp, (*argcp + argc + 1));
547
548 for (argi = 0; argi < argc; argi++)
549 (*argvp)[(*argcp)++] = xstrdup (argv[argi]);
550 (*argvp)[(*argcp)] = NULL;
551 }
552
553 /* String for 'set compile-gcc' and 'show compile-gcc'. */
554 static char *compile_gcc;
555
556 /* Implement 'show compile-gcc'. */
557
558 static void
559 show_compile_gcc (struct ui_file *file, int from_tty,
560 struct cmd_list_element *c, const char *value)
561 {
562 fprintf_filtered (file, _("Compile command GCC driver filename is \"%s\".\n"),
563 value);
564 }
565
566 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
567 Return NULL otherwise.
568
569 GCC already filters its command-line arguments only for the suitable ones to
570 put into DW_AT_producer - see GCC function gen_producer_string. */
571
572 static const char *
573 get_selected_pc_producer_options (void)
574 {
575 CORE_ADDR pc = get_frame_pc (get_selected_frame (NULL));
576 struct compunit_symtab *symtab = find_pc_compunit_symtab (pc);
577 const char *cs;
578
579 if (symtab == NULL || symtab->producer == NULL
580 || !startswith (symtab->producer, "GNU "))
581 return NULL;
582
583 cs = symtab->producer;
584 while (*cs != 0 && *cs != '-')
585 cs = skip_spaces (skip_to_space (cs));
586 if (*cs != '-')
587 return NULL;
588 return cs;
589 }
590
591 /* Filter out unwanted options from *ARGCP and ARGV. */
592
593 static void
594 filter_args (int *argcp, char **argv)
595 {
596 char **destv;
597
598 for (destv = argv; *argv != NULL; argv++)
599 {
600 /* -fpreprocessed may get in commonly from ccache. */
601 if (strcmp (*argv, "-fpreprocessed") == 0)
602 {
603 xfree (*argv);
604 (*argcp)--;
605 continue;
606 }
607 *destv++ = *argv;
608 }
609 *destv = NULL;
610 }
611
612 /* Produce final vector of GCC compilation options.
613
614 The first element of the combined argument vector are arguments
615 relating to the target size ("-m64", "-m32" etc.). These are
616 sourced from the inferior's architecture.
617
618 The second element of the combined argument vector are arguments
619 stored in the inferior DW_AT_producer section. If these are stored
620 in the inferior (there is no guarantee that they are), they are
621 added to the vector.
622
623 The third element of the combined argument vector are argument
624 supplied by the language implementation provided by
625 compile-{lang}-support. These contain language specific arguments.
626
627 The final element of the combined argument vector are arguments
628 supplied by the "set compile-args" command. These are always
629 appended last so as to override any of the arguments automatically
630 generated above. */
631
632 static void
633 get_args (const compile_instance *compiler, struct gdbarch *gdbarch,
634 int *argcp, char ***argvp)
635 {
636 const char *cs_producer_options;
637 int argc_compiler;
638 char **argv_compiler;
639
640 build_argc_argv (gdbarch_gcc_target_options (gdbarch).c_str (),
641 argcp, argvp);
642
643 cs_producer_options = get_selected_pc_producer_options ();
644 if (cs_producer_options != NULL)
645 {
646 int argc_producer;
647 char **argv_producer;
648
649 build_argc_argv (cs_producer_options, &argc_producer, &argv_producer);
650 filter_args (&argc_producer, argv_producer);
651 append_args (argcp, argvp, argc_producer, argv_producer);
652 freeargv (argv_producer);
653 }
654
655 build_argc_argv (compiler->gcc_target_options ().c_str (),
656 &argc_compiler, &argv_compiler);
657 append_args (argcp, argvp, argc_compiler, argv_compiler);
658 freeargv (argv_compiler);
659
660 append_args (argcp, argvp, compile_args_argc, compile_args_argv);
661 }
662
663 /* A helper function suitable for use as the "print_callback" in the
664 compiler object. */
665
666 static void
667 print_callback (void *ignore, const char *message)
668 {
669 fputs_filtered (message, gdb_stderr);
670 }
671
672 /* Process the compilation request. On success it returns the object
673 and source file names. On an error condition, error () is
674 called. */
675
676 static compile_file_names
677 compile_to_object (struct command_line *cmd, const char *cmd_string,
678 enum compile_i_scope_types scope)
679 {
680 const struct block *expr_block;
681 CORE_ADDR trash_pc, expr_pc;
682 int argc;
683 char **argv;
684 int ok;
685 struct gdbarch *gdbarch = get_current_arch ();
686 std::string triplet_rx;
687
688 if (!target_has_execution)
689 error (_("The program must be running for the compile command to "\
690 "work."));
691
692 expr_block = get_expr_block_and_pc (&trash_pc);
693 expr_pc = get_frame_address_in_block (get_selected_frame (NULL));
694
695 /* Set up instance and context for the compiler. */
696 std::unique_ptr <compile_instance> compiler
697 (current_language->get_compile_instance ());
698 if (compiler == nullptr)
699 error (_("No compiler support for language %s."),
700 current_language->la_name);
701 compiler->set_print_callback (print_callback, NULL);
702 compiler->set_scope (scope);
703 compiler->set_block (expr_block);
704
705 /* From the provided expression, build a scope to pass to the
706 compiler. */
707
708 string_file input_buf;
709 const char *input;
710
711 if (cmd != NULL)
712 {
713 struct command_line *iter;
714
715 for (iter = cmd->body_list_0.get (); iter; iter = iter->next)
716 {
717 input_buf.puts (iter->line);
718 input_buf.puts ("\n");
719 }
720
721 input = input_buf.c_str ();
722 }
723 else if (cmd_string != NULL)
724 input = cmd_string;
725 else
726 error (_("Neither a simple expression, or a multi-line specified."));
727
728 std::string code
729 = current_language->compute_program (compiler.get (), input, gdbarch,
730 expr_block, expr_pc);
731 if (compile_debug)
732 fprintf_unfiltered (gdb_stdlog, "debug output:\n\n%s", code.c_str ());
733
734 compiler->set_verbose (compile_debug);
735
736 if (compile_gcc[0] != 0)
737 {
738 if (compiler->version () < GCC_FE_VERSION_1)
739 error (_("Command 'set compile-gcc' requires GCC version 6 or higher "
740 "(libcc1 interface version 1 or higher)"));
741
742 compiler->set_driver_filename (compile_gcc);
743 }
744 else
745 {
746 const char *os_rx = osabi_triplet_regexp (gdbarch_osabi (gdbarch));
747 const char *arch_rx = gdbarch_gnu_triplet_regexp (gdbarch);
748
749 /* Allow triplets with or without vendor set. */
750 triplet_rx = std::string (arch_rx) + "(-[^-]*)?-" + os_rx;
751 compiler->set_triplet_regexp (triplet_rx.c_str ());
752 }
753
754 /* Set compiler command-line arguments. */
755 get_args (compiler.get (), gdbarch, &argc, &argv);
756 gdb_argv argv_holder (argv);
757
758 gdb::unique_xmalloc_ptr<char> error_message;
759 error_message.reset (compiler->set_arguments (argc, argv,
760 triplet_rx.c_str ()));
761
762 if (error_message != NULL)
763 error ("%s", error_message.get ());
764
765 if (compile_debug)
766 {
767 int argi;
768
769 fprintf_unfiltered (gdb_stdlog, "Passing %d compiler options:\n", argc);
770 for (argi = 0; argi < argc; argi++)
771 fprintf_unfiltered (gdb_stdlog, "Compiler option %d: <%s>\n",
772 argi, argv[argi]);
773 }
774
775 compile_file_names fnames = get_new_file_names ();
776
777 gdb::optional<gdb::unlinker> source_remover;
778
779 {
780 gdb_file_up src = gdb_fopen_cloexec (fnames.source_file (), "w");
781 if (src == NULL)
782 perror_with_name (_("Could not open source file for writing"));
783
784 source_remover.emplace (fnames.source_file ());
785
786 if (fputs (code.c_str (), src.get ()) == EOF)
787 perror_with_name (_("Could not write to source file"));
788 }
789
790 if (compile_debug)
791 fprintf_unfiltered (gdb_stdlog, "source file produced: %s\n\n",
792 fnames.source_file ());
793
794 /* Call the compiler and start the compilation process. */
795 compiler->set_source_file (fnames.source_file ());
796 ok = compiler->compile (fnames.object_file (), compile_debug);
797 if (!ok)
798 error (_("Compilation failed."));
799
800 if (compile_debug)
801 fprintf_unfiltered (gdb_stdlog, "object file produced: %s\n\n",
802 fnames.object_file ());
803
804 /* Keep the source file. */
805 source_remover->keep ();
806 return fnames;
807 }
808
809 /* The "compile" prefix command. */
810
811 static void
812 compile_command (const char *args, int from_tty)
813 {
814 /* If a sub-command is not specified to the compile prefix command,
815 assume it is a direct code compilation. */
816 compile_code_command (args, from_tty);
817 }
818
819 /* See compile.h. */
820
821 void
822 eval_compile_command (struct command_line *cmd, const char *cmd_string,
823 enum compile_i_scope_types scope, void *scope_data)
824 {
825 struct compile_module *compile_module;
826
827 compile_file_names fnames = compile_to_object (cmd, cmd_string, scope);
828
829 gdb::unlinker object_remover (fnames.object_file ());
830 gdb::unlinker source_remover (fnames.source_file ());
831
832 compile_module = compile_object_load (fnames, scope, scope_data);
833 if (compile_module == NULL)
834 {
835 gdb_assert (scope == COMPILE_I_PRINT_ADDRESS_SCOPE);
836 eval_compile_command (cmd, cmd_string,
837 COMPILE_I_PRINT_VALUE_SCOPE, scope_data);
838 return;
839 }
840
841 /* Keep the files. */
842 source_remover.keep ();
843 object_remover.keep ();
844
845 compile_object_run (compile_module);
846 }
847
848 /* See compile/compile-internal.h. */
849
850 std::string
851 compile_register_name_mangled (struct gdbarch *gdbarch, int regnum)
852 {
853 const char *regname = gdbarch_register_name (gdbarch, regnum);
854
855 return string_printf ("__%s", regname);
856 }
857
858 /* See compile/compile-internal.h. */
859
860 int
861 compile_register_name_demangle (struct gdbarch *gdbarch,
862 const char *regname)
863 {
864 int regnum;
865
866 if (regname[0] != '_' || regname[1] != '_')
867 error (_("Invalid register name \"%s\"."), regname);
868 regname += 2;
869
870 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
871 if (strcmp (regname, gdbarch_register_name (gdbarch, regnum)) == 0)
872 return regnum;
873
874 error (_("Cannot find gdbarch register \"%s\"."), regname);
875 }
876
877 /* Forwards to the plug-in. */
878
879 #define FORWARD(OP,...) (m_gcc_fe->ops->OP (m_gcc_fe, ##__VA_ARGS__))
880
881 /* See compile-internal.h. */
882
883 void
884 compile_instance::set_print_callback
885 (void (*print_function) (void *, const char *), void *datum)
886 {
887 FORWARD (set_print_callback, print_function, datum);
888 }
889
890 /* See compile-internal.h. */
891
892 unsigned int
893 compile_instance::version () const
894 {
895 return m_gcc_fe->ops->version;
896 }
897
898 /* See compile-internal.h. */
899
900 void
901 compile_instance::set_verbose (int level)
902 {
903 if (version () >= GCC_FE_VERSION_1)
904 FORWARD (set_verbose, level);
905 }
906
907 /* See compile-internal.h. */
908
909 void
910 compile_instance::set_driver_filename (const char *filename)
911 {
912 if (version () >= GCC_FE_VERSION_1)
913 FORWARD (set_driver_filename, filename);
914 }
915
916 /* See compile-internal.h. */
917
918 void
919 compile_instance::set_triplet_regexp (const char *regexp)
920 {
921 if (version () >= GCC_FE_VERSION_1)
922 FORWARD (set_triplet_regexp, regexp);
923 }
924
925 /* See compile-internal.h. */
926
927 char *
928 compile_instance::set_arguments (int argc, char **argv, const char *regexp)
929 {
930 if (version () >= GCC_FE_VERSION_1)
931 return FORWARD (set_arguments, argc, argv);
932 else
933 return FORWARD (set_arguments_v0, regexp, argc, argv);
934 }
935
936 /* See compile-internal.h. */
937
938 void
939 compile_instance::set_source_file (const char *filename)
940 {
941 FORWARD (set_source_file, filename);
942 }
943
944 /* See compile-internal.h. */
945
946 bool
947 compile_instance::compile (const char *filename, int verbose_level)
948 {
949 if (version () >= GCC_FE_VERSION_1)
950 return FORWARD (compile, filename);
951 else
952 return FORWARD (compile_v0, filename, verbose_level);
953 }
954
955 #undef FORWARD
956
957 /* See compile.h. */
958 cmd_list_element *compile_cmd_element = nullptr;
959
960 void _initialize_compile ();
961 void
962 _initialize_compile ()
963 {
964 struct cmd_list_element *c = NULL;
965
966 compile_cmd_element = add_prefix_cmd ("compile", class_obscure,
967 compile_command, _("\
968 Command to compile source code and inject it into the inferior."),
969 &compile_command_list, "compile ", 1, &cmdlist);
970 add_com_alias ("expression", "compile", class_obscure, 0);
971
972 const auto compile_opts = make_compile_options_def_group (nullptr);
973
974 static const std::string compile_code_help
975 = gdb::option::build_help (_("\
976 Compile, inject, and execute code.\n\
977 \n\
978 Usage: compile code [OPTION]... [CODE]\n\
979 \n\
980 Options:\n\
981 %OPTIONS%\n\
982 \n\
983 The source code may be specified as a simple one line expression, e.g.:\n\
984 \n\
985 compile code printf(\"Hello world\\n\");\n\
986 \n\
987 Alternatively, you can type a multiline expression by invoking\n\
988 this command with no argument. GDB will then prompt for the\n\
989 expression interactively; type a line containing \"end\" to\n\
990 indicate the end of the expression."),
991 compile_opts);
992
993 c = add_cmd ("code", class_obscure, compile_code_command,
994 compile_code_help.c_str (),
995 &compile_command_list);
996 set_cmd_completer_handle_brkchars (c, compile_code_command_completer);
997
998 static const std::string compile_file_help
999 = gdb::option::build_help (_("\
1000 Evaluate a file containing source code.\n\
1001 \n\
1002 Usage: compile file [OPTION].. [FILENAME]\n\
1003 \n\
1004 Options:\n\
1005 %OPTIONS%"),
1006 compile_opts);
1007
1008 c = add_cmd ("file", class_obscure, compile_file_command,
1009 compile_file_help.c_str (),
1010 &compile_command_list);
1011 set_cmd_completer_handle_brkchars (c, compile_file_command_completer);
1012
1013 const auto compile_print_opts = make_value_print_options_def_group (nullptr);
1014
1015 static const std::string compile_print_help
1016 = gdb::option::build_help (_("\
1017 Evaluate EXPR by using the compiler and print result.\n\
1018 \n\
1019 Usage: compile print [[OPTION]... --] [/FMT] [EXPR]\n\
1020 \n\
1021 Options:\n\
1022 %OPTIONS%\n\
1023 \n\
1024 Note: because this command accepts arbitrary expressions, if you\n\
1025 specify any command option, you must use a double dash (\"--\")\n\
1026 to mark the end of option processing. E.g.: \"compile print -o -- myobj\".\n\
1027 \n\
1028 The expression may be specified on the same line as the command, e.g.:\n\
1029 \n\
1030 compile print i\n\
1031 \n\
1032 Alternatively, you can type a multiline expression by invoking\n\
1033 this command with no argument. GDB will then prompt for the\n\
1034 expression interactively; type a line containing \"end\" to\n\
1035 indicate the end of the expression.\n\
1036 \n\
1037 EXPR may be preceded with /FMT, where FMT is a format letter\n\
1038 but no count or size letter (see \"x\" command)."),
1039 compile_print_opts);
1040
1041 c = add_cmd ("print", class_obscure, compile_print_command,
1042 compile_print_help.c_str (),
1043 &compile_command_list);
1044 set_cmd_completer_handle_brkchars (c, print_command_completer);
1045
1046 add_setshow_boolean_cmd ("compile", class_maintenance, &compile_debug, _("\
1047 Set compile command debugging."), _("\
1048 Show compile command debugging."), _("\
1049 When on, compile command debugging is enabled."),
1050 NULL, show_compile_debug,
1051 &setdebuglist, &showdebuglist);
1052
1053 add_setshow_string_cmd ("compile-args", class_support,
1054 &compile_args,
1055 _("Set compile command GCC command-line arguments."),
1056 _("Show compile command GCC command-line arguments."),
1057 _("\
1058 Use options like -I (include file directory) or ABI settings.\n\
1059 String quoting is parsed like in shell, for example:\n\
1060 -mno-align-double \"-I/dir with a space/include\""),
1061 set_compile_args, show_compile_args, &setlist, &showlist);
1062
1063 /* Override flags possibly coming from DW_AT_producer. */
1064 compile_args = xstrdup ("-O0 -gdwarf-4"
1065 /* We use -fPIE Otherwise GDB would need to reserve space large enough for
1066 any object file in the inferior in advance to get the final address when
1067 to link the object file to and additionally the default system linker
1068 script would need to be modified so that one can specify there the
1069 absolute target address.
1070 -fPIC is not used at is would require from GDB to generate .got. */
1071 " -fPIE"
1072 /* We want warnings, except for some commonly happening for GDB commands. */
1073 " -Wall "
1074 " -Wno-unused-but-set-variable"
1075 " -Wno-unused-variable"
1076 /* Override CU's possible -fstack-protector-strong. */
1077 " -fno-stack-protector"
1078 );
1079 set_compile_args (compile_args, 0, NULL);
1080
1081 add_setshow_optional_filename_cmd ("compile-gcc", class_support,
1082 &compile_gcc,
1083 _("Set compile command "
1084 "GCC driver filename."),
1085 _("Show compile command "
1086 "GCC driver filename."),
1087 _("\
1088 It should be absolute filename of the gcc executable.\n\
1089 If empty the default target triplet will be searched in $PATH."),
1090 NULL, show_compile_gcc, &setlist,
1091 &showlist);
1092 compile_gcc = xstrdup ("");
1093 }
1094