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