gdb/compile/compile.c - gdb

Global variables defined

Functions defined

Macros defined

Source code

  1. /* General Compile and inject code

  2.    Copyright (C) 2014-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "interps.h"
  16. #include "ui-out.h"
  17. #include "command.h"
  18. #include "cli/cli-script.h"
  19. #include "cli/cli-utils.h"
  20. #include "completer.h"
  21. #include "gdbcmd.h"
  22. #include "compile.h"
  23. #include "compile-internal.h"
  24. #include "compile-object-load.h"
  25. #include "compile-object-run.h"
  26. #include "language.h"
  27. #include "frame.h"
  28. #include "source.h"
  29. #include "block.h"
  30. #include "arch-utils.h"
  31. #include "filestuff.h"
  32. #include "target.h"
  33. #include "osabi.h"
  34. #include "gdb_wait.h"



  35. /* Initial filename for temporary files.  */

  36. #define TMP_PREFIX "/tmp/gdbobj-"

  37. /* Hold "compile" commands.  */

  38. static struct cmd_list_element *compile_command_list;

  39. /* Debug flag for "compile" commands.  */

  40. int compile_debug;

  41. /* Implement "show debug compile".  */

  42. static void
  43. show_compile_debug (struct ui_file *file, int from_tty,
  44.                     struct cmd_list_element *c, const char *value)
  45. {
  46.   fprintf_filtered (file, _("Compile debugging is %s.\n"), value);
  47. }



  48. /* Check *ARG for a "-raw" or "-r" argument.  Return 0 if not seen.
  49.    Return 1 if seen and update *ARG.  */

  50. static int
  51. check_raw_argument (char **arg)
  52. {
  53.   *arg = skip_spaces (*arg);

  54.   if (arg != NULL
  55.       && (check_for_argument (arg, "-raw", sizeof ("-raw") - 1)
  56.           || check_for_argument (arg, "-r", sizeof ("-r") - 1)))
  57.       return 1;
  58.   return 0;
  59. }

  60. /* Handle the input from the 'compile file' command.  The "compile
  61.    file" command is used to evaluate an expression contained in a file
  62.    that may contain calls to the GCC compiler.  */

  63. static void
  64. compile_file_command (char *arg, int from_tty)
  65. {
  66.   enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;
  67.   char *buffer;
  68.   struct cleanup *cleanup;

  69.   cleanup = make_cleanup_restore_integer (&interpreter_async);
  70.   interpreter_async = 0;

  71.   /* Check the user did not just <enter> after command.  */
  72.   if (arg == NULL)
  73.     error (_("You must provide a filename for this command."));

  74.   /* Check if a raw (-r|-raw) argument is provided.  */
  75.   if (arg != NULL && check_raw_argument (&arg))
  76.     {
  77.       scope = COMPILE_I_RAW_SCOPE;
  78.       arg = skip_spaces (arg);
  79.     }

  80.   /* After processing arguments, check there is a filename at the end
  81.      of the command.  */
  82.   if (arg[0] == '\0')
  83.     error (_("You must provide a filename with the raw option set."));

  84.   if (arg[0] == '-')
  85.     error (_("Unknown argument specified."));

  86.   arg = skip_spaces (arg);
  87.   arg = gdb_abspath (arg);
  88.   make_cleanup (xfree, arg);
  89.   buffer = xstrprintf ("#include \"%s\"\n", arg);
  90.   make_cleanup (xfree, buffer);
  91.   eval_compile_command (NULL, buffer, scope);
  92.   do_cleanups (cleanup);
  93. }

  94. /* Handle the input from the 'compile code' command.  The
  95.    "compile code" command is used to evaluate an expression that may
  96.    contain calls to the GCC compiler.  The language expected in this
  97.    compile command is the language currently set in GDB.  */

  98. static void
  99. compile_code_command (char *arg, int from_tty)
  100. {
  101.   struct cleanup *cleanup;
  102.   enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;

  103.   cleanup = make_cleanup_restore_integer (&interpreter_async);
  104.   interpreter_async = 0;

  105.   if (arg != NULL && check_raw_argument (&arg))
  106.     {
  107.       scope = COMPILE_I_RAW_SCOPE;
  108.       arg = skip_spaces (arg);
  109.     }

  110.   arg = skip_spaces (arg);

  111.   if (arg != NULL && !check_for_argument (&arg, "--", sizeof ("--") - 1))
  112.     {
  113.       if (arg[0] == '-')
  114.         error (_("Unknown argument specified."));
  115.     }

  116.   if (arg && *arg)
  117.       eval_compile_command (NULL, arg, scope);
  118.   else
  119.     {
  120.       struct command_line *l = get_command_line (compile_control, "");

  121.       make_cleanup_free_command_lines (&l);
  122.       l->control_u.compile.scope = scope;
  123.       execute_control_command_untraced (l);
  124.     }

  125.   do_cleanups (cleanup);
  126. }

  127. /* A cleanup function to remove a directory and all its contents.  */

  128. static void
  129. do_rmdir (void *arg)
  130. {
  131.   const char *dir = arg;
  132.   char *zap;
  133.   int wstat;

  134.   gdb_assert (strncmp (dir, TMP_PREFIX, strlen (TMP_PREFIX)) == 0);
  135.   zap = concat ("rm -rf ", dir, (char *) NULL);
  136.   wstat = system (zap);
  137.   if (wstat == -1 || !WIFEXITED (wstat) || WEXITSTATUS (wstat) != 0)
  138.     warning (_("Could not remove temporary directory %s"), dir);
  139.   XDELETEVEC (zap);
  140. }

  141. /* Return the name of the temporary directory to use for .o files, and
  142.    arrange for the directory to be removed at shutdown.  */

  143. static const char *
  144. get_compile_file_tempdir (void)
  145. {
  146.   static char *tempdir_name;

  147. #define TEMPLATE TMP_PREFIX "XXXXXX"
  148.   char tname[sizeof (TEMPLATE)];

  149.   if (tempdir_name != NULL)
  150.     return tempdir_name;

  151.   strcpy (tname, TEMPLATE);
  152. #undef TEMPLATE
  153. #ifdef HAVE_MKDTEMP
  154.   tempdir_name = mkdtemp (tname);
  155. #else
  156.   error (_("Command not supported on this host."));
  157. #endif
  158.   if (tempdir_name == NULL)
  159.     perror_with_name (_("Could not make temporary directory"));

  160.   tempdir_name = xstrdup (tempdir_name);
  161.   make_final_cleanup (do_rmdir, tempdir_name);
  162.   return tempdir_name;
  163. }

  164. /* Compute the names of source and object files to use.  The names are
  165.    allocated by malloc and should be freed by the caller.  */

  166. static void
  167. get_new_file_names (char **source_file, char **object_file)
  168. {
  169.   static int seq;
  170.   const char *dir = get_compile_file_tempdir ();

  171.   ++seq;
  172.   *source_file = xstrprintf ("%s%sout%d.c", dir, SLASH_STRING, seq);
  173.   *object_file = xstrprintf ("%s%sout%d.o", dir, SLASH_STRING, seq);
  174. }

  175. /* Get the block and PC at which to evaluate an expression.  */

  176. static const struct block *
  177. get_expr_block_and_pc (CORE_ADDR *pc)
  178. {
  179.   const struct block *block = get_selected_block (pc);

  180.   if (block == NULL)
  181.     {
  182.       struct symtab_and_line cursal = get_current_source_symtab_and_line ();

  183.       if (cursal.symtab)
  184.         block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal.symtab),
  185.                                    STATIC_BLOCK);
  186.       if (block != NULL)
  187.         *pc = BLOCK_START (block);
  188.     }
  189.   else
  190.     *pc = BLOCK_START (block);

  191.   return block;
  192. }

  193. /* Call gdb_buildargv, set its result for S into *ARGVP but calculate also the
  194.    number of parsed arguments into *ARGCP.  If gdb_buildargv has returned NULL
  195.    then *ARGCP is set to zero.  */

  196. static void
  197. build_argc_argv (const char *s, int *argcp, char ***argvp)
  198. {
  199.   *argvp = gdb_buildargv (s);
  200.   *argcp = countargv (*argvp);
  201. }

  202. /* String for 'set compile-args' and 'show compile-args'.  */
  203. static char *compile_args;

  204. /* Parsed form of COMPILE_ARGS.  COMPILE_ARGS_ARGV is NULL terminated.  */
  205. static int compile_args_argc;
  206. static char **compile_args_argv;

  207. /* Implement 'set compile-args'.  */

  208. static void
  209. set_compile_args (char *args, int from_tty, struct cmd_list_element *c)
  210. {
  211.   freeargv (compile_args_argv);
  212.   build_argc_argv (compile_args, &compile_args_argc, &compile_args_argv);
  213. }

  214. /* Implement 'show compile-args'.  */

  215. static void
  216. show_compile_args (struct ui_file *file, int from_tty,
  217.                    struct cmd_list_element *c, const char *value)
  218. {
  219.   fprintf_filtered (file, _("Compile command command-line arguments "
  220.                             "are \"%s\".\n"),
  221.                     value);
  222. }

  223. /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
  224.    ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL.  */

  225. static void
  226. append_args (int *argcp, char ***argvp, int argc, char **argv)
  227. {
  228.   int argi;

  229.   *argvp = xrealloc (*argvp, (*argcp + argc + 1) * sizeof (**argvp));

  230.   for (argi = 0; argi < argc; argi++)
  231.     (*argvp)[(*argcp)++] = xstrdup (argv[argi]);
  232.   (*argvp)[(*argcp)] = NULL;
  233. }

  234. /* Return DW_AT_producer parsed for get_selected_frame () (if any).
  235.    Return NULL otherwise.

  236.    GCC already filters its command-line arguments only for the suitable ones to
  237.    put into DW_AT_producer - see GCC function gen_producer_string.  */

  238. static const char *
  239. get_selected_pc_producer_options (void)
  240. {
  241.   CORE_ADDR pc = get_frame_pc (get_selected_frame (NULL));
  242.   struct compunit_symtab *symtab = find_pc_compunit_symtab (pc);
  243.   const char *cs;

  244.   if (symtab == NULL || symtab->producer == NULL
  245.       || strncmp (symtab->producer, "GNU ", strlen ("GNU ")) != 0)
  246.     return NULL;

  247.   cs = symtab->producer;
  248.   while (*cs != 0 && *cs != '-')
  249.     cs = skip_spaces_const (skip_to_space_const (cs));
  250.   if (*cs != '-')
  251.     return NULL;
  252.   return cs;
  253. }

  254. /* Produce final vector of GCC compilation options.  First element is target
  255.    size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
  256.    and then compile-args string GDB variable.  */

  257. static void
  258. get_args (const struct compile_instance *compiler, struct gdbarch *gdbarch,
  259.           int *argcp, char ***argvp)
  260. {
  261.   const char *cs_producer_options;
  262.   int argc_compiler;
  263.   char **argv_compiler;

  264.   build_argc_argv (gdbarch_gcc_target_options (gdbarch),
  265.                    argcp, argvp);

  266.   cs_producer_options = get_selected_pc_producer_options ();
  267.   if (cs_producer_options != NULL)
  268.     {
  269.       int argc_producer;
  270.       char **argv_producer;

  271.       build_argc_argv (cs_producer_options, &argc_producer, &argv_producer);
  272.       append_args (argcp, argvp, argc_producer, argv_producer);
  273.       freeargv (argv_producer);
  274.     }

  275.   build_argc_argv (compiler->gcc_target_options,
  276.                    &argc_compiler, &argv_compiler);
  277.   append_args (argcp, argvp, argc_compiler, argv_compiler);
  278.   freeargv (argv_compiler);

  279.   append_args (argcp, argvp, compile_args_argc, compile_args_argv);
  280. }

  281. /* A cleanup function to destroy a gdb_gcc_instance.  */

  282. static void
  283. cleanup_compile_instance (void *arg)
  284. {
  285.   struct compile_instance *inst = arg;

  286.   inst->destroy (inst);
  287. }

  288. /* A cleanup function to unlink a file.  */

  289. static void
  290. cleanup_unlink_file (void *arg)
  291. {
  292.   const char *filename = arg;

  293.   unlink (filename);
  294. }

  295. /* A helper function suitable for use as the "print_callback" in the
  296.    compiler object.  */

  297. static void
  298. print_callback (void *ignore, const char *message)
  299. {
  300.   fputs_filtered (message, gdb_stderr);
  301. }

  302. /* Process the compilation request.  On success it returns the object
  303.    file name and *SOURCE_FILEP is set to source file name.  On an
  304.    error condition, error () is called.  The caller is responsible for
  305.    freeing both strings.  */

  306. static char *
  307. compile_to_object (struct command_line *cmd, char *cmd_string,
  308.                    enum compile_i_scope_types scope,
  309.                    char **source_filep)
  310. {
  311.   char *code;
  312.   char *source_file, *object_file;
  313.   struct compile_instance *compiler;
  314.   struct cleanup *cleanup, *inner_cleanup;
  315.   const struct block *expr_block;
  316.   CORE_ADDR trash_pc, expr_pc;
  317.   int argc;
  318.   char **argv;
  319.   int ok;
  320.   FILE *src;
  321.   struct gdbarch *gdbarch = get_current_arch ();
  322.   const char *os_rx;
  323.   const char *arch_rx;
  324.   char *triplet_rx;
  325.   char *error_message;

  326.   if (!target_has_execution)
  327.     error (_("The program must be running for the compile command to "\
  328.              "work."));

  329.   expr_block = get_expr_block_and_pc (&trash_pc);
  330.   expr_pc = get_frame_address_in_block (get_selected_frame (NULL));

  331.   /* Set up instance and context for the compiler.  */
  332.   if (current_language->la_get_compile_instance == NULL)
  333.     error (_("No compiler support for this language."));
  334.   compiler = current_language->la_get_compile_instance ();
  335.   cleanup = make_cleanup (cleanup_compile_instance, compiler);

  336.   compiler->fe->ops->set_print_callback (compiler->fe, print_callback, NULL);

  337.   compiler->scope = scope;
  338.   compiler->block = expr_block;

  339.   /* From the provided expression, build a scope to pass to the
  340.      compiler.  */
  341.   if (cmd != NULL)
  342.     {
  343.       struct ui_file *stream = mem_fileopen ();
  344.       struct command_line *iter;

  345.       make_cleanup_ui_file_delete (stream);
  346.       for (iter = cmd->body_list[0]; iter; iter = iter->next)
  347.         {
  348.           fputs_unfiltered (iter->line, stream);
  349.           fputs_unfiltered ("\n", stream);
  350.         }

  351.       code = ui_file_xstrdup (stream, NULL);
  352.       make_cleanup (xfree, code);
  353.     }
  354.   else if (cmd_string != NULL)
  355.     code = cmd_string;
  356.   else
  357.     error (_("Neither a simple expression, or a multi-line specified."));

  358.   code = current_language->la_compute_program (compiler, code, gdbarch,
  359.                                                expr_block, expr_pc);
  360.   make_cleanup (xfree, code);
  361.   if (compile_debug)
  362.     fprintf_unfiltered (gdb_stdout, "debug output:\n\n%s", code);

  363.   os_rx = osabi_triplet_regexp (gdbarch_osabi (gdbarch));
  364.   arch_rx = gdbarch_gnu_triplet_regexp (gdbarch);
  365.   triplet_rx = concat (arch_rx, "-[^-]*-", os_rx, (char *) NULL);
  366.   make_cleanup (xfree, triplet_rx);

  367.   /* Set compiler command-line arguments.  */
  368.   get_args (compiler, gdbarch, &argc, &argv);
  369.   make_cleanup_freeargv (argv);

  370.   error_message = compiler->fe->ops->set_arguments (compiler->fe, triplet_rx,
  371.                                                     argc, argv);
  372.   if (error_message != NULL)
  373.     {
  374.       make_cleanup (xfree, error_message);
  375.       error ("%s", error_message);
  376.     }

  377.   if (compile_debug)
  378.     {
  379.       int argi;

  380.       fprintf_unfiltered (gdb_stdout, "Passing %d compiler options:\n", argc);
  381.       for (argi = 0; argi < argc; argi++)
  382.         fprintf_unfiltered (gdb_stdout, "Compiler option %d: <%s>\n",
  383.                             argi, argv[argi]);
  384.     }

  385.   get_new_file_names (&source_file, &object_file);
  386.   inner_cleanup = make_cleanup (xfree, source_file);
  387.   make_cleanup (xfree, object_file);

  388.   src = gdb_fopen_cloexec (source_file, "w");
  389.   if (src == NULL)
  390.     perror_with_name (_("Could not open source file for writing"));
  391.   make_cleanup (cleanup_unlink_file, source_file);
  392.   if (fputs (code, src) == EOF)
  393.     perror_with_name (_("Could not write to source file"));
  394.   fclose (src);

  395.   if (compile_debug)
  396.     fprintf_unfiltered (gdb_stdout, "source file produced: %s\n\n",
  397.                         source_file);

  398.   /* Call the compiler and start the compilation process.  */
  399.   compiler->fe->ops->set_source_file (compiler->fe, source_file);

  400.   if (!compiler->fe->ops->compile (compiler->fe, object_file,
  401.                                    compile_debug))
  402.     error (_("Compilation failed."));

  403.   if (compile_debug)
  404.     fprintf_unfiltered (gdb_stdout, "object file produced: %s\n\n",
  405.                         object_file);

  406.   discard_cleanups (inner_cleanup);
  407.   do_cleanups (cleanup);
  408.   *source_filep = source_file;
  409.   return object_file;
  410. }

  411. /* The "compile" prefix command.  */

  412. static void
  413. compile_command (char *args, int from_tty)
  414. {
  415.   /* If a sub-command is not specified to the compile prefix command,
  416.      assume it is a direct code compilation.  */
  417.   compile_code_command (args, from_tty);
  418. }

  419. /* See compile.h.  */

  420. void
  421. eval_compile_command (struct command_line *cmd, char *cmd_string,
  422.                       enum compile_i_scope_types scope)
  423. {
  424.   char *object_file, *source_file;

  425.   object_file = compile_to_object (cmd, cmd_string, scope, &source_file);
  426.   if (object_file != NULL)
  427.     {
  428.       struct cleanup *cleanup_xfree, *cleanup_unlink;
  429.       struct compile_module *compile_module;

  430.       cleanup_xfree = make_cleanup (xfree, object_file);
  431.       make_cleanup (xfree, source_file);
  432.       cleanup_unlink = make_cleanup (cleanup_unlink_file, object_file);
  433.       make_cleanup (cleanup_unlink_file, source_file);
  434.       compile_module = compile_object_load (object_file, source_file);
  435.       discard_cleanups (cleanup_unlink);
  436.       do_cleanups (cleanup_xfree);
  437.       compile_object_run (compile_module);
  438.     }
  439. }

  440. /* See compile/compile-internal.h.  */

  441. char *
  442. compile_register_name_mangled (struct gdbarch *gdbarch, int regnum)
  443. {
  444.   const char *regname = gdbarch_register_name (gdbarch, regnum);

  445.   return xstrprintf ("__%s", regname);
  446. }

  447. /* See compile/compile-internal.h.  */

  448. int
  449. compile_register_name_demangle (struct gdbarch *gdbarch,
  450.                                  const char *regname)
  451. {
  452.   int regnum;

  453.   if (regname[0] != '_' || regname[1] != '_')
  454.     error (_("Invalid register name \"%s\"."), regname);
  455.   regname += 2;

  456.   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
  457.     if (strcmp (regname, gdbarch_register_name (gdbarch, regnum)) == 0)
  458.       return regnum;

  459.   error (_("Cannot find gdbarch register \"%s\"."), regname);
  460. }

  461. extern initialize_file_ftype _initialize_compile;

  462. void
  463. _initialize_compile (void)
  464. {
  465.   struct cmd_list_element *c = NULL;

  466.   add_prefix_cmd ("compile", class_obscure, compile_command,
  467.                   _("\
  468. Command to compile source code and inject it into the inferior."),
  469.                   &compile_command_list, "compile ", 1, &cmdlist);
  470.   add_com_alias ("expression", "compile", class_obscure, 0);

  471.   add_cmd ("code", class_obscure, compile_code_command,
  472.            _("\
  473. Compile, inject, and execute code.\n\
  474. \n\
  475. Usage: compile code [-r|-raw] [--] [CODE]\n\
  476. -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
  477. --: Do not parse any options beyond this delimiter.  All text to the\n\
  478.     right will be treated as source code.\n\
  479. \n\
  480. The source code may be specified as a simple one line expression, e.g.:\n\
  481. \n\
  482.     compile code printf(\"Hello world\\n\");\n\
  483. \n\
  484. Alternatively, you can type the source code interactively.\n\
  485. You can invoke this mode when no argument is given to the command\n\
  486. (i.e.,\"compile code\" is typed with nothing after it).  An\n\
  487. interactive prompt will be shown allowing you to enter multiple\n\
  488. lines of source code.  Type a line containing \"end\" to indicate\n\
  489. the end of the source code."),
  490.            &compile_command_list);

  491.   c = add_cmd ("file", class_obscure, compile_file_command,
  492.                _("\
  493. Evaluate a file containing source code.\n\
  494. \n\
  495. Usage: compile file [-r|-raw] [filename]\n\
  496. -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
  497.                &compile_command_list);
  498.   set_cmd_completer (c, filename_completer);

  499.   add_setshow_boolean_cmd ("compile", class_maintenance, &compile_debug, _("\
  500. Set compile command debugging."), _("\
  501. Show compile command debugging."), _("\
  502. When on, compile command debugging is enabled."),
  503.                            NULL, show_compile_debug,
  504.                            &setdebuglist, &showdebuglist);

  505.   add_setshow_string_cmd ("compile-args", class_support,
  506.                           &compile_args,
  507.                           _("Set compile command GCC command-line arguments"),
  508.                           _("Show compile command GCC command-line arguments"),
  509.                           _("\
  510. Use options like -I (include file directory) or ABI settings.\n\
  511. String quoting is parsed like in shell, for example:\n\
  512.   -mno-align-double \"-I/dir with a space/include\""),
  513.                           set_compile_args, show_compile_args, &setlist, &showlist);

  514.   /* Override flags possibly coming from DW_AT_producer.  */
  515.   compile_args = xstrdup ("-O0 -gdwarf-4"
  516.   /* We use -fPIC Otherwise GDB would need to reserve space large enough for
  517.      any object file in the inferior in advance to get the final address when
  518.      to link the object file to and additionally the default system linker
  519.      script would need to be modified so that one can specify there the
  520.      absolute target address.  */
  521.                          " -fPIC"
  522.   /* We don't want warnings.  */
  523.                          " -w"
  524.   /* Override CU's possible -fstack-protector-strong.  */
  525.                          " -fno-stack-protector"
  526.   );
  527.   set_compile_args (compile_args, 0, NULL);
  528. }