compile.c revision 1.1 1 /* General Compile and inject code
2
3 Copyright (C) 2014-2015 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20 #include "defs.h"
21 #include "interps.h"
22 #include "ui-out.h"
23 #include "command.h"
24 #include "cli/cli-script.h"
25 #include "cli/cli-utils.h"
26 #include "completer.h"
27 #include "gdbcmd.h"
28 #include "compile.h"
29 #include "compile-internal.h"
30 #include "compile-object-load.h"
31 #include "compile-object-run.h"
32 #include "language.h"
33 #include "frame.h"
34 #include "source.h"
35 #include "block.h"
36 #include "arch-utils.h"
37 #include "filestuff.h"
38 #include "target.h"
39 #include "osabi.h"
40 #include "gdb_wait.h"
41
42
43
45 /* Initial filename for temporary files. */
46
47 #define TMP_PREFIX "/tmp/gdbobj-"
48
49 /* Hold "compile" commands. */
50
51 static struct cmd_list_element *compile_command_list;
52
53 /* Debug flag for "compile" commands. */
54
55 int compile_debug;
56
57 /* Implement "show debug compile". */
58
59 static void
60 show_compile_debug (struct ui_file *file, int from_tty,
61 struct cmd_list_element *c, const char *value)
62 {
63 fprintf_filtered (file, _("Compile debugging is %s.\n"), value);
64 }
65
66
67
69 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
70 Return 1 if seen and update *ARG. */
71
72 static int
73 check_raw_argument (char **arg)
74 {
75 *arg = skip_spaces (*arg);
76
77 if (arg != NULL
78 && (check_for_argument (arg, "-raw", sizeof ("-raw") - 1)
79 || check_for_argument (arg, "-r", sizeof ("-r") - 1)))
80 return 1;
81 return 0;
82 }
83
84 /* Handle the input from the 'compile file' command. The "compile
85 file" command is used to evaluate an expression contained in a file
86 that may contain calls to the GCC compiler. */
87
88 static void
89 compile_file_command (char *arg, int from_tty)
90 {
91 enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;
92 char *buffer;
93 struct cleanup *cleanup;
94
95 cleanup = make_cleanup_restore_integer (&interpreter_async);
96 interpreter_async = 0;
97
98 /* Check the user did not just <enter> after command. */
99 if (arg == NULL)
100 error (_("You must provide a filename for this command."));
101
102 /* Check if a raw (-r|-raw) argument is provided. */
103 if (arg != NULL && check_raw_argument (&arg))
104 {
105 scope = COMPILE_I_RAW_SCOPE;
106 arg = skip_spaces (arg);
107 }
108
109 /* After processing arguments, check there is a filename at the end
110 of the command. */
111 if (arg[0] == '\0')
112 error (_("You must provide a filename with the raw option set."));
113
114 if (arg[0] == '-')
115 error (_("Unknown argument specified."));
116
117 arg = skip_spaces (arg);
118 arg = gdb_abspath (arg);
119 make_cleanup (xfree, arg);
120 buffer = xstrprintf ("#include \"%s\"\n", arg);
121 make_cleanup (xfree, buffer);
122 eval_compile_command (NULL, buffer, scope);
123 do_cleanups (cleanup);
124 }
125
126 /* Handle the input from the 'compile code' command. The
127 "compile code" command is used to evaluate an expression that may
128 contain calls to the GCC compiler. The language expected in this
129 compile command is the language currently set in GDB. */
130
131 static void
132 compile_code_command (char *arg, int from_tty)
133 {
134 struct cleanup *cleanup;
135 enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;
136
137 cleanup = make_cleanup_restore_integer (&interpreter_async);
138 interpreter_async = 0;
139
140 if (arg != NULL && check_raw_argument (&arg))
141 {
142 scope = COMPILE_I_RAW_SCOPE;
143 arg = skip_spaces (arg);
144 }
145
146 arg = skip_spaces (arg);
147
148 if (arg != NULL && !check_for_argument (&arg, "--", sizeof ("--") - 1))
149 {
150 if (arg[0] == '-')
151 error (_("Unknown argument specified."));
152 }
153
154 if (arg && *arg)
155 eval_compile_command (NULL, arg, scope);
156 else
157 {
158 struct command_line *l = get_command_line (compile_control, "");
159
160 make_cleanup_free_command_lines (&l);
161 l->control_u.compile.scope = scope;
162 execute_control_command_untraced (l);
163 }
164
165 do_cleanups (cleanup);
166 }
167
168 /* A cleanup function to remove a directory and all its contents. */
169
170 static void
171 do_rmdir (void *arg)
172 {
173 const char *dir = arg;
174 char *zap;
175 int wstat;
176
177 gdb_assert (strncmp (dir, TMP_PREFIX, strlen (TMP_PREFIX)) == 0);
178 zap = concat ("rm -rf ", dir, (char *) NULL);
179 wstat = system (zap);
180 if (wstat == -1 || !WIFEXITED (wstat) || WEXITSTATUS (wstat) != 0)
181 warning (_("Could not remove temporary directory %s"), dir);
182 XDELETEVEC (zap);
183 }
184
185 /* Return the name of the temporary directory to use for .o files, and
186 arrange for the directory to be removed at shutdown. */
187
188 static const char *
189 get_compile_file_tempdir (void)
190 {
191 static char *tempdir_name;
192
193 #define TEMPLATE TMP_PREFIX "XXXXXX"
194 char tname[sizeof (TEMPLATE)];
195
196 if (tempdir_name != NULL)
197 return tempdir_name;
198
199 strcpy (tname, TEMPLATE);
200 #undef TEMPLATE
201 #ifdef HAVE_MKDTEMP
202 tempdir_name = mkdtemp (tname);
203 #else
204 error (_("Command not supported on this host."));
205 #endif
206 if (tempdir_name == NULL)
207 perror_with_name (_("Could not make temporary directory"));
208
209 tempdir_name = xstrdup (tempdir_name);
210 make_final_cleanup (do_rmdir, tempdir_name);
211 return tempdir_name;
212 }
213
214 /* Compute the names of source and object files to use. The names are
215 allocated by malloc and should be freed by the caller. */
216
217 static void
218 get_new_file_names (char **source_file, char **object_file)
219 {
220 static int seq;
221 const char *dir = get_compile_file_tempdir ();
222
223 ++seq;
224 *source_file = xstrprintf ("%s%sout%d.c", dir, SLASH_STRING, seq);
225 *object_file = xstrprintf ("%s%sout%d.o", dir, SLASH_STRING, seq);
226 }
227
228 /* Get the block and PC at which to evaluate an expression. */
229
230 static const struct block *
231 get_expr_block_and_pc (CORE_ADDR *pc)
232 {
233 const struct block *block = get_selected_block (pc);
234
235 if (block == NULL)
236 {
237 struct symtab_and_line cursal = get_current_source_symtab_and_line ();
238
239 if (cursal.symtab)
240 block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal.symtab),
241 STATIC_BLOCK);
242 if (block != NULL)
243 *pc = BLOCK_START (block);
244 }
245 else
246 *pc = BLOCK_START (block);
247
248 return block;
249 }
250
251 /* Call gdb_buildargv, set its result for S into *ARGVP but calculate also the
252 number of parsed arguments into *ARGCP. If gdb_buildargv has returned NULL
253 then *ARGCP is set to zero. */
254
255 static void
256 build_argc_argv (const char *s, int *argcp, char ***argvp)
257 {
258 *argvp = gdb_buildargv (s);
259 *argcp = countargv (*argvp);
260 }
261
262 /* String for 'set compile-args' and 'show compile-args'. */
263 static char *compile_args;
264
265 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
266 static int compile_args_argc;
267 static char **compile_args_argv;
268
269 /* Implement 'set compile-args'. */
270
271 static void
272 set_compile_args (char *args, int from_tty, struct cmd_list_element *c)
273 {
274 freeargv (compile_args_argv);
275 build_argc_argv (compile_args, &compile_args_argc, &compile_args_argv);
276 }
277
278 /* Implement 'show compile-args'. */
279
280 static void
281 show_compile_args (struct ui_file *file, int from_tty,
282 struct cmd_list_element *c, const char *value)
283 {
284 fprintf_filtered (file, _("Compile command command-line arguments "
285 "are \"%s\".\n"),
286 value);
287 }
288
289 /* Append ARGC and ARGV (as parsed by build_argc_argv) to *ARGCP and *ARGVP.
290 ARGCP+ARGVP can be zero+NULL and also ARGC+ARGV can be zero+NULL. */
291
292 static void
293 append_args (int *argcp, char ***argvp, int argc, char **argv)
294 {
295 int argi;
296
297 *argvp = xrealloc (*argvp, (*argcp + argc + 1) * sizeof (**argvp));
298
299 for (argi = 0; argi < argc; argi++)
300 (*argvp)[(*argcp)++] = xstrdup (argv[argi]);
301 (*argvp)[(*argcp)] = NULL;
302 }
303
304 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
305 Return NULL otherwise.
306
307 GCC already filters its command-line arguments only for the suitable ones to
308 put into DW_AT_producer - see GCC function gen_producer_string. */
309
310 static const char *
311 get_selected_pc_producer_options (void)
312 {
313 CORE_ADDR pc = get_frame_pc (get_selected_frame (NULL));
314 struct compunit_symtab *symtab = find_pc_compunit_symtab (pc);
315 const char *cs;
316
317 if (symtab == NULL || symtab->producer == NULL
318 || strncmp (symtab->producer, "GNU ", strlen ("GNU ")) != 0)
319 return NULL;
320
321 cs = symtab->producer;
322 while (*cs != 0 && *cs != '-')
323 cs = skip_spaces_const (skip_to_space_const (cs));
324 if (*cs != '-')
325 return NULL;
326 return cs;
327 }
328
329 /* Filter out unwanted options from *ARGCP and ARGV. */
330
331 static void
332 filter_args (int *argcp, char **argv)
333 {
334 char **destv;
335
336 for (destv = argv; *argv != NULL; argv++)
337 {
338 /* -fpreprocessed may get in commonly from ccache. */
339 if (strcmp (*argv, "-fpreprocessed") == 0)
340 {
341 xfree (*argv);
342 (*argcp)--;
343 continue;
344 }
345 *destv++ = *argv;
346 }
347 *destv = NULL;
348 }
349
350 /* Produce final vector of GCC compilation options. First element is target
351 size ("-m64", "-m32" etc.), optionally followed by DW_AT_producer options
352 and then compile-args string GDB variable. */
353
354 static void
355 get_args (const struct compile_instance *compiler, struct gdbarch *gdbarch,
356 int *argcp, char ***argvp)
357 {
358 const char *cs_producer_options;
359 int argc_compiler;
360 char **argv_compiler;
361
362 build_argc_argv (gdbarch_gcc_target_options (gdbarch),
363 argcp, argvp);
364
365 cs_producer_options = get_selected_pc_producer_options ();
366 if (cs_producer_options != NULL)
367 {
368 int argc_producer;
369 char **argv_producer;
370
371 build_argc_argv (cs_producer_options, &argc_producer, &argv_producer);
372 filter_args (&argc_producer, argv_producer);
373 append_args (argcp, argvp, argc_producer, argv_producer);
374 freeargv (argv_producer);
375 }
376
377 build_argc_argv (compiler->gcc_target_options,
378 &argc_compiler, &argv_compiler);
379 append_args (argcp, argvp, argc_compiler, argv_compiler);
380 freeargv (argv_compiler);
381
382 append_args (argcp, argvp, compile_args_argc, compile_args_argv);
383 }
384
385 /* A cleanup function to destroy a gdb_gcc_instance. */
386
387 static void
388 cleanup_compile_instance (void *arg)
389 {
390 struct compile_instance *inst = arg;
391
392 inst->destroy (inst);
393 }
394
395 /* A cleanup function to unlink a file. */
396
397 static void
398 cleanup_unlink_file (void *arg)
399 {
400 const char *filename = arg;
401
402 unlink (filename);
403 }
404
405 /* A helper function suitable for use as the "print_callback" in the
406 compiler object. */
407
408 static void
409 print_callback (void *ignore, const char *message)
410 {
411 fputs_filtered (message, gdb_stderr);
412 }
413
414 /* Process the compilation request. On success it returns the object
415 file name and *SOURCE_FILEP is set to source file name. On an
416 error condition, error () is called. The caller is responsible for
417 freeing both strings. */
418
419 static char *
420 compile_to_object (struct command_line *cmd, char *cmd_string,
421 enum compile_i_scope_types scope,
422 char **source_filep)
423 {
424 char *code;
425 char *source_file, *object_file;
426 struct compile_instance *compiler;
427 struct cleanup *cleanup, *inner_cleanup;
428 const struct block *expr_block;
429 CORE_ADDR trash_pc, expr_pc;
430 int argc;
431 char **argv;
432 int ok;
433 FILE *src;
434 struct gdbarch *gdbarch = get_current_arch ();
435 const char *os_rx;
436 const char *arch_rx;
437 char *triplet_rx;
438 char *error_message;
439
440 if (!target_has_execution)
441 error (_("The program must be running for the compile command to "\
442 "work."));
443
444 expr_block = get_expr_block_and_pc (&trash_pc);
445 expr_pc = get_frame_address_in_block (get_selected_frame (NULL));
446
447 /* Set up instance and context for the compiler. */
448 if (current_language->la_get_compile_instance == NULL)
449 error (_("No compiler support for this language."));
450 compiler = current_language->la_get_compile_instance ();
451 cleanup = make_cleanup (cleanup_compile_instance, compiler);
452
453 compiler->fe->ops->set_print_callback (compiler->fe, print_callback, NULL);
454
455 compiler->scope = scope;
456 compiler->block = expr_block;
457
458 /* From the provided expression, build a scope to pass to the
459 compiler. */
460 if (cmd != NULL)
461 {
462 struct ui_file *stream = mem_fileopen ();
463 struct command_line *iter;
464
465 make_cleanup_ui_file_delete (stream);
466 for (iter = cmd->body_list[0]; iter; iter = iter->next)
467 {
468 fputs_unfiltered (iter->line, stream);
469 fputs_unfiltered ("\n", stream);
470 }
471
472 code = ui_file_xstrdup (stream, NULL);
473 make_cleanup (xfree, code);
474 }
475 else if (cmd_string != NULL)
476 code = cmd_string;
477 else
478 error (_("Neither a simple expression, or a multi-line specified."));
479
480 code = current_language->la_compute_program (compiler, code, gdbarch,
481 expr_block, expr_pc);
482 make_cleanup (xfree, code);
483 if (compile_debug)
484 fprintf_unfiltered (gdb_stdout, "debug output:\n\n%s", code);
485
486 os_rx = osabi_triplet_regexp (gdbarch_osabi (gdbarch));
487 arch_rx = gdbarch_gnu_triplet_regexp (gdbarch);
488
489 /* Allow triplets with or without vendor set. */
490 triplet_rx = concat (arch_rx, "(-[^-]*)?-", os_rx, (char *) NULL);
491 make_cleanup (xfree, triplet_rx);
492
493 /* Set compiler command-line arguments. */
494 get_args (compiler, gdbarch, &argc, &argv);
495 make_cleanup_freeargv (argv);
496
497 error_message = compiler->fe->ops->set_arguments (compiler->fe, triplet_rx,
498 argc, argv);
499 if (error_message != NULL)
500 {
501 make_cleanup (xfree, error_message);
502 error ("%s", error_message);
503 }
504
505 if (compile_debug)
506 {
507 int argi;
508
509 fprintf_unfiltered (gdb_stdout, "Passing %d compiler options:\n", argc);
510 for (argi = 0; argi < argc; argi++)
511 fprintf_unfiltered (gdb_stdout, "Compiler option %d: <%s>\n",
512 argi, argv[argi]);
513 }
514
515 get_new_file_names (&source_file, &object_file);
516 inner_cleanup = make_cleanup (xfree, source_file);
517 make_cleanup (xfree, object_file);
518
519 src = gdb_fopen_cloexec (source_file, "w");
520 if (src == NULL)
521 perror_with_name (_("Could not open source file for writing"));
522 make_cleanup (cleanup_unlink_file, source_file);
523 if (fputs (code, src) == EOF)
524 perror_with_name (_("Could not write to source file"));
525 fclose (src);
526
527 if (compile_debug)
528 fprintf_unfiltered (gdb_stdout, "source file produced: %s\n\n",
529 source_file);
530
531 /* Call the compiler and start the compilation process. */
532 compiler->fe->ops->set_source_file (compiler->fe, source_file);
533
534 if (!compiler->fe->ops->compile (compiler->fe, object_file,
535 compile_debug))
536 error (_("Compilation failed."));
537
538 if (compile_debug)
539 fprintf_unfiltered (gdb_stdout, "object file produced: %s\n\n",
540 object_file);
541
542 discard_cleanups (inner_cleanup);
543 do_cleanups (cleanup);
544 *source_filep = source_file;
545 return object_file;
546 }
547
548 /* The "compile" prefix command. */
549
550 static void
551 compile_command (char *args, int from_tty)
552 {
553 /* If a sub-command is not specified to the compile prefix command,
554 assume it is a direct code compilation. */
555 compile_code_command (args, from_tty);
556 }
557
558 /* See compile.h. */
559
560 void
561 eval_compile_command (struct command_line *cmd, char *cmd_string,
562 enum compile_i_scope_types scope)
563 {
564 char *object_file, *source_file;
565
566 object_file = compile_to_object (cmd, cmd_string, scope, &source_file);
567 if (object_file != NULL)
568 {
569 struct cleanup *cleanup_xfree, *cleanup_unlink;
570 struct compile_module *compile_module;
571
572 cleanup_xfree = make_cleanup (xfree, object_file);
573 make_cleanup (xfree, source_file);
574 cleanup_unlink = make_cleanup (cleanup_unlink_file, object_file);
575 make_cleanup (cleanup_unlink_file, source_file);
576 compile_module = compile_object_load (object_file, source_file);
577 discard_cleanups (cleanup_unlink);
578 do_cleanups (cleanup_xfree);
579 compile_object_run (compile_module);
580 }
581 }
582
583 /* See compile/compile-internal.h. */
584
585 char *
586 compile_register_name_mangled (struct gdbarch *gdbarch, int regnum)
587 {
588 const char *regname = gdbarch_register_name (gdbarch, regnum);
589
590 return xstrprintf ("__%s", regname);
591 }
592
593 /* See compile/compile-internal.h. */
594
595 int
596 compile_register_name_demangle (struct gdbarch *gdbarch,
597 const char *regname)
598 {
599 int regnum;
600
601 if (regname[0] != '_' || regname[1] != '_')
602 error (_("Invalid register name \"%s\"."), regname);
603 regname += 2;
604
605 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
606 if (strcmp (regname, gdbarch_register_name (gdbarch, regnum)) == 0)
607 return regnum;
608
609 error (_("Cannot find gdbarch register \"%s\"."), regname);
610 }
611
612 extern initialize_file_ftype _initialize_compile;
613
614 void
615 _initialize_compile (void)
616 {
617 struct cmd_list_element *c = NULL;
618
619 add_prefix_cmd ("compile", class_obscure, compile_command,
620 _("\
621 Command to compile source code and inject it into the inferior."),
622 &compile_command_list, "compile ", 1, &cmdlist);
623 add_com_alias ("expression", "compile", class_obscure, 0);
624
625 add_cmd ("code", class_obscure, compile_code_command,
626 _("\
627 Compile, inject, and execute code.\n\
628 \n\
629 Usage: compile code [-r|-raw] [--] [CODE]\n\
630 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping.\n\
631 --: Do not parse any options beyond this delimiter. All text to the\n\
632 right will be treated as source code.\n\
633 \n\
634 The source code may be specified as a simple one line expression, e.g.:\n\
635 \n\
636 compile code printf(\"Hello world\\n\");\n\
637 \n\
638 Alternatively, you can type the source code interactively.\n\
639 You can invoke this mode when no argument is given to the command\n\
640 (i.e.,\"compile code\" is typed with nothing after it). An\n\
641 interactive prompt will be shown allowing you to enter multiple\n\
642 lines of source code. Type a line containing \"end\" to indicate\n\
643 the end of the source code."),
644 &compile_command_list);
645
646 c = add_cmd ("file", class_obscure, compile_file_command,
647 _("\
648 Evaluate a file containing source code.\n\
649 \n\
650 Usage: compile file [-r|-raw] [filename]\n\
651 -r|-raw: Suppress automatic 'void _gdb_expr () { CODE }' wrapping."),
652 &compile_command_list);
653 set_cmd_completer (c, filename_completer);
654
655 add_setshow_boolean_cmd ("compile", class_maintenance, &compile_debug, _("\
656 Set compile command debugging."), _("\
657 Show compile command debugging."), _("\
658 When on, compile command debugging is enabled."),
659 NULL, show_compile_debug,
660 &setdebuglist, &showdebuglist);
661
662 add_setshow_string_cmd ("compile-args", class_support,
663 &compile_args,
664 _("Set compile command GCC command-line arguments"),
665 _("Show compile command GCC command-line arguments"),
666 _("\
667 Use options like -I (include file directory) or ABI settings.\n\
668 String quoting is parsed like in shell, for example:\n\
669 -mno-align-double \"-I/dir with a space/include\""),
670 set_compile_args, show_compile_args, &setlist, &showlist);
671
672 /* Override flags possibly coming from DW_AT_producer. */
673 compile_args = xstrdup ("-O0 -gdwarf-4"
674 /* We use -fPIE Otherwise GDB would need to reserve space large enough for
675 any object file in the inferior in advance to get the final address when
676 to link the object file to and additionally the default system linker
677 script would need to be modified so that one can specify there the
678 absolute target address.
679 -fPIC is not used at is would require from GDB to generate .got. */
680 " -fPIE"
681 /* We don't want warnings. */
682 " -w"
683 /* Override CU's possible -fstack-protector-strong. */
684 " -fno-stack-protector"
685 );
686 set_compile_args (compile_args, 0, NULL);
687 }
688