gdb/
[external/binutils.git] / gdb / jit.c
1 /* Handle JIT code generation in the inferior for GDB, the GNU Debugger.
2
3    Copyright (C) 2009, 2010, 2011 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
22 #include "jit.h"
23 #include "jit-reader.h"
24 #include "breakpoint.h"
25 #include "command.h"
26 #include "gdbcmd.h"
27 #include "gdbcore.h"
28 #include "inferior.h"
29 #include "observer.h"
30 #include "objfiles.h"
31 #include "symfile.h"
32 #include "symtab.h"
33 #include "target.h"
34 #include "gdb-dlfcn.h"
35 #include "gdb_stat.h"
36
37 static const char *jit_reader_dir = NULL;
38
39 static const struct objfile_data *jit_objfile_data;
40
41 static const char *const jit_break_name = "__jit_debug_register_code";
42
43 static const char *const jit_descriptor_name = "__jit_debug_descriptor";
44
45 static const struct inferior_data *jit_inferior_data = NULL;
46
47 static void jit_inferior_init (struct gdbarch *gdbarch);
48
49 /* Non-zero if we want to see trace of jit level stuff.  */
50
51 static int jit_debug = 0;
52
53 static void
54 show_jit_debug (struct ui_file *file, int from_tty,
55                 struct cmd_list_element *c, const char *value)
56 {
57   fprintf_filtered (file, _("JIT debugging is %s.\n"), value);
58 }
59
60 struct target_buffer
61 {
62   CORE_ADDR base;
63   ULONGEST size;
64 };
65
66 /* Openning the file is a no-op.  */
67
68 static void *
69 mem_bfd_iovec_open (struct bfd *abfd, void *open_closure)
70 {
71   return open_closure;
72 }
73
74 /* Closing the file is just freeing the base/size pair on our side.  */
75
76 static int
77 mem_bfd_iovec_close (struct bfd *abfd, void *stream)
78 {
79   xfree (stream);
80   return 1;
81 }
82
83 /* For reading the file, we just need to pass through to target_read_memory and
84    fix up the arguments and return values.  */
85
86 static file_ptr
87 mem_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
88                      file_ptr nbytes, file_ptr offset)
89 {
90   int err;
91   struct target_buffer *buffer = (struct target_buffer *) stream;
92
93   /* If this read will read all of the file, limit it to just the rest.  */
94   if (offset + nbytes > buffer->size)
95     nbytes = buffer->size - offset;
96
97   /* If there are no more bytes left, we've reached EOF.  */
98   if (nbytes == 0)
99     return 0;
100
101   err = target_read_memory (buffer->base + offset, (gdb_byte *) buf, nbytes);
102   if (err)
103     return -1;
104
105   return nbytes;
106 }
107
108 /* For statting the file, we only support the st_size attribute.  */
109
110 static int
111 mem_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
112 {
113   struct target_buffer *buffer = (struct target_buffer*) stream;
114
115   sb->st_size = buffer->size;
116   return 0;
117 }
118
119 /* One reader that has been loaded successfully, and can potentially be used to
120    parse debug info.  */
121
122 static struct jit_reader
123 {
124   struct gdb_reader_funcs *functions;
125   void *handle;
126 } *loaded_jit_reader = NULL;
127
128 typedef struct gdb_reader_funcs * (reader_init_fn_type) (void);
129 static const char *reader_init_fn_sym = "gdb_init_reader";
130
131 /* Try to load FILE_NAME as a JIT debug info reader.  */
132
133 static struct jit_reader *
134 jit_reader_load (const char *file_name)
135 {
136   void *so;
137   reader_init_fn_type *init_fn;
138   struct jit_reader *new_reader = NULL;
139   struct gdb_reader_funcs *funcs = NULL;
140   struct cleanup *old_cleanups;
141
142   if (jit_debug)
143     fprintf_unfiltered (gdb_stdlog, _("Opening shared object %s.\n"),
144                         file_name);
145   so = gdb_dlopen (file_name);
146   old_cleanups = make_cleanup_dlclose (so);
147
148   init_fn = gdb_dlsym (so, reader_init_fn_sym);
149   if (!init_fn)
150     error (_("Could not locate initialization function: %s."),
151           reader_init_fn_sym);
152
153   if (gdb_dlsym (so, "plugin_is_GPL_compatible") == NULL)
154     error (_("Reader not GPL compatible."));
155
156   funcs = init_fn ();
157   if (funcs->reader_version != GDB_READER_INTERFACE_VERSION)
158     error (_("Reader version does not match GDB version."));
159
160   new_reader = XZALLOC (struct jit_reader);
161   new_reader->functions = funcs;
162   new_reader->handle = so;
163
164   discard_cleanups (old_cleanups);
165   return new_reader;
166 }
167
168 /* Provides the jit-reader-load command.  */
169
170 static void
171 jit_reader_load_command (char *args, int from_tty)
172 {
173   char *so_name;
174   int len;
175   struct cleanup *prev_cleanup;
176
177   if (args == NULL)
178     error (_("No reader name provided."));
179
180   if (loaded_jit_reader != NULL)
181     error (_("JIT reader already loaded.  Run jit-reader-unload first."));
182
183   so_name = xstrprintf ("%s/%s", jit_reader_dir, args);
184   prev_cleanup = make_cleanup (xfree, so_name);
185
186   loaded_jit_reader = jit_reader_load (so_name);
187   do_cleanups (prev_cleanup);
188 }
189
190 /* Provides the jit-reader-unload command.  */
191
192 static void
193 jit_reader_unload_command (char *args, int from_tty)
194 {
195   if (!loaded_jit_reader)
196     error (_("No JIT reader loaded."));
197
198   loaded_jit_reader->functions->destroy (loaded_jit_reader->functions);
199
200   gdb_dlclose (loaded_jit_reader->handle);
201   xfree (loaded_jit_reader);
202   loaded_jit_reader = NULL;
203 }
204
205 /* Open a BFD from the target's memory.  */
206
207 static struct bfd *
208 bfd_open_from_target_memory (CORE_ADDR addr, ULONGEST size, char *target)
209 {
210   const char *filename = xstrdup ("<in-memory>");
211   struct target_buffer *buffer = xmalloc (sizeof (struct target_buffer));
212
213   buffer->base = addr;
214   buffer->size = size;
215   return bfd_openr_iovec (filename, target,
216                           mem_bfd_iovec_open,
217                           buffer,
218                           mem_bfd_iovec_pread,
219                           mem_bfd_iovec_close,
220                           mem_bfd_iovec_stat);
221 }
222
223 /* Per-inferior structure recording the addresses in the inferior.  */
224
225 struct jit_inferior_data
226 {
227   CORE_ADDR breakpoint_addr;  /* &__jit_debug_register_code()  */
228   CORE_ADDR descriptor_addr;  /* &__jit_debug_descriptor  */
229 };
230
231 /* Return jit_inferior_data for current inferior.  Allocate if not already
232    present.  */
233
234 static struct jit_inferior_data *
235 get_jit_inferior_data (void)
236 {
237   struct inferior *inf;
238   struct jit_inferior_data *inf_data;
239
240   inf = current_inferior ();
241   inf_data = inferior_data (inf, jit_inferior_data);
242   if (inf_data == NULL)
243     {
244       inf_data = XZALLOC (struct jit_inferior_data);
245       set_inferior_data (inf, jit_inferior_data, inf_data);
246     }
247
248   return inf_data;
249 }
250
251 static void
252 jit_inferior_data_cleanup (struct inferior *inf, void *arg)
253 {
254   xfree (arg);
255 }
256
257 /* Helper function for reading the global JIT descriptor from remote
258    memory.  */
259
260 static void
261 jit_read_descriptor (struct gdbarch *gdbarch,
262                      struct jit_descriptor *descriptor,
263                      CORE_ADDR descriptor_addr)
264 {
265   int err;
266   struct type *ptr_type;
267   int ptr_size;
268   int desc_size;
269   gdb_byte *desc_buf;
270   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
271
272   /* Figure out how big the descriptor is on the remote and how to read it.  */
273   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
274   ptr_size = TYPE_LENGTH (ptr_type);
275   desc_size = 8 + 2 * ptr_size;  /* Two 32-bit ints and two pointers.  */
276   desc_buf = alloca (desc_size);
277
278   /* Read the descriptor.  */
279   err = target_read_memory (descriptor_addr, desc_buf, desc_size);
280   if (err)
281     error (_("Unable to read JIT descriptor from remote memory!"));
282
283   /* Fix the endianness to match the host.  */
284   descriptor->version = extract_unsigned_integer (&desc_buf[0], 4, byte_order);
285   descriptor->action_flag =
286       extract_unsigned_integer (&desc_buf[4], 4, byte_order);
287   descriptor->relevant_entry = extract_typed_address (&desc_buf[8], ptr_type);
288   descriptor->first_entry =
289       extract_typed_address (&desc_buf[8 + ptr_size], ptr_type);
290 }
291
292 /* Helper function for reading a JITed code entry from remote memory.  */
293
294 static void
295 jit_read_code_entry (struct gdbarch *gdbarch,
296                      CORE_ADDR code_addr, struct jit_code_entry *code_entry)
297 {
298   int err, off;
299   struct type *ptr_type;
300   int ptr_size;
301   int entry_size;
302   int align_bytes;
303   gdb_byte *entry_buf;
304   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
305
306   /* Figure out how big the entry is on the remote and how to read it.  */
307   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
308   ptr_size = TYPE_LENGTH (ptr_type);
309   entry_size = 3 * ptr_size + 8;  /* Three pointers and one 64-bit int.  */
310   entry_buf = alloca (entry_size);
311
312   /* Read the entry.  */
313   err = target_read_memory (code_addr, entry_buf, entry_size);
314   if (err)
315     error (_("Unable to read JIT code entry from remote memory!"));
316
317   /* Fix the endianness to match the host.  */
318   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
319   code_entry->next_entry = extract_typed_address (&entry_buf[0], ptr_type);
320   code_entry->prev_entry =
321       extract_typed_address (&entry_buf[ptr_size], ptr_type);
322   code_entry->symfile_addr =
323       extract_typed_address (&entry_buf[2 * ptr_size], ptr_type);
324
325   align_bytes = gdbarch_long_long_align_bit (gdbarch) / 8;
326   off = 3 * ptr_size;
327   off = (off + (align_bytes - 1)) & ~(align_bytes - 1);
328
329   code_entry->symfile_size =
330       extract_unsigned_integer (&entry_buf[off], 8, byte_order);
331 }
332
333 /* This function registers code associated with a JIT code entry.  It uses the
334    pointer and size pair in the entry to read the symbol file from the remote
335    and then calls symbol_file_add_from_local_memory to add it as though it were
336    a symbol file added by the user.  */
337
338 static void
339 jit_register_code (struct gdbarch *gdbarch,
340                    CORE_ADDR entry_addr, struct jit_code_entry *code_entry)
341 {
342   bfd *nbfd;
343   struct section_addr_info *sai;
344   struct bfd_section *sec;
345   struct objfile *objfile;
346   struct cleanup *old_cleanups;
347   int i;
348   const struct bfd_arch_info *b;
349   CORE_ADDR *entry_addr_ptr;
350
351   if (jit_debug)
352     fprintf_unfiltered (gdb_stdlog,
353                         "jit_register_code, symfile_addr = %s, "
354                         "symfile_size = %s\n",
355                         paddress (gdbarch, code_entry->symfile_addr),
356                         pulongest (code_entry->symfile_size));
357
358   nbfd = bfd_open_from_target_memory (code_entry->symfile_addr,
359                                       code_entry->symfile_size, gnutarget);
360   if (nbfd == NULL)
361     {
362       puts_unfiltered (_("Error opening JITed symbol file, ignoring it.\n"));
363       return;
364     }
365
366   /* Check the format.  NOTE: This initializes important data that GDB uses!
367      We would segfault later without this line.  */
368   if (!bfd_check_format (nbfd, bfd_object))
369     {
370       printf_unfiltered (_("\
371 JITed symbol file is not an object file, ignoring it.\n"));
372       bfd_close (nbfd);
373       return;
374     }
375
376   /* Check bfd arch.  */
377   b = gdbarch_bfd_arch_info (gdbarch);
378   if (b->compatible (b, bfd_get_arch_info (nbfd)) != b)
379     warning (_("JITed object file architecture %s is not compatible "
380                "with target architecture %s."), bfd_get_arch_info
381              (nbfd)->printable_name, b->printable_name);
382
383   /* Read the section address information out of the symbol file.  Since the
384      file is generated by the JIT at runtime, it should all of the absolute
385      addresses that we care about.  */
386   sai = alloc_section_addr_info (bfd_count_sections (nbfd));
387   old_cleanups = make_cleanup_free_section_addr_info (sai);
388   i = 0;
389   for (sec = nbfd->sections; sec != NULL; sec = sec->next)
390     if ((bfd_get_section_flags (nbfd, sec) & (SEC_ALLOC|SEC_LOAD)) != 0)
391       {
392         /* We assume that these virtual addresses are absolute, and do not
393            treat them as offsets.  */
394         sai->other[i].addr = bfd_get_section_vma (nbfd, sec);
395         sai->other[i].name = xstrdup (bfd_get_section_name (nbfd, sec));
396         sai->other[i].sectindex = sec->index;
397         ++i;
398       }
399
400   /* This call takes ownership of NBFD.  It does not take ownership of SAI.  */
401   objfile = symbol_file_add_from_bfd (nbfd, 0, sai, OBJF_SHARED, NULL);
402
403   /* Remember a mapping from entry_addr to objfile.  */
404   entry_addr_ptr = xmalloc (sizeof (CORE_ADDR));
405   *entry_addr_ptr = entry_addr;
406   set_objfile_data (objfile, jit_objfile_data, entry_addr_ptr);
407
408   do_cleanups (old_cleanups);
409 }
410
411 /* This function unregisters JITed code and frees the corresponding
412    objfile.  */
413
414 static void
415 jit_unregister_code (struct objfile *objfile)
416 {
417   free_objfile (objfile);
418 }
419
420 /* Look up the objfile with this code entry address.  */
421
422 static struct objfile *
423 jit_find_objf_with_entry_addr (CORE_ADDR entry_addr)
424 {
425   struct objfile *objf;
426   CORE_ADDR *objf_entry_addr;
427
428   ALL_OBJFILES (objf)
429     {
430       objf_entry_addr = (CORE_ADDR *) objfile_data (objf, jit_objfile_data);
431       if (objf_entry_addr != NULL && *objf_entry_addr == entry_addr)
432         return objf;
433     }
434   return NULL;
435 }
436
437 /* (Re-)Initialize the jit breakpoint if necessary.
438    Return 0 on success.  */
439
440 static int
441 jit_breakpoint_re_set_internal (struct gdbarch *gdbarch,
442                                 struct jit_inferior_data *inf_data)
443 {
444   if (inf_data->breakpoint_addr == 0)
445     {
446       struct minimal_symbol *reg_symbol;
447
448       /* Lookup the registration symbol.  If it is missing, then we assume
449          we are not attached to a JIT.  */
450       reg_symbol = lookup_minimal_symbol (jit_break_name, NULL, NULL);
451       if (reg_symbol == NULL)
452         return 1;
453       inf_data->breakpoint_addr = SYMBOL_VALUE_ADDRESS (reg_symbol);
454       if (inf_data->breakpoint_addr == 0)
455         return 2;
456
457       /* If we have not read the jit descriptor yet (e.g. because the JITer
458          itself is in a shared library which just got loaded), do so now.  */
459       if (inf_data->descriptor_addr == 0)
460         jit_inferior_init (gdbarch);
461     }
462   else
463     return 0;
464
465   if (jit_debug)
466     fprintf_unfiltered (gdb_stdlog,
467                         "jit_breakpoint_re_set_internal, "
468                         "breakpoint_addr = %s\n",
469                         paddress (gdbarch, inf_data->breakpoint_addr));
470
471   /* Put a breakpoint in the registration symbol.  */
472   create_jit_event_breakpoint (gdbarch, inf_data->breakpoint_addr);
473
474   return 0;
475 }
476
477 /* Register any already created translations.  */
478
479 static void
480 jit_inferior_init (struct gdbarch *gdbarch)
481 {
482   struct jit_descriptor descriptor;
483   struct jit_code_entry cur_entry;
484   struct jit_inferior_data *inf_data;
485   CORE_ADDR cur_entry_addr;
486
487   if (jit_debug)
488     fprintf_unfiltered (gdb_stdlog, "jit_inferior_init\n");
489
490   inf_data = get_jit_inferior_data ();
491   if (jit_breakpoint_re_set_internal (gdbarch, inf_data) != 0)
492     return;
493
494   if (inf_data->descriptor_addr == 0)
495     {
496       struct minimal_symbol *desc_symbol;
497
498       /* Lookup the descriptor symbol and cache the addr.  If it is
499          missing, we assume we are not attached to a JIT and return early.  */
500       desc_symbol = lookup_minimal_symbol (jit_descriptor_name, NULL, NULL);
501       if (desc_symbol == NULL)
502         return;
503
504       inf_data->descriptor_addr = SYMBOL_VALUE_ADDRESS (desc_symbol);
505       if (inf_data->descriptor_addr == 0)
506         return;
507     }
508
509   if (jit_debug)
510     fprintf_unfiltered (gdb_stdlog,
511                         "jit_inferior_init, descriptor_addr = %s\n",
512                         paddress (gdbarch, inf_data->descriptor_addr));
513
514   /* Read the descriptor so we can check the version number and load
515      any already JITed functions.  */
516   jit_read_descriptor (gdbarch, &descriptor, inf_data->descriptor_addr);
517
518   /* Check that the version number agrees with that we support.  */
519   if (descriptor.version != 1)
520     error (_("Unsupported JIT protocol version in descriptor!"));
521
522   /* If we've attached to a running program, we need to check the descriptor
523      to register any functions that were already generated.  */
524   for (cur_entry_addr = descriptor.first_entry;
525        cur_entry_addr != 0;
526        cur_entry_addr = cur_entry.next_entry)
527     {
528       jit_read_code_entry (gdbarch, cur_entry_addr, &cur_entry);
529
530       /* This hook may be called many times during setup, so make sure we don't
531          add the same symbol file twice.  */
532       if (jit_find_objf_with_entry_addr (cur_entry_addr) != NULL)
533         continue;
534
535       jit_register_code (gdbarch, cur_entry_addr, &cur_entry);
536     }
537 }
538
539 /* Exported routine to call when an inferior has been created.  */
540
541 void
542 jit_inferior_created_hook (void)
543 {
544   jit_inferior_init (target_gdbarch);
545 }
546
547 /* Exported routine to call to re-set the jit breakpoints,
548    e.g. when a program is rerun.  */
549
550 void
551 jit_breakpoint_re_set (void)
552 {
553   jit_breakpoint_re_set_internal (target_gdbarch,
554                                   get_jit_inferior_data ());
555 }
556
557 /* Reset inferior_data, so sybols will be looked up again, and jit_breakpoint
558    will be reset.  */
559
560 static void
561 jit_reset_inferior_data_and_breakpoints (void)
562 {
563   struct jit_inferior_data *inf_data;
564
565   /* Force jit_inferior_init to re-lookup of jit symbol addresses.  */
566   inf_data = get_jit_inferior_data ();
567   inf_data->breakpoint_addr = 0;
568   inf_data->descriptor_addr = 0;
569
570   /* Remove any existing JIT breakpoint(s).  */
571   remove_jit_event_breakpoints ();
572
573   jit_inferior_init (target_gdbarch);
574 }
575
576 /* Wrapper to match the observer function pointer prototype.  */
577
578 static void
579 jit_inferior_created_observer (struct target_ops *objfile, int from_tty)
580 {
581   jit_reset_inferior_data_and_breakpoints ();
582 }
583
584 /* This function cleans up any code entries left over when the
585    inferior exits.  We get left over code when the inferior exits
586    without unregistering its code, for example when it crashes.  */
587
588 static void
589 jit_inferior_exit_hook (struct inferior *inf)
590 {
591   struct objfile *objf;
592   struct objfile *temp;
593
594   ALL_OBJFILES_SAFE (objf, temp)
595     if (objfile_data (objf, jit_objfile_data) != NULL)
596       jit_unregister_code (objf);
597 }
598
599 static void
600 jit_executable_changed_observer (void)
601 {
602   jit_reset_inferior_data_and_breakpoints ();
603 }
604
605 void
606 jit_event_handler (struct gdbarch *gdbarch)
607 {
608   struct jit_descriptor descriptor;
609   struct jit_code_entry code_entry;
610   CORE_ADDR entry_addr;
611   struct objfile *objf;
612
613   /* Read the descriptor from remote memory.  */
614   jit_read_descriptor (gdbarch, &descriptor,
615                        get_jit_inferior_data ()->descriptor_addr);
616   entry_addr = descriptor.relevant_entry;
617
618   /* Do the corresponding action.  */
619   switch (descriptor.action_flag)
620     {
621     case JIT_NOACTION:
622       break;
623     case JIT_REGISTER:
624       jit_read_code_entry (gdbarch, entry_addr, &code_entry);
625       jit_register_code (gdbarch, entry_addr, &code_entry);
626       break;
627     case JIT_UNREGISTER:
628       objf = jit_find_objf_with_entry_addr (entry_addr);
629       if (objf == NULL)
630         printf_unfiltered (_("Unable to find JITed code "
631                              "entry at address: %s\n"),
632                            paddress (gdbarch, entry_addr));
633       else
634         jit_unregister_code (objf);
635
636       break;
637     default:
638       error (_("Unknown action_flag value in JIT descriptor!"));
639       break;
640     }
641 }
642
643 /* Provide a prototype to silence -Wmissing-prototypes.  */
644
645 extern void _initialize_jit (void);
646
647 void
648 _initialize_jit (void)
649 {
650   jit_reader_dir = relocate_gdb_directory (JIT_READER_DIR,
651                                            JIT_READER_DIR_RELOCATABLE);
652   add_setshow_zinteger_cmd ("jit", class_maintenance, &jit_debug,
653                             _("Set JIT debugging."),
654                             _("Show JIT debugging."),
655                             _("When non-zero, JIT debugging is enabled."),
656                             NULL,
657                             show_jit_debug,
658                             &setdebuglist, &showdebuglist);
659
660   observer_attach_inferior_created (jit_inferior_created_observer);
661   observer_attach_inferior_exit (jit_inferior_exit_hook);
662   observer_attach_executable_changed (jit_executable_changed_observer);
663   jit_objfile_data = register_objfile_data ();
664   jit_inferior_data =
665     register_inferior_data_with_cleanup (jit_inferior_data_cleanup);
666   if (is_dl_available ())
667     {
668       add_com ("jit-reader-load", no_class, jit_reader_load_command, _("\
669 Load FILE as debug info reader and unwinder for JIT compiled code.\n\
670 Usage: jit-reader-load FILE\n\
671 Try to load file FILE as a debug info reader (and unwinder) for\n\
672 JIT compiled code.  The file is loaded from " JIT_READER_DIR ",\n\
673 relocated relative to the GDB executable if required."));
674       add_com ("jit-reader-unload", no_class, jit_reader_unload_command, _("\
675 Unload the currently loaded JIT debug info reader.\n\
676 Usage: jit-reader-unload FILE\n\n\
677 Do \"help jit-reader-load\" for info on loading debug info readers."));
678     }
679 }