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"
43 /* Initial filename for temporary files. */
45 #define TMP_PREFIX "/tmp/gdbobj-"
47 /* Hold "compile" commands. */
49 static struct cmd_list_element
*compile_command_list
;
51 /* Debug flag for "compile" commands. */
55 /* Implement "show debug compile". */
58 show_compile_debug (struct ui_file
*file
, int from_tty
,
59 struct cmd_list_element
*c
, const char *value
)
61 fprintf_filtered (file
, _("Compile debugging is %s.\n"), value
);
66 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
67 Return 1 if seen and update *ARG. */
70 check_raw_argument (char **arg
)
72 *arg
= skip_spaces (*arg
);
75 && (check_for_argument (arg
, "-raw", sizeof ("-raw") - 1)
76 || check_for_argument (arg
, "-r", sizeof ("-r") - 1)))
81 /* Handle the input from the 'compile file' command. The "compile
82 file" command is used to evaluate an expression contained in a file
83 that may contain calls to the GCC compiler. */
86 compile_file_command (char *arg
, int from_tty
)
88 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
90 struct cleanup
*cleanup
;
92 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
93 interpreter_async
= 0;
95 /* Check the user did not just <enter> after command. */
97 error (_("You must provide a filename for this command."));
99 /* Check if a raw (-r|-raw) argument is provided. */
100 if (arg
!= NULL
&& check_raw_argument (&arg
))
102 scope
= COMPILE_I_RAW_SCOPE
;
103 arg
= skip_spaces (arg
);
106 /* After processing arguments, check there is a filename at the end
109 error (_("You must provide a filename with the raw option set."));
112 error (_("Unknown argument specified."));
114 arg
= skip_spaces (arg
);
115 arg
= gdb_abspath (arg
);
116 make_cleanup (xfree
, arg
);
117 buffer
= xstrprintf ("#include \"%s\"\n", arg
);
118 make_cleanup (xfree
, buffer
);
119 eval_compile_command (NULL
, buffer
, scope
);
120 do_cleanups (cleanup
);
123 /* Handle the input from the 'compile code' command. The
124 "compile code" command is used to evaluate an expression that may
125 contain calls to the GCC compiler. The language expected in this
126 compile command is the language currently set in GDB. */
129 compile_code_command (char *arg
, int from_tty
)
131 struct cleanup
*cleanup
;
132 enum compile_i_scope_types scope
= COMPILE_I_SIMPLE_SCOPE
;
134 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
135 interpreter_async
= 0;
137 if (arg
!= NULL
&& check_raw_argument (&arg
))
139 scope
= COMPILE_I_RAW_SCOPE
;
140 arg
= skip_spaces (arg
);
143 arg
= skip_spaces (arg
);
145 if (arg
!= NULL
&& !check_for_argument (&arg
, "--", sizeof ("--") - 1))
148 error (_("Unknown argument specified."));
152 eval_compile_command (NULL
, arg
, scope
);
155 struct command_line
*l
= get_command_line (compile_control
, "");
157 make_cleanup_free_command_lines (&l
);
158 l
->control_u
.compile
.scope
= scope
;
159 execute_control_command_untraced (l
);
162 do_cleanups (cleanup
);
165 /* A cleanup function to remove a directory and all its contents. */
170 const char *dir
= arg
;
173 gdb_assert (strncmp (dir
, TMP_PREFIX
, strlen (TMP_PREFIX
)) == 0);
174 zap
= concat ("rm -rf ", dir
, (char *) NULL
);
178 /* Return the name of the temporary directory to use for .o files, and
179 arrange for the directory to be removed at shutdown. */
182 get_compile_file_tempdir (void)
184 static char *tempdir_name
;
186 #define TEMPLATE TMP_PREFIX "XXXXXX"
187 char tname
[sizeof (TEMPLATE
)];
189 if (tempdir_name
!= NULL
)
192 strcpy (tname
, TEMPLATE
);
195 tempdir_name
= mkdtemp (tname
);
197 error (_("Command not supported on this host."));
199 if (tempdir_name
== NULL
)
200 perror_with_name (_("Could not make temporary directory"));
202 tempdir_name
= xstrdup (tempdir_name
);
203 make_final_cleanup (do_rmdir
, tempdir_name
);
207 /* Compute the names of source and object files to use. The names are
208 allocated by malloc and should be freed by the caller. */
211 get_new_file_names (char **source_file
, char **object_file
)
214 const char *dir
= get_compile_file_tempdir ();
217 *source_file
= xstrprintf ("%s%sout%d.c", dir
, SLASH_STRING
, seq
);
218 *object_file
= xstrprintf ("%s%sout%d.o", dir
, SLASH_STRING
, seq
);
221 /* Get the block and PC at which to evaluate an expression. */
223 static const struct block
*
224 get_expr_block_and_pc (CORE_ADDR
*pc
)
226 const struct block
*block
= get_selected_block (pc
);
230 struct symtab_and_line cursal
= get_current_source_symtab_and_line ();
233 block
= BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal
.symtab
),
236 *pc
= BLOCK_START (block
);
239 *pc
= BLOCK_START (block
);
244 /* Call gdb_buildargv, set its result for S into *ARGVP but calculate also the
245 number of parsed arguments into *ARGCP. If gdb_buildargv has returned NULL
246 then *ARGCP is set to zero. */
249 build_argc_argv (const char *s
, int *argcp
, char ***argvp
)
251 *argvp
= gdb_buildargv (s
);
252 *argcp
= countargv (*argvp
);
255 /* String for 'set compile-args' and 'show compile-args'. */
256 static char *compile_args
;
258 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
259 static int compile_args_argc
;
260 static char **compile_args_argv
;
262 /* Implement 'set compile-args'. */
265 set_compile_args (char *args
, int from_tty
, struct cmd_list_element
*c
)
267 freeargv (compile_args_argv
);
268 build_argc_argv (compile_args
, &compile_args_argc
, &compile_args_argv
);
271 /* Implement 'show compile-args'. */
274 show_compile_args (struct ui_file
*file
, int from_tty
,
275 struct cmd_list_element
*c
, const char *value
)
277 fprintf_filtered (file
, _("Compile command command-line arguments "
282 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
283 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
286 append_args (int *argcp
, char ***argvp
, int argc
, char **argv
)
290 *argvp
= xrealloc (*argvp
, (*argcp
+ argc
+ 1) * sizeof (**argvp
));
292 for (argi
= 0; argi
< argc
; argi
++)
293 (*argvp
)[(*argcp
)++] = xstrdup (argv
[argi
]);
294 (*argvp
)[(*argcp
)] = NULL
;
297 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
298 Return NULL otherwise.
300 GCC already filters its command-line arguments only for the suitable ones to
301 put into DW_AT_producer - see GCC function gen_producer_string. */
304 get_selected_pc_producer_options (void)
306 CORE_ADDR pc
= get_frame_pc (get_selected_frame (NULL
));
307 struct compunit_symtab
*symtab
= find_pc_compunit_symtab (pc
);
310 if (symtab
== NULL
|| symtab
->producer
== NULL
311 || strncmp (symtab
->producer
, "GNU ", strlen ("GNU ")) != 0)
314 cs
= symtab
->producer
;
315 while (*cs
!= 0 && *cs
!= '-')
316 cs
= skip_spaces_const (skip_to_space_const (cs
));
322 /* Produce final vector of GCC compilation options. First element is target
323 size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
324 and then compile-args string GDB variable. */
327 get_args (const struct compile_instance
*compiler
, struct gdbarch
*gdbarch
,
328 int *argcp
, char ***argvp
)
330 const char *cs_producer_options
;
332 char **argv_compiler
;
334 build_argc_argv (gdbarch_gcc_target_options (gdbarch
),
337 cs_producer_options
= get_selected_pc_producer_options ();
338 if (cs_producer_options
!= NULL
)
341 char **argv_producer
;
343 build_argc_argv (cs_producer_options
, &argc_producer
, &argv_producer
);
344 append_args (argcp
, argvp
, argc_producer
, argv_producer
);
345 freeargv (argv_producer
);
348 build_argc_argv (compiler
->gcc_target_options
,
349 &argc_compiler
, &argv_compiler
);
350 append_args (argcp
, argvp
, argc_compiler
, argv_compiler
);
351 freeargv (argv_compiler
);
353 append_args (argcp
, argvp
, compile_args_argc
, compile_args_argv
);
356 /* A cleanup function to destroy a gdb_gcc_instance. */
359 cleanup_compile_instance (void *arg
)
361 struct compile_instance
*inst
= arg
;
363 inst
->destroy (inst
);
366 /* A cleanup function to unlink a file. */
369 cleanup_unlink_file (void *arg
)
371 const char *filename
= arg
;
376 /* A helper function suitable for use as the "print_callback" in the
380 print_callback (void *ignore
, const char *message
)
382 fputs_filtered (message
, gdb_stderr
);
385 /* Process the compilation request. On success it returns the object
386 file name and *SOURCE_FILEP is set to source file name. On an
387 error condition, error () is called. The caller is responsible for
388 freeing both strings. */
391 compile_to_object (struct command_line
*cmd
, char *cmd_string
,
392 enum compile_i_scope_types scope
,
396 char *source_file
, *object_file
;
397 struct compile_instance
*compiler
;
398 struct cleanup
*cleanup
, *inner_cleanup
;
399 const struct block
*expr_block
;
400 CORE_ADDR trash_pc
, expr_pc
;
405 struct gdbarch
*gdbarch
= get_current_arch ();
411 if (!target_has_execution
)
412 error (_("The program must be running for the compile command to "\
415 expr_block
= get_expr_block_and_pc (&trash_pc
);
416 expr_pc
= get_frame_address_in_block (get_selected_frame (NULL
));
418 /* Set up instance and context for the compiler. */
419 if (current_language
->la_get_compile_instance
== NULL
)
420 error (_("No compiler support for this language."));
421 compiler
= current_language
->la_get_compile_instance ();
422 cleanup
= make_cleanup (cleanup_compile_instance
, compiler
);
424 compiler
->fe
->ops
->set_print_callback (compiler
->fe
, print_callback
, NULL
);
426 compiler
->scope
= scope
;
427 compiler
->block
= expr_block
;
429 /* From the provided expression, build a scope to pass to the
433 struct ui_file
*stream
= mem_fileopen ();
434 struct command_line
*iter
;
436 make_cleanup_ui_file_delete (stream
);
437 for (iter
= cmd
->body_list
[0]; iter
; iter
= iter
->next
)
439 fputs_unfiltered (iter
->line
, stream
);
440 fputs_unfiltered ("\n", stream
);
443 code
= ui_file_xstrdup (stream
, NULL
);
444 make_cleanup (xfree
, code
);
446 else if (cmd_string
!= NULL
)
449 error (_("Neither a simple expression, or a multi-line specified."));
451 code
= current_language
->la_compute_program (compiler
, code
, gdbarch
,
452 expr_block
, expr_pc
);
453 make_cleanup (xfree
, code
);
455 fprintf_unfiltered (gdb_stdout
, "debug output:\n\n%s", code
);
457 os_rx
= osabi_triplet_regexp (gdbarch_osabi (gdbarch
));
458 arch_rx
= gdbarch_gnu_triplet_regexp (gdbarch
);
459 triplet_rx
= concat (arch_rx
, "-[^-]*-", os_rx
, (char *) NULL
);
460 make_cleanup (xfree
, triplet_rx
);
462 /* Set compiler command-line arguments. */
463 get_args (compiler
, gdbarch
, &argc
, &argv
);
464 make_cleanup_freeargv (argv
);
466 error_message
= compiler
->fe
->ops
->set_arguments (compiler
->fe
, triplet_rx
,
468 if (error_message
!= NULL
)
470 make_cleanup (xfree
, error_message
);
471 error ("%s", error_message
);
478 fprintf_unfiltered (gdb_stdout
, "Passing %d compiler options:\n", argc
);
479 for (argi
= 0; argi
< argc
; argi
++)
480 fprintf_unfiltered (gdb_stdout
, "Compiler option %d: <%s>\n",
484 get_new_file_names (&source_file
, &object_file
);
485 inner_cleanup
= make_cleanup (xfree
, source_file
);
486 make_cleanup (xfree
, object_file
);
488 src
= gdb_fopen_cloexec (source_file
, "w");
490 perror_with_name (_("Could not open source file for writing"));
491 make_cleanup (cleanup_unlink_file
, source_file
);
492 if (fputs (code
, src
) == EOF
)
493 perror_with_name (_("Could not write to source file"));
497 fprintf_unfiltered (gdb_stdout
, "source file produced: %s\n\n",
500 /* Call the compiler and start the compilation process. */
501 compiler
->fe
->ops
->set_source_file (compiler
->fe
, source_file
);
503 if (!compiler
->fe
->ops
->compile (compiler
->fe
, object_file
,
505 error (_("Compilation failed."));
508 fprintf_unfiltered (gdb_stdout
, "object file produced: %s\n\n",
511 discard_cleanups (inner_cleanup
);
512 do_cleanups (cleanup
);
513 *source_filep
= source_file
;
517 /* The "compile" prefix command. */
520 compile_command (char *args
, int from_tty
)
522 /* If a sub-command is not specified to the compile prefix command,
523 assume it is a direct code compilation. */
524 compile_code_command (args
, from_tty
);
530 eval_compile_command (struct command_line
*cmd
, char *cmd_string
,
531 enum compile_i_scope_types scope
)
533 char *object_file
, *source_file
;
535 object_file
= compile_to_object (cmd
, cmd_string
, scope
, &source_file
);
536 if (object_file
!= NULL
)
538 struct cleanup
*cleanup_xfree
, *cleanup_unlink
;
539 struct compile_module
*compile_module
;
541 cleanup_xfree
= make_cleanup (xfree
, object_file
);
542 make_cleanup (xfree
, source_file
);
543 cleanup_unlink
= make_cleanup (cleanup_unlink_file
, object_file
);
544 make_cleanup (cleanup_unlink_file
, source_file
);
545 compile_module
= compile_object_load (object_file
, source_file
);
546 discard_cleanups (cleanup_unlink
);
547 do_cleanups (cleanup_xfree
);
548 compile_object_run (compile_module
);
552 /* See compile/compile-internal.h. */
555 compile_register_name_mangled (struct gdbarch
*gdbarch
, int regnum
)
557 const char *regname
= gdbarch_register_name (gdbarch
, regnum
);
559 return xstrprintf ("__%s", regname
);
562 /* See compile/compile-internal.h. */
565 compile_register_name_demangle (struct gdbarch
*gdbarch
,
570 if (regname
[0] != '_' || regname
[1] != '_')
571 error (_("Invalid register name \"%s\"."), regname
);
574 for (regnum
= 0; regnum
< gdbarch_num_regs (gdbarch
); regnum
++)
575 if (strcmp (regname
, gdbarch_register_name (gdbarch
, regnum
)) == 0)
578 error (_("Cannot find gdbarch register \"%s\"."), regname
);
581 extern initialize_file_ftype _initialize_compile
;
584 _initialize_compile (void)
586 struct cmd_list_element
*c
= NULL
;
588 add_prefix_cmd ("compile", class_obscure
, compile_command
,
590 Command to compile source code and inject it into the inferior."),
591 &compile_command_list
, "compile ", 1, &cmdlist
);
592 add_com_alias ("expression", "compile", class_obscure
, 0);
594 add_cmd ("code", class_obscure
, compile_code_command
,
596 Compile, inject, and execute code.\n\
598 Usage: compile code [-r|-raw] [--] [CODE]\n\
599 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
600 --: Do not parse any options beyond this delimiter. All text to the\n\
601 right will be treated as source code.\n\
603 The source code may be specified as a simple one line expression, e.g.:\n\
605 compile code printf(\"Hello world\\n\");\n\
607 Alternatively, you can type the source code interactively.\n\
608 You can invoke this mode when no argument is given to the command\n\
609 (i.e.,\"compile code\" is typed with nothing after it). An\n\
610 interactive prompt will be shown allowing you to enter multiple\n\
611 lines of source code. Type a line containing \"end\" to indicate\n\
612 the end of the source code."),
613 &compile_command_list
);
615 c
= add_cmd ("file", class_obscure
, compile_file_command
,
617 Evaluate a file containing source code.\n\
619 Usage: compile file [-r|-raw] [filename]\n\
620 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
621 &compile_command_list
);
622 set_cmd_completer (c
, filename_completer
);
624 add_setshow_boolean_cmd ("compile", class_maintenance
, &compile_debug
, _("\
625 Set compile command debugging."), _("\
626 Show compile command debugging."), _("\
627 When on, compile command debugging is enabled."),
628 NULL
, show_compile_debug
,
629 &setdebuglist
, &showdebuglist
);
631 add_setshow_string_cmd ("compile-args", class_support
,
633 _("Set compile command GCC command-line arguments"),
634 _("Show compile command GCC command-line arguments"),
636 Use options like -I (include file directory) or ABI settings.\n\
637 String quoting is parsed like in shell, for example:\n\
638 -mno-align-double \"-I/dir with a space/include\""),
639 set_compile_args
, show_compile_args
, &setlist
, &showlist
);
641 /* Override flags possibly coming from DW_AT_producer. */
642 compile_args
= xstrdup ("-O0 -gdwarf-4"
643 /* We use -fPIC Otherwise GDB would need to reserve space large enough for
644 any object file in the inferior in advance to get the final address when
645 to link the object file to and additionally the default system linker
646 script would need to be modified so that one can specify there the
647 absolute target address. */
649 /* We don't want warnings. */
651 /* Override CU's possible -fstack-protector-strong. */
652 " -fno-stack-protector"
654 set_compile_args (compile_args
, 0, NULL
);