1 /* General Compile and inject code
3 Copyright (C) 2014-2016 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"
45 /* Initial filename for temporary files. */
47 #define TMP_PREFIX "/tmp/gdbobj-"
49 /* Hold "compile" commands. */
51 static struct cmd_list_element
*compile_command_list
;
53 /* Debug flag for "compile" commands. */
57 /* Implement "show debug compile". */
60 show_compile_debug (struct ui_file
*file
, int from_tty
,
61 struct cmd_list_element
*c
, const char *value
)
63 fprintf_filtered (file
, _("Compile debugging is %s.\n"), value
);
68 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
69 Return 1 if seen and update *ARG. */
72 check_raw_argument (char **arg
)
74 *arg
= skip_spaces (*arg
);
77 && (check_for_argument (arg
, "-raw", sizeof ("-raw") - 1)
78 || check_for_argument (arg
, "-r", sizeof ("-r") - 1)))
83 /* Handle the input from the 'compile file' command. The "compile
84 file" command is used to evaluate an expression contained in a file
85 that may contain calls to the GCC compiler. */
88 compile_file_command (char *arg
, int from_tty
)
90 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
92 struct cleanup
*cleanup
;
94 cleanup
= make_cleanup_restore_integer (¤t_ui
->async
);
95 current_ui
->async
= 0;
97 /* Check the user did not just <enter> after command. */
99 error (_("You must provide a filename for this command."));
101 /* Check if a raw (-r|-raw) argument is provided. */
102 if (arg
!= NULL
&& check_raw_argument (&arg
))
104 scope
= COMPILE_I_RAW_SCOPE
;
105 arg
= skip_spaces (arg
);
108 /* After processing arguments, check there is a filename at the end
111 error (_("You must provide a filename with the raw option set."));
114 error (_("Unknown argument specified."));
116 arg
= skip_spaces (arg
);
117 arg
= gdb_abspath (arg
);
118 make_cleanup (xfree
, arg
);
119 buffer
= xstrprintf ("#include \"%s\"\n", arg
);
120 make_cleanup (xfree
, buffer
);
121 eval_compile_command (NULL
, buffer
, scope
, NULL
);
122 do_cleanups (cleanup
);
125 /* Handle the input from the 'compile code' command. The
126 "compile code" command is used to evaluate an expression that may
127 contain calls to the GCC compiler. The language expected in this
128 compile command is the language currently set in GDB. */
131 compile_code_command (char *arg
, int from_tty
)
133 struct cleanup
*cleanup
;
134 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
136 cleanup
= make_cleanup_restore_integer (¤t_ui
->async
);
137 current_ui
->async
= 0;
139 if (arg
!= NULL
&& check_raw_argument (&arg
))
141 scope
= COMPILE_I_RAW_SCOPE
;
142 arg
= skip_spaces (arg
);
145 arg
= skip_spaces (arg
);
147 if (arg
!= NULL
&& !check_for_argument (&arg
, "--", sizeof ("--") - 1))
150 error (_("Unknown argument specified."));
154 eval_compile_command (NULL
, arg
, scope
, NULL
);
157 struct command_line
*l
= get_command_line (compile_control
, "");
159 make_cleanup_free_command_lines (&l
);
160 l
->control_u
.compile
.scope
= scope
;
161 execute_control_command_untraced (l
);
164 do_cleanups (cleanup
);
167 /* Callback for compile_print_command. */
170 compile_print_value (struct value
*val
, void *data_voidp
)
172 const struct format_data
*fmtp
= (const struct format_data
*) data_voidp
;
174 print_value (val
, fmtp
);
177 /* Handle the input from the 'compile print' command. The "compile
178 print" command is used to evaluate and print an expression that may
179 contain calls to the GCC compiler. The language expected in this
180 compile command is the language currently set in GDB. */
183 compile_print_command (char *arg_param
, int from_tty
)
185 const char *arg
= arg_param
;
186 struct cleanup
*cleanup
;
187 enum compile_i_scope_types scope
= COMPILE_I_PRINT_ADDRESS_SCOPE
;
188 struct format_data fmt
;
190 cleanup
= make_cleanup_restore_integer (¤t_ui
->async
);
191 current_ui
->async
= 0;
193 /* Passing &FMT as SCOPE_DATA is safe as do_module_cleanup will not
194 touch the stale pointer if compile_object_run has already quit. */
195 print_command_parse_format (&arg
, "compile print", &fmt
);
198 eval_compile_command (NULL
, arg
, scope
, &fmt
);
201 struct command_line
*l
= get_command_line (compile_control
, "");
203 make_cleanup_free_command_lines (&l
);
204 l
->control_u
.compile
.scope
= scope
;
205 l
->control_u
.compile
.scope_data
= &fmt
;
206 execute_control_command_untraced (l
);
209 do_cleanups (cleanup
);
212 /* A cleanup function to remove a directory and all its contents. */
217 const char *dir
= (const char *) arg
;
221 gdb_assert (startswith (dir
, TMP_PREFIX
));
222 zap
= concat ("rm -rf ", dir
, (char *) NULL
);
223 wstat
= system (zap
);
224 if (wstat
== -1 || !WIFEXITED (wstat
) || WEXITSTATUS (wstat
) != 0)
225 warning (_("Could not remove temporary directory %s"), dir
);
229 /* Return the name of the temporary directory to use for .o files, and
230 arrange for the directory to be removed at shutdown. */
233 get_compile_file_tempdir (void)
235 static char *tempdir_name
;
237 #define TEMPLATE TMP_PREFIX "XXXXXX"
238 char tname
[sizeof (TEMPLATE
)];
240 if (tempdir_name
!= NULL
)
243 strcpy (tname
, TEMPLATE
);
246 tempdir_name
= mkdtemp (tname
);
248 error (_("Command not supported on this host."));
250 if (tempdir_name
== NULL
)
251 perror_with_name (_("Could not make temporary directory"));
253 tempdir_name
= xstrdup (tempdir_name
);
254 make_final_cleanup (do_rmdir
, tempdir_name
);
258 /* Compute the names of source and object files to use. The names are
259 allocated by malloc and should be freed by the caller. */
262 get_new_file_names (char **source_file
, char **object_file
)
265 const char *dir
= get_compile_file_tempdir ();
268 *source_file
= xstrprintf ("%s%sout%d.c", dir
, SLASH_STRING
, seq
);
269 *object_file
= xstrprintf ("%s%sout%d.o", dir
, SLASH_STRING
, seq
);
272 /* Get the block and PC at which to evaluate an expression. */
274 static const struct block
*
275 get_expr_block_and_pc (CORE_ADDR
*pc
)
277 const struct block
*block
= get_selected_block (pc
);
281 struct symtab_and_line cursal
= get_current_source_symtab_and_line ();
284 block
= BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal
.symtab
),
287 *pc
= BLOCK_START (block
);
290 *pc
= BLOCK_START (block
);
295 /* Call gdb_buildargv, set its result for S into *ARGVP but calculate also the
296 number of parsed arguments into *ARGCP. If gdb_buildargv has returned NULL
297 then *ARGCP is set to zero. */
300 build_argc_argv (const char *s
, int *argcp
, char ***argvp
)
302 *argvp
= gdb_buildargv (s
);
303 *argcp
= countargv (*argvp
);
306 /* String for 'set compile-args' and 'show compile-args'. */
307 static char *compile_args
;
309 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
310 static int compile_args_argc
;
311 static char **compile_args_argv
;
313 /* Implement 'set compile-args'. */
316 set_compile_args (char *args
, int from_tty
, struct cmd_list_element
*c
)
318 freeargv (compile_args_argv
);
319 build_argc_argv (compile_args
, &compile_args_argc
, &compile_args_argv
);
322 /* Implement 'show compile-args'. */
325 show_compile_args (struct ui_file
*file
, int from_tty
,
326 struct cmd_list_element
*c
, const char *value
)
328 fprintf_filtered (file
, _("Compile command command-line arguments "
333 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
334 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
337 append_args (int *argcp
, char ***argvp
, int argc
, char **argv
)
341 *argvp
= XRESIZEVEC (char *, *argvp
, (*argcp
+ argc
+ 1));
343 for (argi
= 0; argi
< argc
; argi
++)
344 (*argvp
)[(*argcp
)++] = xstrdup (argv
[argi
]);
345 (*argvp
)[(*argcp
)] = NULL
;
348 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
349 Return NULL otherwise.
351 GCC already filters its command-line arguments only for the suitable ones to
352 put into DW_AT_producer - see GCC function gen_producer_string. */
355 get_selected_pc_producer_options (void)
357 CORE_ADDR pc
= get_frame_pc (get_selected_frame (NULL
));
358 struct compunit_symtab
*symtab
= find_pc_compunit_symtab (pc
);
361 if (symtab
== NULL
|| symtab
->producer
== NULL
362 || !startswith (symtab
->producer
, "GNU "))
365 cs
= symtab
->producer
;
366 while (*cs
!= 0 && *cs
!= '-')
367 cs
= skip_spaces_const (skip_to_space_const (cs
));
373 /* Filter out unwanted options from *ARGCP and ARGV. */
376 filter_args (int *argcp
, char **argv
)
380 for (destv
= argv
; *argv
!= NULL
; argv
++)
382 /* -fpreprocessed may get in commonly from ccache. */
383 if (strcmp (*argv
, "-fpreprocessed") == 0)
394 /* Produce final vector of GCC compilation options. First element is target
395 size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
396 and then compile-args string GDB variable. */
399 get_args (const struct compile_instance
*compiler
, struct gdbarch
*gdbarch
,
400 int *argcp
, char ***argvp
)
402 const char *cs_producer_options
;
404 char **argv_compiler
;
406 build_argc_argv (gdbarch_gcc_target_options (gdbarch
),
409 cs_producer_options
= get_selected_pc_producer_options ();
410 if (cs_producer_options
!= NULL
)
413 char **argv_producer
;
415 build_argc_argv (cs_producer_options
, &argc_producer
, &argv_producer
);
416 filter_args (&argc_producer
, argv_producer
);
417 append_args (argcp
, argvp
, argc_producer
, argv_producer
);
418 freeargv (argv_producer
);
421 build_argc_argv (compiler
->gcc_target_options
,
422 &argc_compiler
, &argv_compiler
);
423 append_args (argcp
, argvp
, argc_compiler
, argv_compiler
);
424 freeargv (argv_compiler
);
426 append_args (argcp
, argvp
, compile_args_argc
, compile_args_argv
);
429 /* A cleanup function to destroy a gdb_gcc_instance. */
432 cleanup_compile_instance (void *arg
)
434 struct compile_instance
*inst
= (struct compile_instance
*) arg
;
436 inst
->destroy (inst
);
439 /* A cleanup function to unlink a file. */
442 cleanup_unlink_file (void *arg
)
444 const char *filename
= (const char *) arg
;
449 /* A helper function suitable for use as the "print_callback" in the
453 print_callback (void *ignore
, const char *message
)
455 fputs_filtered (message
, gdb_stderr
);
458 /* Process the compilation request. On success it returns the object
459 file name and *SOURCE_FILEP is set to source file name. On an
460 error condition, error () is called. The caller is responsible for
461 freeing both strings. */
464 compile_to_object (struct command_line
*cmd
, const char *cmd_string
,
465 enum compile_i_scope_types scope
,
470 char *source_file
, *object_file
;
471 struct compile_instance
*compiler
;
472 struct cleanup
*cleanup
, *inner_cleanup
;
473 const struct block
*expr_block
;
474 CORE_ADDR trash_pc
, expr_pc
;
479 struct gdbarch
*gdbarch
= get_current_arch ();
485 if (!target_has_execution
)
486 error (_("The program must be running for the compile command to "\
489 expr_block
= get_expr_block_and_pc (&trash_pc
);
490 expr_pc
= get_frame_address_in_block (get_selected_frame (NULL
));
492 /* Set up instance and context for the compiler. */
493 if (current_language
->la_get_compile_instance
== NULL
)
494 error (_("No compiler support for language %s."),
495 current_language
->la_name
);
496 compiler
= current_language
->la_get_compile_instance ();
497 cleanup
= make_cleanup (cleanup_compile_instance
, compiler
);
499 compiler
->fe
->ops
->set_print_callback (compiler
->fe
, print_callback
, NULL
);
501 compiler
->scope
= scope
;
502 compiler
->block
= expr_block
;
504 /* From the provided expression, build a scope to pass to the
508 struct ui_file
*stream
= mem_fileopen ();
509 struct command_line
*iter
;
512 make_cleanup_ui_file_delete (stream
);
513 for (iter
= cmd
->body_list
[0]; iter
; iter
= iter
->next
)
515 fputs_unfiltered (iter
->line
, stream
);
516 fputs_unfiltered ("\n", stream
);
519 stream_buf
= ui_file_xstrdup (stream
, NULL
);
520 make_cleanup (xfree
, stream_buf
);
523 else if (cmd_string
!= NULL
)
526 error (_("Neither a simple expression, or a multi-line specified."));
528 code
= current_language
->la_compute_program (compiler
, input
, gdbarch
,
529 expr_block
, expr_pc
);
530 make_cleanup (xfree
, code
);
532 fprintf_unfiltered (gdb_stdlog
, "debug output:\n\n%s", code
);
534 os_rx
= osabi_triplet_regexp (gdbarch_osabi (gdbarch
));
535 arch_rx
= gdbarch_gnu_triplet_regexp (gdbarch
);
537 /* Allow triplets with or without vendor set. */
538 triplet_rx
= concat (arch_rx
, "(-[^-]*)?-", os_rx
, (char *) NULL
);
539 make_cleanup (xfree
, triplet_rx
);
541 /* Set compiler command-line arguments. */
542 get_args (compiler
, gdbarch
, &argc
, &argv
);
543 make_cleanup_freeargv (argv
);
545 error_message
= compiler
->fe
->ops
->set_arguments (compiler
->fe
, triplet_rx
,
547 if (error_message
!= NULL
)
549 make_cleanup (xfree
, error_message
);
550 error ("%s", error_message
);
557 fprintf_unfiltered (gdb_stdlog
, "Passing %d compiler options:\n", argc
);
558 for (argi
= 0; argi
< argc
; argi
++)
559 fprintf_unfiltered (gdb_stdlog
, "Compiler option %d: <%s>\n",
563 get_new_file_names (&source_file
, &object_file
);
564 inner_cleanup
= make_cleanup (xfree
, source_file
);
565 make_cleanup (xfree
, object_file
);
567 src
= gdb_fopen_cloexec (source_file
, "w");
569 perror_with_name (_("Could not open source file for writing"));
570 make_cleanup (cleanup_unlink_file
, source_file
);
571 if (fputs (code
, src
) == EOF
)
572 perror_with_name (_("Could not write to source file"));
576 fprintf_unfiltered (gdb_stdlog
, "source file produced: %s\n\n",
579 /* Call the compiler and start the compilation process. */
580 compiler
->fe
->ops
->set_source_file (compiler
->fe
, source_file
);
582 if (!compiler
->fe
->ops
->compile (compiler
->fe
, object_file
,
584 error (_("Compilation failed."));
587 fprintf_unfiltered (gdb_stdlog
, "object file produced: %s\n\n",
590 discard_cleanups (inner_cleanup
);
591 do_cleanups (cleanup
);
592 *source_filep
= source_file
;
596 /* The "compile" prefix command. */
599 compile_command (char *args
, int from_tty
)
601 /* If a sub-command is not specified to the compile prefix command,
602 assume it is a direct code compilation. */
603 compile_code_command (args
, from_tty
);
609 eval_compile_command (struct command_line
*cmd
, const char *cmd_string
,
610 enum compile_i_scope_types scope
, void *scope_data
)
612 char *object_file
, *source_file
;
614 object_file
= compile_to_object (cmd
, cmd_string
, scope
, &source_file
);
615 if (object_file
!= NULL
)
617 struct cleanup
*cleanup_xfree
, *cleanup_unlink
;
618 struct compile_module
*compile_module
;
620 cleanup_xfree
= make_cleanup (xfree
, object_file
);
621 make_cleanup (xfree
, source_file
);
622 cleanup_unlink
= make_cleanup (cleanup_unlink_file
, object_file
);
623 make_cleanup (cleanup_unlink_file
, source_file
);
624 compile_module
= compile_object_load (object_file
, source_file
,
626 if (compile_module
== NULL
)
628 gdb_assert (scope
== COMPILE_I_PRINT_ADDRESS_SCOPE
);
629 do_cleanups (cleanup_xfree
);
630 eval_compile_command (cmd
, cmd_string
,
631 COMPILE_I_PRINT_VALUE_SCOPE
, scope_data
);
634 discard_cleanups (cleanup_unlink
);
635 do_cleanups (cleanup_xfree
);
636 compile_object_run (compile_module
);
640 /* See compile/compile-internal.h. */
643 compile_register_name_mangled (struct gdbarch
*gdbarch
, int regnum
)
645 const char *regname
= gdbarch_register_name (gdbarch
, regnum
);
647 return xstrprintf ("__%s", regname
);
650 /* See compile/compile-internal.h. */
653 compile_register_name_demangle (struct gdbarch
*gdbarch
,
658 if (regname
[0] != '_' || regname
[1] != '_')
659 error (_("Invalid register name \"%s\"."), regname
);
662 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
663 if (strcmp (regname
, gdbarch_register_name (gdbarch
, regnum
)) == 0)
666 error (_("Cannot find gdbarch register \"%s\"."), regname
);
669 extern initialize_file_ftype _initialize_compile
;
672 _initialize_compile (void)
674 struct cmd_list_element
*c
= NULL
;
676 add_prefix_cmd ("compile", class_obscure
, compile_command
,
678 Command to compile source code and inject it into the inferior."),
679 &compile_command_list
, "compile ", 1, &cmdlist
);
680 add_com_alias ("expression", "compile", class_obscure
, 0);
682 add_cmd ("code", class_obscure
, compile_code_command
,
684 Compile, inject, and execute code.\n\
686 Usage: compile code [-r|-raw] [--] [CODE]\n\
687 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
688 --: Do not parse any options beyond this delimiter. All text to the\n\
689 right will be treated as source code.\n\
691 The source code may be specified as a simple one line expression, e.g.:\n\
693 compile code printf(\"Hello world\\n\");\n\
695 Alternatively, you can type a multiline expression by invoking\n\
696 this command with no argument. GDB will then prompt for the\n\
697 expression interactively; type a line containing \"end\" to\n\
698 indicate the end of the expression."),
699 &compile_command_list
);
701 c
= add_cmd ("file", class_obscure
, compile_file_command
,
703 Evaluate a file containing source code.\n\
705 Usage: compile file [-r|-raw] [filename]\n\
706 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
707 &compile_command_list
);
708 set_cmd_completer (c
, filename_completer
);
710 add_cmd ("print", class_obscure
, compile_print_command
,
712 Evaluate EXPR by using the compiler and print result.\n\
714 Usage: compile print[/FMT] [EXPR]\n\
716 The expression may be specified on the same line as the command, e.g.:\n\
720 Alternatively, you can type a multiline expression by invoking\n\
721 this command with no argument. GDB will then prompt for the\n\
722 expression interactively; type a line containing \"end\" to\n\
723 indicate the end of the expression.\n\
725 EXPR may be preceded with /FMT, where FMT is a format letter\n\
726 but no count or size letter (see \"x\" command)."),
727 &compile_command_list
);
729 add_setshow_boolean_cmd ("compile", class_maintenance
, &compile_debug
, _("\
730 Set compile command debugging."), _("\
731 Show compile command debugging."), _("\
732 When on, compile command debugging is enabled."),
733 NULL
, show_compile_debug
,
734 &setdebuglist
, &showdebuglist
);
736 add_setshow_string_cmd ("compile-args", class_support
,
738 _("Set compile command GCC command-line arguments"),
739 _("Show compile command GCC command-line arguments"),
741 Use options like -I (include file directory) or ABI settings.\n\
742 String quoting is parsed like in shell, for example:\n\
743 -mno-align-double \"-I/dir with a space/include\""),
744 set_compile_args
, show_compile_args
, &setlist
, &showlist
);
746 /* Override flags possibly coming from DW_AT_producer. */
747 compile_args
= xstrdup ("-O0 -gdwarf-4"
748 /* We use -fPIE Otherwise GDB would need to reserve space large enough for
749 any object file in the inferior in advance to get the final address when
750 to link the object file to and additionally the default system linker
751 script would need to be modified so that one can specify there the
752 absolute target address.
753 -fPIC is not used at is would require from GDB to generate .got. */
755 /* We want warnings, except for some commonly happening for GDB commands. */
757 " -Wno-implicit-function-declaration"
758 " -Wno-unused-but-set-variable"
759 " -Wno-unused-variable"
760 /* Override CU's possible -fstack-protector-strong. */
761 " -fno-stack-protector"
763 set_compile_args (compile_args
, 0, NULL
);