1 /* General Compile and inject code
3 Copyright (C) 2014-2015 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"
44 /* Initial filename for temporary files. */
46 #define TMP_PREFIX "/tmp/gdbobj-"
48 /* Hold "compile" commands. */
50 static struct cmd_list_element
*compile_command_list
;
52 /* Debug flag for "compile" commands. */
56 /* Implement "show debug compile". */
59 show_compile_debug (struct ui_file
*file
, int from_tty
,
60 struct cmd_list_element
*c
, const char *value
)
62 fprintf_filtered (file
, _("Compile debugging is %s.\n"), value
);
67 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
68 Return 1 if seen and update *ARG. */
71 check_raw_argument (char **arg
)
73 *arg
= skip_spaces (*arg
);
76 && (check_for_argument (arg
, "-raw", sizeof ("-raw") - 1)
77 || check_for_argument (arg
, "-r", sizeof ("-r") - 1)))
82 /* Handle the input from the 'compile file' command. The "compile
83 file" command is used to evaluate an expression contained in a file
84 that may contain calls to the GCC compiler. */
87 compile_file_command (char *arg
, int from_tty
)
89 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
91 struct cleanup
*cleanup
;
93 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
94 interpreter_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 arg
= gdb_abspath (arg
);
117 make_cleanup (xfree
, arg
);
118 buffer
= xstrprintf ("#include \"%s\"\n", arg
);
119 make_cleanup (xfree
, buffer
);
120 eval_compile_command (NULL
, buffer
, scope
, NULL
);
121 do_cleanups (cleanup
);
124 /* Handle the input from the 'compile code' command. The
125 "compile code" command is used to evaluate an expression that may
126 contain calls to the GCC compiler. The language expected in this
127 compile command is the language currently set in GDB. */
130 compile_code_command (char *arg
, int from_tty
)
132 struct cleanup
*cleanup
;
133 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
135 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
136 interpreter_async
= 0;
138 if (arg
!= NULL
&& check_raw_argument (&arg
))
140 scope
= COMPILE_I_RAW_SCOPE
;
141 arg
= skip_spaces (arg
);
144 arg
= skip_spaces (arg
);
146 if (arg
!= NULL
&& !check_for_argument (&arg
, "--", sizeof ("--") - 1))
149 error (_("Unknown argument specified."));
153 eval_compile_command (NULL
, arg
, scope
, NULL
);
156 struct command_line
*l
= get_command_line (compile_control
, "");
158 make_cleanup_free_command_lines (&l
);
159 l
->control_u
.compile
.scope
= scope
;
160 execute_control_command_untraced (l
);
163 do_cleanups (cleanup
);
166 /* A cleanup function to remove a directory and all its contents. */
171 const char *dir
= arg
;
175 gdb_assert (startswith (dir
, TMP_PREFIX
));
176 zap
= concat ("rm -rf ", dir
, (char *) NULL
);
177 wstat
= system (zap
);
178 if (wstat
== -1 || !WIFEXITED (wstat
) || WEXITSTATUS (wstat
) != 0)
179 warning (_("Could not remove temporary directory %s"), dir
);
183 /* Return the name of the temporary directory to use for .o files, and
184 arrange for the directory to be removed at shutdown. */
187 get_compile_file_tempdir (void)
189 static char *tempdir_name
;
191 #define TEMPLATE TMP_PREFIX "XXXXXX"
192 char tname
[sizeof (TEMPLATE
)];
194 if (tempdir_name
!= NULL
)
197 strcpy (tname
, TEMPLATE
);
200 tempdir_name
= mkdtemp (tname
);
202 error (_("Command not supported on this host."));
204 if (tempdir_name
== NULL
)
205 perror_with_name (_("Could not make temporary directory"));
207 tempdir_name
= xstrdup (tempdir_name
);
208 make_final_cleanup (do_rmdir
, tempdir_name
);
212 /* Compute the names of source and object files to use. The names are
213 allocated by malloc and should be freed by the caller. */
216 get_new_file_names (char **source_file
, char **object_file
)
219 const char *dir
= get_compile_file_tempdir ();
222 *source_file
= xstrprintf ("%s%sout%d.c", dir
, SLASH_STRING
, seq
);
223 *object_file
= xstrprintf ("%s%sout%d.o", dir
, SLASH_STRING
, seq
);
226 /* Get the block and PC at which to evaluate an expression. */
228 static const struct block
*
229 get_expr_block_and_pc (CORE_ADDR
*pc
)
231 const struct block
*block
= get_selected_block (pc
);
235 struct symtab_and_line cursal
= get_current_source_symtab_and_line ();
238 block
= BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal
.symtab
),
241 *pc
= BLOCK_START (block
);
244 *pc
= BLOCK_START (block
);
249 /* Call gdb_buildargv, set its result for S into *ARGVP but calculate also the
250 number of parsed arguments into *ARGCP. If gdb_buildargv has returned NULL
251 then *ARGCP is set to zero. */
254 build_argc_argv (const char *s
, int *argcp
, char ***argvp
)
256 *argvp
= gdb_buildargv (s
);
257 *argcp
= countargv (*argvp
);
260 /* String for 'set compile-args' and 'show compile-args'. */
261 static char *compile_args
;
263 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
264 static int compile_args_argc
;
265 static char **compile_args_argv
;
267 /* Implement 'set compile-args'. */
270 set_compile_args (char *args
, int from_tty
, struct cmd_list_element
*c
)
272 freeargv (compile_args_argv
);
273 build_argc_argv (compile_args
, &compile_args_argc
, &compile_args_argv
);
276 /* Implement 'show compile-args'. */
279 show_compile_args (struct ui_file
*file
, int from_tty
,
280 struct cmd_list_element
*c
, const char *value
)
282 fprintf_filtered (file
, _("Compile command command-line arguments "
287 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
288 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
291 append_args (int *argcp
, char ***argvp
, int argc
, char **argv
)
295 *argvp
= xrealloc (*argvp
, (*argcp
+ argc
+ 1) * sizeof (**argvp
));
297 for (argi
= 0; argi
< argc
; argi
++)
298 (*argvp
)[(*argcp
)++] = xstrdup (argv
[argi
]);
299 (*argvp
)[(*argcp
)] = NULL
;
302 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
303 Return NULL otherwise.
305 GCC already filters its command-line arguments only for the suitable ones to
306 put into DW_AT_producer - see GCC function gen_producer_string. */
309 get_selected_pc_producer_options (void)
311 CORE_ADDR pc
= get_frame_pc (get_selected_frame (NULL
));
312 struct compunit_symtab
*symtab
= find_pc_compunit_symtab (pc
);
315 if (symtab
== NULL
|| symtab
->producer
== NULL
316 || !startswith (symtab
->producer
, "GNU "))
319 cs
= symtab
->producer
;
320 while (*cs
!= 0 && *cs
!= '-')
321 cs
= skip_spaces_const (skip_to_space_const (cs
));
327 /* Filter out unwanted options from *ARGCP and ARGV. */
330 filter_args (int *argcp
, char **argv
)
334 for (destv
= argv
; *argv
!= NULL
; argv
++)
336 /* -fpreprocessed may get in commonly from ccache. */
337 if (strcmp (*argv
, "-fpreprocessed") == 0)
348 /* Produce final vector of GCC compilation options. First element is target
349 size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
350 and then compile-args string GDB variable. */
353 get_args (const struct compile_instance
*compiler
, struct gdbarch
*gdbarch
,
354 int *argcp
, char ***argvp
)
356 const char *cs_producer_options
;
358 char **argv_compiler
;
360 build_argc_argv (gdbarch_gcc_target_options (gdbarch
),
363 cs_producer_options
= get_selected_pc_producer_options ();
364 if (cs_producer_options
!= NULL
)
367 char **argv_producer
;
369 build_argc_argv (cs_producer_options
, &argc_producer
, &argv_producer
);
370 filter_args (&argc_producer
, argv_producer
);
371 append_args (argcp
, argvp
, argc_producer
, argv_producer
);
372 freeargv (argv_producer
);
375 build_argc_argv (compiler
->gcc_target_options
,
376 &argc_compiler
, &argv_compiler
);
377 append_args (argcp
, argvp
, argc_compiler
, argv_compiler
);
378 freeargv (argv_compiler
);
380 append_args (argcp
, argvp
, compile_args_argc
, compile_args_argv
);
383 /* A cleanup function to destroy a gdb_gcc_instance. */
386 cleanup_compile_instance (void *arg
)
388 struct compile_instance
*inst
= arg
;
390 inst
->destroy (inst
);
393 /* A cleanup function to unlink a file. */
396 cleanup_unlink_file (void *arg
)
398 const char *filename
= arg
;
403 /* A helper function suitable for use as the "print_callback" in the
407 print_callback (void *ignore
, const char *message
)
409 fputs_filtered (message
, gdb_stderr
);
412 /* Process the compilation request. On success it returns the object
413 file name and *SOURCE_FILEP is set to source file name. On an
414 error condition, error () is called. The caller is responsible for
415 freeing both strings. */
418 compile_to_object (struct command_line
*cmd
, const char *cmd_string
,
419 enum compile_i_scope_types scope
,
424 char *source_file
, *object_file
;
425 struct compile_instance
*compiler
;
426 struct cleanup
*cleanup
, *inner_cleanup
;
427 const struct block
*expr_block
;
428 CORE_ADDR trash_pc
, expr_pc
;
433 struct gdbarch
*gdbarch
= get_current_arch ();
439 if (!target_has_execution
)
440 error (_("The program must be running for the compile command to "\
443 expr_block
= get_expr_block_and_pc (&trash_pc
);
444 expr_pc
= get_frame_address_in_block (get_selected_frame (NULL
));
446 /* Set up instance and context for the compiler. */
447 if (current_language
->la_get_compile_instance
== NULL
)
448 error (_("No compiler support for this language."));
449 compiler
= current_language
->la_get_compile_instance ();
450 cleanup
= make_cleanup (cleanup_compile_instance
, compiler
);
452 compiler
->fe
->ops
->set_print_callback (compiler
->fe
, print_callback
, NULL
);
454 compiler
->scope
= scope
;
455 compiler
->block
= expr_block
;
457 /* From the provided expression, build a scope to pass to the
461 struct ui_file
*stream
= mem_fileopen ();
462 struct command_line
*iter
;
465 make_cleanup_ui_file_delete (stream
);
466 for (iter
= cmd
->body_list
[0]; iter
; iter
= iter
->next
)
468 fputs_unfiltered (iter
->line
, stream
);
469 fputs_unfiltered ("\n", stream
);
472 stream_buf
= ui_file_xstrdup (stream
, NULL
);
473 make_cleanup (xfree
, stream_buf
);
476 else if (cmd_string
!= NULL
)
479 error (_("Neither a simple expression, or a multi-line specified."));
481 code
= current_language
->la_compute_program (compiler
, input
, gdbarch
,
482 expr_block
, expr_pc
);
483 make_cleanup (xfree
, code
);
485 fprintf_unfiltered (gdb_stdout
, "debug output:\n\n%s", code
);
487 os_rx
= osabi_triplet_regexp (gdbarch_osabi (gdbarch
));
488 arch_rx
= gdbarch_gnu_triplet_regexp (gdbarch
);
490 /* Allow triplets with or without vendor set. */
491 triplet_rx
= concat (arch_rx
, "(-[^-]*)?-", os_rx
, (char *) NULL
);
492 make_cleanup (xfree
, triplet_rx
);
494 /* Set compiler command-line arguments. */
495 get_args (compiler
, gdbarch
, &argc
, &argv
);
496 make_cleanup_freeargv (argv
);
498 error_message
= compiler
->fe
->ops
->set_arguments (compiler
->fe
, triplet_rx
,
500 if (error_message
!= NULL
)
502 make_cleanup (xfree
, error_message
);
503 error ("%s", error_message
);
510 fprintf_unfiltered (gdb_stdout
, "Passing %d compiler options:\n", argc
);
511 for (argi
= 0; argi
< argc
; argi
++)
512 fprintf_unfiltered (gdb_stdout
, "Compiler option %d: <%s>\n",
516 get_new_file_names (&source_file
, &object_file
);
517 inner_cleanup
= make_cleanup (xfree
, source_file
);
518 make_cleanup (xfree
, object_file
);
520 src
= gdb_fopen_cloexec (source_file
, "w");
522 perror_with_name (_("Could not open source file for writing"));
523 make_cleanup (cleanup_unlink_file
, source_file
);
524 if (fputs (code
, src
) == EOF
)
525 perror_with_name (_("Could not write to source file"));
529 fprintf_unfiltered (gdb_stdout
, "source file produced: %s\n\n",
532 /* Call the compiler and start the compilation process. */
533 compiler
->fe
->ops
->set_source_file (compiler
->fe
, source_file
);
535 if (!compiler
->fe
->ops
->compile (compiler
->fe
, object_file
,
537 error (_("Compilation failed."));
540 fprintf_unfiltered (gdb_stdout
, "object file produced: %s\n\n",
543 discard_cleanups (inner_cleanup
);
544 do_cleanups (cleanup
);
545 *source_filep
= source_file
;
549 /* The "compile" prefix command. */
552 compile_command (char *args
, int from_tty
)
554 /* If a sub-command is not specified to the compile prefix command,
555 assume it is a direct code compilation. */
556 compile_code_command (args
, from_tty
);
562 eval_compile_command (struct command_line
*cmd
, const char *cmd_string
,
563 enum compile_i_scope_types scope
, void *scope_data
)
565 char *object_file
, *source_file
;
567 object_file
= compile_to_object (cmd
, cmd_string
, scope
, &source_file
);
568 if (object_file
!= NULL
)
570 struct cleanup
*cleanup_xfree
, *cleanup_unlink
;
571 struct compile_module
*compile_module
;
573 cleanup_xfree
= make_cleanup (xfree
, object_file
);
574 make_cleanup (xfree
, source_file
);
575 cleanup_unlink
= make_cleanup (cleanup_unlink_file
, object_file
);
576 make_cleanup (cleanup_unlink_file
, source_file
);
577 compile_module
= compile_object_load (object_file
, source_file
,
579 discard_cleanups (cleanup_unlink
);
580 do_cleanups (cleanup_xfree
);
581 compile_object_run (compile_module
);
585 /* See compile/compile-internal.h. */
588 compile_register_name_mangled (struct gdbarch
*gdbarch
, int regnum
)
590 const char *regname
= gdbarch_register_name (gdbarch
, regnum
);
592 return xstrprintf ("__%s", regname
);
595 /* See compile/compile-internal.h. */
598 compile_register_name_demangle (struct gdbarch
*gdbarch
,
603 if (regname
[0] != '_' || regname
[1] != '_')
604 error (_("Invalid register name \"%s\"."), regname
);
607 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
608 if (strcmp (regname
, gdbarch_register_name (gdbarch
, regnum
)) == 0)
611 error (_("Cannot find gdbarch register \"%s\"."), regname
);
614 extern initialize_file_ftype _initialize_compile
;
617 _initialize_compile (void)
619 struct cmd_list_element
*c
= NULL
;
621 add_prefix_cmd ("compile", class_obscure
, compile_command
,
623 Command to compile source code and inject it into the inferior."),
624 &compile_command_list
, "compile ", 1, &cmdlist
);
625 add_com_alias ("expression", "compile", class_obscure
, 0);
627 add_cmd ("code", class_obscure
, compile_code_command
,
629 Compile, inject, and execute code.\n\
631 Usage: compile code [-r|-raw] [--] [CODE]\n\
632 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
633 --: Do not parse any options beyond this delimiter. All text to the\n\
634 right will be treated as source code.\n\
636 The source code may be specified as a simple one line expression, e.g.:\n\
638 compile code printf(\"Hello world\\n\");\n\
640 Alternatively, you can type the source code interactively.\n\
641 You can invoke this mode when no argument is given to the command\n\
642 (i.e.,\"compile code\" is typed with nothing after it). An\n\
643 interactive prompt will be shown allowing you to enter multiple\n\
644 lines of source code. Type a line containing \"end\" to indicate\n\
645 the end of the source code."),
646 &compile_command_list
);
648 c
= add_cmd ("file", class_obscure
, compile_file_command
,
650 Evaluate a file containing source code.\n\
652 Usage: compile file [-r|-raw] [filename]\n\
653 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
654 &compile_command_list
);
655 set_cmd_completer (c
, filename_completer
);
657 add_setshow_boolean_cmd ("compile", class_maintenance
, &compile_debug
, _("\
658 Set compile command debugging."), _("\
659 Show compile command debugging."), _("\
660 When on, compile command debugging is enabled."),
661 NULL
, show_compile_debug
,
662 &setdebuglist
, &showdebuglist
);
664 add_setshow_string_cmd ("compile-args", class_support
,
666 _("Set compile command GCC command-line arguments"),
667 _("Show compile command GCC command-line arguments"),
669 Use options like -I (include file directory) or ABI settings.\n\
670 String quoting is parsed like in shell, for example:\n\
671 -mno-align-double \"-I/dir with a space/include\""),
672 set_compile_args
, show_compile_args
, &setlist
, &showlist
);
674 /* Override flags possibly coming from DW_AT_producer. */
675 compile_args
= xstrdup ("-O0 -gdwarf-4"
676 /* We use -fPIE Otherwise GDB would need to reserve space large enough for
677 any object file in the inferior in advance to get the final address when
678 to link the object file to and additionally the default system linker
679 script would need to be modified so that one can specify there the
680 absolute target address.
681 -fPIC is not used at is would require from GDB to generate .got. */
683 /* We don't want warnings. */
685 /* Override CU's possible -fstack-protector-strong. */
686 " -fno-stack-protector"
688 set_compile_args (compile_args
, 0, NULL
);