]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/compile/compile.c
Update year range in copyright notice of all files owned by the GDB project.
[thirdparty/binutils-gdb.git] / gdb / compile / compile.c
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
41 \f
42
43 /* Initial filename for temporary files. */
44
45 #define TMP_PREFIX "/tmp/gdbobj-"
46
47 /* Hold "compile" commands. */
48
49 static struct cmd_list_element *compile_command_list;
50
51 /* Debug flag for "compile" commands. */
52
53 int compile_debug;
54
55 /* Implement "show debug compile". */
56
57 static void
58 show_compile_debug (struct ui_file *file, int from_tty,
59 struct cmd_list_element *c, const char *value)
60 {
61 fprintf_filtered (file, _("Compile debugging is %s.\n"), value);
62 }
63
64 \f
65
66 /* Check *ARG for a "-raw" or "-r" argument. Return 0 if not seen.
67 Return 1 if seen and update *ARG. */
68
69 static int
70 check_raw_argument (char **arg)
71 {
72 *arg = skip_spaces (*arg);
73
74 if (arg != NULL
75 && (check_for_argument (arg, "-raw", sizeof ("-raw") - 1)
76 || check_for_argument (arg, "-r", sizeof ("-r") - 1)))
77 return 1;
78 return 0;
79 }
80
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. */
84
85 static void
86 compile_file_command (char *arg, int from_tty)
87 {
88 enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;
89 char *buffer;
90 struct cleanup *cleanup;
91
92 cleanup = make_cleanup_restore_integer (&interpreter_async);
93 interpreter_async = 0;
94
95 /* Check the user did not just <enter> after command. */
96 if (arg == NULL)
97 error (_("You must provide a filename for this command."));
98
99 /* Check if a raw (-r|-raw) argument is provided. */
100 if (arg != NULL && check_raw_argument (&arg))
101 {
102 scope = COMPILE_I_RAW_SCOPE;
103 arg = skip_spaces (arg);
104 }
105
106 /* After processing arguments, check there is a filename at the end
107 of the command. */
108 if (arg[0] == '\0')
109 error (_("You must provide a filename with the raw option set."));
110
111 if (arg[0] == '-')
112 error (_("Unknown argument specified."));
113
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);
121 }
122
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. */
127
128 static void
129 compile_code_command (char *arg, int from_tty)
130 {
131 struct cleanup *cleanup;
132 enum compile_i_scope_types scope = COMPILE_I_SIMPLE_SCOPE;
133
134 cleanup = make_cleanup_restore_integer (&interpreter_async);
135 interpreter_async = 0;
136
137 if (arg != NULL && check_raw_argument (&arg))
138 {
139 scope = COMPILE_I_RAW_SCOPE;
140 arg = skip_spaces (arg);
141 }
142
143 arg = skip_spaces (arg);
144
145 if (arg != NULL && !check_for_argument (&arg, "--", sizeof ("--") - 1))
146 {
147 if (arg[0] == '-')
148 error (_("Unknown argument specified."));
149 }
150
151 if (arg && *arg)
152 eval_compile_command (NULL, arg, scope);
153 else
154 {
155 struct command_line *l = get_command_line (compile_control, "");
156
157 make_cleanup_free_command_lines (&l);
158 l->control_u.compile.scope = scope;
159 execute_control_command_untraced (l);
160 }
161
162 do_cleanups (cleanup);
163 }
164
165 /* A cleanup function to remove a directory and all its contents. */
166
167 static void
168 do_rmdir (void *arg)
169 {
170 const char *dir = arg;
171 char *zap;
172
173 gdb_assert (strncmp (dir, TMP_PREFIX, strlen (TMP_PREFIX)) == 0);
174 zap = concat ("rm -rf ", dir, (char *) NULL);
175 system (zap);
176 }
177
178 /* Return the name of the temporary directory to use for .o files, and
179 arrange for the directory to be removed at shutdown. */
180
181 static const char *
182 get_compile_file_tempdir (void)
183 {
184 static char *tempdir_name;
185
186 #define TEMPLATE TMP_PREFIX "XXXXXX"
187 char tname[sizeof (TEMPLATE)];
188
189 if (tempdir_name != NULL)
190 return tempdir_name;
191
192 strcpy (tname, TEMPLATE);
193 #undef TEMPLATE
194 #ifdef HAVE_MKDTEMP
195 tempdir_name = mkdtemp (tname);
196 #else
197 error (_("Command not supported on this host."));
198 #endif
199 if (tempdir_name == NULL)
200 perror_with_name (_("Could not make temporary directory"));
201
202 tempdir_name = xstrdup (tempdir_name);
203 make_final_cleanup (do_rmdir, tempdir_name);
204 return tempdir_name;
205 }
206
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. */
209
210 static void
211 get_new_file_names (char **source_file, char **object_file)
212 {
213 static int seq;
214 const char *dir = get_compile_file_tempdir ();
215
216 ++seq;
217 *source_file = xstrprintf ("%s%sout%d.c", dir, SLASH_STRING, seq);
218 *object_file = xstrprintf ("%s%sout%d.o", dir, SLASH_STRING, seq);
219 }
220
221 /* Get the block and PC at which to evaluate an expression. */
222
223 static const struct block *
224 get_expr_block_and_pc (CORE_ADDR *pc)
225 {
226 const struct block *block = get_selected_block (pc);
227
228 if (block == NULL)
229 {
230 struct symtab_and_line cursal = get_current_source_symtab_and_line ();
231
232 if (cursal.symtab)
233 block = BLOCKVECTOR_BLOCK (SYMTAB_BLOCKVECTOR (cursal.symtab),
234 STATIC_BLOCK);
235 if (block != NULL)
236 *pc = BLOCK_START (block);
237 }
238 else
239 *pc = BLOCK_START (block);
240
241 return block;
242 }
243
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. */
247
248 static void
249 build_argc_argv (const char *s, int *argcp, char ***argvp)
250 {
251 *argvp = gdb_buildargv (s);
252 *argcp = countargv (*argvp);
253 }
254
255 /* String for 'set compile-args' and 'show compile-args'. */
256 static char *compile_args;
257
258 /* Parsed form of COMPILE_ARGS. COMPILE_ARGS_ARGV is NULL terminated. */
259 static int compile_args_argc;
260 static char **compile_args_argv;
261
262 /* Implement 'set compile-args'. */
263
264 static void
265 set_compile_args (char *args, int from_tty, struct cmd_list_element *c)
266 {
267 freeargv (compile_args_argv);
268 build_argc_argv (compile_args, &compile_args_argc, &compile_args_argv);
269 }
270
271 /* Implement 'show compile-args'. */
272
273 static void
274 show_compile_args (struct ui_file *file, int from_tty,
275 struct cmd_list_element *c, const char *value)
276 {
277 fprintf_filtered (file, _("Compile command command-line arguments "
278 "are \"%s\".\n"),
279 value);
280 }
281
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. */
284
285 static void
286 append_args (int *argcp, char ***argvp, int argc, char **argv)
287 {
288 int argi;
289
290 *argvp = xrealloc (*argvp, (*argcp + argc + 1) * sizeof (**argvp));
291
292 for (argi = 0; argi < argc; argi++)
293 (*argvp)[(*argcp)++] = xstrdup (argv[argi]);
294 (*argvp)[(*argcp)] = NULL;
295 }
296
297 /* Return DW_AT_producer parsed for get_selected_frame () (if any).
298 Return NULL otherwise.
299
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. */
302
303 static const char *
304 get_selected_pc_producer_options (void)
305 {
306 CORE_ADDR pc = get_frame_pc (get_selected_frame (NULL));
307 struct compunit_symtab *symtab = find_pc_compunit_symtab (pc);
308 const char *cs;
309
310 if (symtab == NULL || symtab->producer == NULL
311 || strncmp (symtab->producer, "GNU ", strlen ("GNU ")) != 0)
312 return NULL;
313
314 cs = symtab->producer;
315 while (*cs != 0 && *cs != '-')
316 cs = skip_spaces_const (skip_to_space_const (cs));
317 if (*cs != '-')
318 return NULL;
319 return cs;
320 }
321
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. */
325
326 static void
327 get_args (const struct compile_instance *compiler, struct gdbarch *gdbarch,
328 int *argcp, char ***argvp)
329 {
330 const char *cs_producer_options;
331 int argc_compiler;
332 char **argv_compiler;
333
334 build_argc_argv (gdbarch_gcc_target_options (gdbarch),
335 argcp, argvp);
336
337 cs_producer_options = get_selected_pc_producer_options ();
338 if (cs_producer_options != NULL)
339 {
340 int argc_producer;
341 char **argv_producer;
342
343 build_argc_argv (cs_producer_options, &argc_producer, &argv_producer);
344 append_args (argcp, argvp, argc_producer, argv_producer);
345 freeargv (argv_producer);
346 }
347
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);
352
353 append_args (argcp, argvp, compile_args_argc, compile_args_argv);
354 }
355
356 /* A cleanup function to destroy a gdb_gcc_instance. */
357
358 static void
359 cleanup_compile_instance (void *arg)
360 {
361 struct compile_instance *inst = arg;
362
363 inst->destroy (inst);
364 }
365
366 /* A cleanup function to unlink a file. */
367
368 static void
369 cleanup_unlink_file (void *arg)
370 {
371 const char *filename = arg;
372
373 unlink (filename);
374 }
375
376 /* A helper function suitable for use as the "print_callback" in the
377 compiler object. */
378
379 static void
380 print_callback (void *ignore, const char *message)
381 {
382 fputs_filtered (message, gdb_stderr);
383 }
384
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. */
389
390 static char *
391 compile_to_object (struct command_line *cmd, char *cmd_string,
392 enum compile_i_scope_types scope,
393 char **source_filep)
394 {
395 char *code;
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;
401 int argc;
402 char **argv;
403 int ok;
404 FILE *src;
405 struct gdbarch *gdbarch = get_current_arch ();
406 const char *os_rx;
407 const char *arch_rx;
408 char *triplet_rx;
409 char *error_message;
410
411 if (!target_has_execution)
412 error (_("The program must be running for the compile command to "\
413 "work."));
414
415 expr_block = get_expr_block_and_pc (&trash_pc);
416 expr_pc = get_frame_address_in_block (get_selected_frame (NULL));
417
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);
423
424 compiler->fe->ops->set_print_callback (compiler->fe, print_callback, NULL);
425
426 compiler->scope = scope;
427 compiler->block = expr_block;
428
429 /* From the provided expression, build a scope to pass to the
430 compiler. */
431 if (cmd != NULL)
432 {
433 struct ui_file *stream = mem_fileopen ();
434 struct command_line *iter;
435
436 make_cleanup_ui_file_delete (stream);
437 for (iter = cmd->body_list[0]; iter; iter = iter->next)
438 {
439 fputs_unfiltered (iter->line, stream);
440 fputs_unfiltered ("\n", stream);
441 }
442
443 code = ui_file_xstrdup (stream, NULL);
444 make_cleanup (xfree, code);
445 }
446 else if (cmd_string != NULL)
447 code = cmd_string;
448 else
449 error (_("Neither a simple expression, or a multi-line specified."));
450
451 code = current_language->la_compute_program (compiler, code, gdbarch,
452 expr_block, expr_pc);
453 make_cleanup (xfree, code);
454 if (compile_debug)
455 fprintf_unfiltered (gdb_stdout, "debug output:\n\n%s", code);
456
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);
461
462 /* Set compiler command-line arguments. */
463 get_args (compiler, gdbarch, &argc, &argv);
464 make_cleanup_freeargv (argv);
465
466 error_message = compiler->fe->ops->set_arguments (compiler->fe, triplet_rx,
467 argc, argv);
468 if (error_message != NULL)
469 {
470 make_cleanup (xfree, error_message);
471 error ("%s", error_message);
472 }
473
474 if (compile_debug)
475 {
476 int argi;
477
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",
481 argi, argv[argi]);
482 }
483
484 get_new_file_names (&source_file, &object_file);
485 inner_cleanup = make_cleanup (xfree, source_file);
486 make_cleanup (xfree, object_file);
487
488 src = gdb_fopen_cloexec (source_file, "w");
489 if (src == NULL)
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"));
494 fclose (src);
495
496 if (compile_debug)
497 fprintf_unfiltered (gdb_stdout, "source file produced: %s\n\n",
498 source_file);
499
500 /* Call the compiler and start the compilation process. */
501 compiler->fe->ops->set_source_file (compiler->fe, source_file);
502
503 if (!compiler->fe->ops->compile (compiler->fe, object_file,
504 compile_debug))
505 error (_("Compilation failed."));
506
507 if (compile_debug)
508 fprintf_unfiltered (gdb_stdout, "object file produced: %s\n\n",
509 object_file);
510
511 discard_cleanups (inner_cleanup);
512 do_cleanups (cleanup);
513 *source_filep = source_file;
514 return object_file;
515 }
516
517 /* The "compile" prefix command. */
518
519 static void
520 compile_command (char *args, int from_tty)
521 {
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);
525 }
526
527 /* See compile.h. */
528
529 void
530 eval_compile_command (struct command_line *cmd, char *cmd_string,
531 enum compile_i_scope_types scope)
532 {
533 char *object_file, *source_file;
534
535 object_file = compile_to_object (cmd, cmd_string, scope, &source_file);
536 if (object_file != NULL)
537 {
538 struct cleanup *cleanup_xfree, *cleanup_unlink;
539 struct compile_module *compile_module;
540
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);
549 }
550 }
551
552 /* See compile/compile-internal.h. */
553
554 char *
555 compile_register_name_mangled (struct gdbarch *gdbarch, int regnum)
556 {
557 const char *regname = gdbarch_register_name (gdbarch, regnum);
558
559 return xstrprintf ("__%s", regname);
560 }
561
562 /* See compile/compile-internal.h. */
563
564 int
565 compile_register_name_demangle (struct gdbarch *gdbarch,
566 const char *regname)
567 {
568 int regnum;
569
570 if (regname[0] != '_' || regname[1] != '_')
571 error (_("Invalid register name \"%s\"."), regname);
572 regname += 2;
573
574 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
575 if (strcmp (regname, gdbarch_register_name (gdbarch, regnum)) == 0)
576 return regnum;
577
578 error (_("Cannot find gdbarch register \"%s\"."), regname);
579 }
580
581 extern initialize_file_ftype _initialize_compile;
582
583 void
584 _initialize_compile (void)
585 {
586 struct cmd_list_element *c = NULL;
587
588 add_prefix_cmd ("compile", class_obscure, compile_command,
589 _("\
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);
593
594 add_cmd ("code", class_obscure, compile_code_command,
595 _("\
596 Compile, inject, and execute code.\n\
597 \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\
602 \n\
603 The source code may be specified as a simple one line expression, e.g.:\n\
604 \n\
605 compile code printf(\"Hello world\\n\");\n\
606 \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);
614
615 c = add_cmd ("file", class_obscure, compile_file_command,
616 _("\
617 Evaluate a file containing source code.\n\
618 \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);
623
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);
630
631 add_setshow_string_cmd ("compile-args", class_support,
632 &compile_args,
633 _("Set compile command GCC command-line arguments"),
634 _("Show compile command GCC command-line arguments"),
635 _("\
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);
640
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. */
648 " -fPIC"
649 /* We don't want warnings. */
650 " -w"
651 /* Override CU's possible -fstack-protector-strong. */
652 " -fno-stack-protector"
653 );
654 set_compile_args (compile_args, 0, NULL);
655 }