1 /* General Compile and inject code
3 Copyright (C) 2014-2017 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
24 #include "cli/cli-script.h"
25 #include "cli/cli-utils.h"
26 #include "completer.h"
29 #include "compile-internal.h"
30 #include "compile-object-load.h"
31 #include "compile-object-run.h"
36 #include "arch-utils.h"
37 #include "filestuff.h"
42 #include "common/gdb_optional.h"
43 #include "common/gdb_unlinker.h"
47 /* Initial filename for temporary files. */
49 #define TMP_PREFIX "/tmp/gdbobj-"
51 /* Hold "compile" commands. */
53 static struct cmd_list_element
*compile_command_list
;
55 /* Debug flag for "compile" commands. */
59 /* Implement "show debug compile". */
62 show_compile_debug (struct ui_file
*file
, int from_tty
,
63 struct cmd_list_element
*c
, const char *value
)
65 fprintf_filtered (file
, _("Compile debugging is %s.\n"), value
);
70 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
71 Return 1 if seen and update *ARG. */
74 check_raw_argument (char **arg
)
76 *arg
= skip_spaces (*arg
);
79 && (check_for_argument (arg
, "-raw", sizeof ("-raw") - 1)
80 || check_for_argument (arg
, "-r", sizeof ("-r") - 1)))
85 /* Handle the input from the 'compile file' command. The "compile
86 file" command is used to evaluate an expression contained in a file
87 that may contain calls to the GCC compiler. */
90 compile_file_command (char *arg
, int from_tty
)
92 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
94 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
, 0);
96 /* Check the user did not just <enter> after command. */
98 error (_("You must provide a filename for this command."));
100 /* Check if a raw (-r|-raw) argument is provided. */
101 if (arg
!= NULL
&& check_raw_argument (&arg
))
103 scope
= COMPILE_I_RAW_SCOPE
;
104 arg
= skip_spaces (arg
);
107 /* After processing arguments, check there is a filename at the end
110 error (_("You must provide a filename with the raw option set."));
113 error (_("Unknown argument specified."));
115 arg
= skip_spaces (arg
);
116 gdb::unique_xmalloc_ptr
<char> abspath
= gdb_abspath (arg
);
117 std::string buffer
= string_printf ("#include \"%s\"\n", abspath
.get ());
118 eval_compile_command (NULL
, buffer
.c_str (), scope
, NULL
);
121 /* Handle the input from the 'compile code' command. The
122 "compile code" command is used to evaluate an expression that may
123 contain calls to the GCC compiler. The language expected in this
124 compile command is the language currently set in GDB. */
127 compile_code_command (char *arg
, int from_tty
)
129 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
131 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
, 0);
133 if (arg
!= NULL
&& check_raw_argument (&arg
))
135 scope
= COMPILE_I_RAW_SCOPE
;
136 arg
= skip_spaces (arg
);
139 arg
= skip_spaces (arg
);
141 if (arg
!= NULL
&& !check_for_argument (&arg
, "--", sizeof ("--") - 1))
144 error (_("Unknown argument specified."));
148 eval_compile_command (NULL
, arg
, scope
, NULL
);
151 command_line_up l
= get_command_line (compile_control
, "");
153 l
->control_u
.compile
.scope
= scope
;
154 execute_control_command_untraced (l
.get ());
158 /* Callback for compile_print_command. */
161 compile_print_value (struct value
*val
, void *data_voidp
)
163 const struct format_data
*fmtp
= (const struct format_data
*) data_voidp
;
165 print_value (val
, fmtp
);
168 /* Handle the input from the 'compile print' command. The "compile
169 print" command is used to evaluate and print an expression that may
170 contain calls to the GCC compiler. The language expected in this
171 compile command is the language currently set in GDB. */
174 compile_print_command (char *arg_param
, int from_tty
)
176 const char *arg
= arg_param
;
177 enum compile_i_scope_types scope
= COMPILE_I_PRINT_ADDRESS_SCOPE
;
178 struct format_data fmt
;
180 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
, 0);
182 /* Passing &FMT as SCOPE_DATA is safe as do_module_cleanup will not
183 touch the stale pointer if compile_object_run has already quit. */
184 print_command_parse_format (&arg
, "compile print", &fmt
);
187 eval_compile_command (NULL
, arg
, scope
, &fmt
);
190 command_line_up l
= get_command_line (compile_control
, "");
192 l
->control_u
.compile
.scope
= scope
;
193 l
->control_u
.compile
.scope_data
= &fmt
;
194 execute_control_command_untraced (l
.get ());
198 /* A cleanup function to remove a directory and all its contents. */
203 const char *dir
= (const char *) arg
;
207 gdb_assert (startswith (dir
, TMP_PREFIX
));
208 zap
= concat ("rm -rf ", dir
, (char *) NULL
);
209 wstat
= system (zap
);
210 if (wstat
== -1 || !WIFEXITED (wstat
) || WEXITSTATUS (wstat
) != 0)
211 warning (_("Could not remove temporary directory %s"), dir
);
215 /* Return the name of the temporary directory to use for .o files, and
216 arrange for the directory to be removed at shutdown. */
219 get_compile_file_tempdir (void)
221 static char *tempdir_name
;
223 #define TEMPLATE TMP_PREFIX "XXXXXX"
224 char tname
[sizeof (TEMPLATE
)];
226 if (tempdir_name
!= NULL
)
229 strcpy (tname
, TEMPLATE
);
232 tempdir_name
= mkdtemp (tname
);
234 error (_("Command not supported on this host."));
236 if (tempdir_name
== NULL
)
237 perror_with_name (_("Could not make temporary directory"));
239 tempdir_name
= xstrdup (tempdir_name
);
240 make_final_cleanup (do_rmdir
, tempdir_name
);
244 /* Compute the names of source and object files to use. */
246 static compile_file_names
247 get_new_file_names ()
250 const char *dir
= get_compile_file_tempdir ();
254 return compile_file_names (string_printf ("%s%sout%d.c",
255 dir
, SLASH_STRING
, seq
),
256 string_printf ("%s%sout%d.o",
257 dir
, SLASH_STRING
, seq
));
260 /* Get the block and PC at which to evaluate an expression. */
262 static const struct block
*
263 get_expr_block_and_pc (CORE_ADDR
*pc
)
265 const struct block
*block
= get_selected_block (pc
);
269 struct symtab_and_line cursal
= get_current_source_symtab_and_line ();
272 block
= BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal
.symtab
),
275 *pc
= BLOCK_START (block
);
278 *pc
= BLOCK_START (block
);
283 /* Call buildargv (via gdb_argv), set its result for S into *ARGVP but
284 calculate also the number of parsed arguments into *ARGCP. If
285 buildargv has returned NULL then *ARGCP is set to zero. */
288 build_argc_argv (const char *s
, int *argcp
, char ***argvp
)
292 *argcp
= args
.count ();
293 *argvp
= args
.release ();
296 /* String for 'set compile-args' and 'show compile-args'. */
297 static char *compile_args
;
299 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
300 static int compile_args_argc
;
301 static char **compile_args_argv
;
303 /* Implement 'set compile-args'. */
306 set_compile_args (char *args
, int from_tty
, struct cmd_list_element
*c
)
308 freeargv (compile_args_argv
);
309 build_argc_argv (compile_args
, &compile_args_argc
, &compile_args_argv
);
312 /* Implement 'show compile-args'. */
315 show_compile_args (struct ui_file
*file
, int from_tty
,
316 struct cmd_list_element
*c
, const char *value
)
318 fprintf_filtered (file
, _("Compile command command-line arguments "
323 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
324 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
327 append_args (int *argcp
, char ***argvp
, int argc
, char **argv
)
331 *argvp
= XRESIZEVEC (char *, *argvp
, (*argcp
+ argc
+ 1));
333 for (argi
= 0; argi
< argc
; argi
++)
334 (*argvp
)[(*argcp
)++] = xstrdup (argv
[argi
]);
335 (*argvp
)[(*argcp
)] = NULL
;
338 /* String for 'set compile-gcc' and 'show compile-gcc'. */
339 static char *compile_gcc
;
341 /* Implement 'show compile-gcc'. */
344 show_compile_gcc (struct ui_file
*file
, int from_tty
,
345 struct cmd_list_element
*c
, const char *value
)
347 fprintf_filtered (file
, _("Compile command GCC driver filename is \"%s\".\n"),
351 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
352 Return NULL otherwise.
354 GCC already filters its command-line arguments only for the suitable ones to
355 put into DW_AT_producer - see GCC function gen_producer_string. */
358 get_selected_pc_producer_options (void)
360 CORE_ADDR pc
= get_frame_pc (get_selected_frame (NULL
));
361 struct compunit_symtab
*symtab
= find_pc_compunit_symtab (pc
);
364 if (symtab
== NULL
|| symtab
->producer
== NULL
365 || !startswith (symtab
->producer
, "GNU "))
368 cs
= symtab
->producer
;
369 while (*cs
!= 0 && *cs
!= '-')
370 cs
= skip_spaces_const (skip_to_space_const (cs
));
376 /* Filter out unwanted options from *ARGCP and ARGV. */
379 filter_args (int *argcp
, char **argv
)
383 for (destv
= argv
; *argv
!= NULL
; argv
++)
385 /* -fpreprocessed may get in commonly from ccache. */
386 if (strcmp (*argv
, "-fpreprocessed") == 0)
397 /* Produce final vector of GCC compilation options. First element is target
398 size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
399 and then compile-args string GDB variable. */
402 get_args (const struct compile_instance
*compiler
, struct gdbarch
*gdbarch
,
403 int *argcp
, char ***argvp
)
405 const char *cs_producer_options
;
407 char **argv_compiler
;
409 build_argc_argv (gdbarch_gcc_target_options (gdbarch
),
412 cs_producer_options
= get_selected_pc_producer_options ();
413 if (cs_producer_options
!= NULL
)
416 char **argv_producer
;
418 build_argc_argv (cs_producer_options
, &argc_producer
, &argv_producer
);
419 filter_args (&argc_producer
, argv_producer
);
420 append_args (argcp
, argvp
, argc_producer
, argv_producer
);
421 freeargv (argv_producer
);
424 build_argc_argv (compiler
->gcc_target_options
,
425 &argc_compiler
, &argv_compiler
);
426 append_args (argcp
, argvp
, argc_compiler
, argv_compiler
);
427 freeargv (argv_compiler
);
429 append_args (argcp
, argvp
, compile_args_argc
, compile_args_argv
);
432 /* A cleanup function to destroy a gdb_gcc_instance. */
435 cleanup_compile_instance (void *arg
)
437 struct compile_instance
*inst
= (struct compile_instance
*) arg
;
439 inst
->destroy (inst
);
442 /* A helper function suitable for use as the "print_callback" in the
446 print_callback (void *ignore
, const char *message
)
448 fputs_filtered (message
, gdb_stderr
);
451 /* Process the compilation request. On success it returns the object
452 and source file names. On an error condition, error () is
455 static compile_file_names
456 compile_to_object (struct command_line
*cmd
, const char *cmd_string
,
457 enum compile_i_scope_types scope
)
459 struct compile_instance
*compiler
;
460 struct cleanup
*cleanup
;
461 const struct block
*expr_block
;
462 CORE_ADDR trash_pc
, expr_pc
;
467 struct gdbarch
*gdbarch
= get_current_arch ();
471 if (!target_has_execution
)
472 error (_("The program must be running for the compile command to "\
475 expr_block
= get_expr_block_and_pc (&trash_pc
);
476 expr_pc
= get_frame_address_in_block (get_selected_frame (NULL
));
478 /* Set up instance and context for the compiler. */
479 if (current_language
->la_get_compile_instance
== NULL
)
480 error (_("No compiler support for language %s."),
481 current_language
->la_name
);
482 compiler
= current_language
->la_get_compile_instance ();
483 cleanup
= make_cleanup (cleanup_compile_instance
, compiler
);
485 compiler
->fe
->ops
->set_print_callback (compiler
->fe
, print_callback
, NULL
);
487 compiler
->scope
= scope
;
488 compiler
->block
= expr_block
;
490 /* From the provided expression, build a scope to pass to the
493 string_file input_buf
;
498 struct command_line
*iter
;
500 for (iter
= cmd
->body_list
[0]; iter
; iter
= iter
->next
)
502 input_buf
.puts (iter
->line
);
503 input_buf
.puts ("\n");
506 input
= input_buf
.c_str ();
508 else if (cmd_string
!= NULL
)
511 error (_("Neither a simple expression, or a multi-line specified."));
514 = current_language
->la_compute_program (compiler
, input
, gdbarch
,
515 expr_block
, expr_pc
);
517 fprintf_unfiltered (gdb_stdlog
, "debug output:\n\n%s", code
.c_str ());
519 if (compiler
->fe
->ops
->version
>= GCC_FE_VERSION_1
)
520 compiler
->fe
->ops
->set_verbose (compiler
->fe
, compile_debug
);
522 if (compile_gcc
[0] != 0)
524 if (compiler
->fe
->ops
->version
< GCC_FE_VERSION_1
)
525 error (_("Command 'set compile-gcc' requires GCC version 6 or higher "
526 "(libcc1 interface version 1 or higher)"));
528 compiler
->fe
->ops
->set_driver_filename (compiler
->fe
, compile_gcc
);
532 const char *os_rx
= osabi_triplet_regexp (gdbarch_osabi (gdbarch
));
533 const char *arch_rx
= gdbarch_gnu_triplet_regexp (gdbarch
);
535 /* Allow triplets with or without vendor set. */
536 triplet_rx
= concat (arch_rx
, "(-[^-]*)?-", os_rx
, (char *) NULL
);
537 make_cleanup (xfree
, triplet_rx
);
539 if (compiler
->fe
->ops
->version
>= GCC_FE_VERSION_1
)
540 compiler
->fe
->ops
->set_triplet_regexp (compiler
->fe
, triplet_rx
);
543 /* Set compiler command-line arguments. */
544 get_args (compiler
, gdbarch
, &argc
, &argv
);
545 gdb_argv
argv_holder (argv
);
547 if (compiler
->fe
->ops
->version
>= GCC_FE_VERSION_1
)
548 error_message
= compiler
->fe
->ops
->set_arguments (compiler
->fe
, argc
, argv
);
550 error_message
= compiler
->fe
->ops
->set_arguments_v0 (compiler
->fe
, triplet_rx
,
552 if (error_message
!= NULL
)
554 make_cleanup (xfree
, error_message
);
555 error ("%s", error_message
);
562 fprintf_unfiltered (gdb_stdlog
, "Passing %d compiler options:\n", argc
);
563 for (argi
= 0; argi
< argc
; argi
++)
564 fprintf_unfiltered (gdb_stdlog
, "Compiler option %d: <%s>\n",
568 compile_file_names fnames
= get_new_file_names ();
570 gdb::optional
<gdb::unlinker
> source_remover
;
573 gdb_file_up src
= gdb_fopen_cloexec (fnames
.source_file (), "w");
575 perror_with_name (_("Could not open source file for writing"));
577 source_remover
.emplace (fnames
.source_file ());
579 if (fputs (code
.c_str (), src
.get ()) == EOF
)
580 perror_with_name (_("Could not write to source file"));
584 fprintf_unfiltered (gdb_stdlog
, "source file produced: %s\n\n",
585 fnames
.source_file ());
587 /* Call the compiler and start the compilation process. */
588 compiler
->fe
->ops
->set_source_file (compiler
->fe
, fnames
.source_file ());
590 if (compiler
->fe
->ops
->version
>= GCC_FE_VERSION_1
)
591 ok
= compiler
->fe
->ops
->compile (compiler
->fe
, fnames
.object_file ());
593 ok
= compiler
->fe
->ops
->compile_v0 (compiler
->fe
, fnames
.object_file (),
596 error (_("Compilation failed."));
599 fprintf_unfiltered (gdb_stdlog
, "object file produced: %s\n\n",
600 fnames
.object_file ());
602 /* Keep the source file. */
603 source_remover
->keep ();
605 do_cleanups (cleanup
);
610 /* The "compile" prefix command. */
613 compile_command (char *args
, int from_tty
)
615 /* If a sub-command is not specified to the compile prefix command,
616 assume it is a direct code compilation. */
617 compile_code_command (args
, from_tty
);
623 eval_compile_command (struct command_line
*cmd
, const char *cmd_string
,
624 enum compile_i_scope_types scope
, void *scope_data
)
626 struct compile_module
*compile_module
;
628 compile_file_names fnames
= compile_to_object (cmd
, cmd_string
, scope
);
630 gdb::unlinker
object_remover (fnames
.object_file ());
631 gdb::unlinker
source_remover (fnames
.source_file ());
633 compile_module
= compile_object_load (fnames
, scope
, scope_data
);
634 if (compile_module
== NULL
)
636 gdb_assert (scope
== COMPILE_I_PRINT_ADDRESS_SCOPE
);
637 eval_compile_command (cmd
, cmd_string
,
638 COMPILE_I_PRINT_VALUE_SCOPE
, scope_data
);
642 /* Keep the files. */
643 source_remover
.keep ();
644 object_remover
.keep ();
646 compile_object_run (compile_module
);
649 /* See compile/compile-internal.h. */
652 compile_register_name_mangled (struct gdbarch
*gdbarch
, int regnum
)
654 const char *regname
= gdbarch_register_name (gdbarch
, regnum
);
656 return string_printf ("__%s", regname
);
659 /* See compile/compile-internal.h. */
662 compile_register_name_demangle (struct gdbarch
*gdbarch
,
667 if (regname
[0] != '_' || regname
[1] != '_')
668 error (_("Invalid register name \"%s\"."), regname
);
671 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
672 if (strcmp (regname
, gdbarch_register_name (gdbarch
, regnum
)) == 0)
675 error (_("Cannot find gdbarch register \"%s\"."), regname
);
679 _initialize_compile (void)
681 struct cmd_list_element
*c
= NULL
;
683 add_prefix_cmd ("compile", class_obscure
, compile_command
,
685 Command to compile source code and inject it into the inferior."),
686 &compile_command_list
, "compile ", 1, &cmdlist
);
687 add_com_alias ("expression", "compile", class_obscure
, 0);
689 add_cmd ("code", class_obscure
, compile_code_command
,
691 Compile, inject, and execute code.\n\
693 Usage: compile code [-r|-raw] [--] [CODE]\n\
694 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
695 --: Do not parse any options beyond this delimiter. All text to the\n\
696 right will be treated as source code.\n\
698 The source code may be specified as a simple one line expression, e.g.:\n\
700 compile code printf(\"Hello world\\n\");\n\
702 Alternatively, you can type a multiline expression by invoking\n\
703 this command with no argument. GDB will then prompt for the\n\
704 expression interactively; type a line containing \"end\" to\n\
705 indicate the end of the expression."),
706 &compile_command_list
);
708 c
= add_cmd ("file", class_obscure
, compile_file_command
,
710 Evaluate a file containing source code.\n\
712 Usage: compile file [-r|-raw] [filename]\n\
713 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
714 &compile_command_list
);
715 set_cmd_completer (c
, filename_completer
);
717 add_cmd ("print", class_obscure
, compile_print_command
,
719 Evaluate EXPR by using the compiler and print result.\n\
721 Usage: compile print[/FMT] [EXPR]\n\
723 The expression may be specified on the same line as the command, e.g.:\n\
727 Alternatively, you can type a multiline expression by invoking\n\
728 this command with no argument. GDB will then prompt for the\n\
729 expression interactively; type a line containing \"end\" to\n\
730 indicate the end of the expression.\n\
732 EXPR may be preceded with /FMT, where FMT is a format letter\n\
733 but no count or size letter (see \"x\" command)."),
734 &compile_command_list
);
736 add_setshow_boolean_cmd ("compile", class_maintenance
, &compile_debug
, _("\
737 Set compile command debugging."), _("\
738 Show compile command debugging."), _("\
739 When on, compile command debugging is enabled."),
740 NULL
, show_compile_debug
,
741 &setdebuglist
, &showdebuglist
);
743 add_setshow_string_cmd ("compile-args", class_support
,
745 _("Set compile command GCC command-line arguments"),
746 _("Show compile command GCC command-line arguments"),
748 Use options like -I (include file directory) or ABI settings.\n\
749 String quoting is parsed like in shell, for example:\n\
750 -mno-align-double \"-I/dir with a space/include\""),
751 set_compile_args
, show_compile_args
, &setlist
, &showlist
);
753 /* Override flags possibly coming from DW_AT_producer. */
754 compile_args
= xstrdup ("-O0 -gdwarf-4"
755 /* We use -fPIE Otherwise GDB would need to reserve space large enough for
756 any object file in the inferior in advance to get the final address when
757 to link the object file to and additionally the default system linker
758 script would need to be modified so that one can specify there the
759 absolute target address.
760 -fPIC is not used at is would require from GDB to generate .got. */
762 /* We want warnings, except for some commonly happening for GDB commands. */
764 " -Wno-implicit-function-declaration"
765 " -Wno-unused-but-set-variable"
766 " -Wno-unused-variable"
767 /* Override CU's possible -fstack-protector-strong. */
768 " -fno-stack-protector"
770 set_compile_args (compile_args
, 0, NULL
);
772 add_setshow_optional_filename_cmd ("compile-gcc", class_support
,
774 _("Set compile command "
775 "GCC driver filename"),
776 _("Show compile command "
777 "GCC driver filename"),
779 It should be absolute filename of the gcc executable.\n\
780 If empty the default target triplet will be searched in $PATH."),
781 NULL
, show_compile_gcc
, &setlist
,
783 compile_gcc
= xstrdup ("");