gdb/
[platform/upstream/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 "block.h"
25 #include "breakpoint.h"
26 #include "command.h"
27 #include "dictionary.h"
28 #include "frame-unwind.h"
29 #include "gdbcmd.h"
30 #include "gdbcore.h"
31 #include "inferior.h"
32 #include "observer.h"
33 #include "objfiles.h"
34 #include "regcache.h"
35 #include "symfile.h"
36 #include "symtab.h"
37 #include "target.h"
38 #include "gdb-dlfcn.h"
39 #include "gdb_stat.h"
40 #include "exceptions.h"
41
42 static const char *jit_reader_dir = NULL;
43
44 static const struct objfile_data *jit_objfile_data;
45
46 static const char *const jit_break_name = "__jit_debug_register_code";
47
48 static const char *const jit_descriptor_name = "__jit_debug_descriptor";
49
50 static const struct inferior_data *jit_inferior_data = NULL;
51
52 static void jit_inferior_init (struct gdbarch *gdbarch);
53
54 /* An unwinder is registered for every gdbarch.  This key is used to
55    remember if the unwinder has been registered for a particular
56    gdbarch.  */
57
58 static struct gdbarch_data *jit_gdbarch_data;
59
60 /* Non-zero if we want to see trace of jit level stuff.  */
61
62 static int jit_debug = 0;
63
64 static void
65 show_jit_debug (struct ui_file *file, int from_tty,
66                 struct cmd_list_element *c, const char *value)
67 {
68   fprintf_filtered (file, _("JIT debugging is %s.\n"), value);
69 }
70
71 struct target_buffer
72 {
73   CORE_ADDR base;
74   ULONGEST size;
75 };
76
77 /* Openning the file is a no-op.  */
78
79 static void *
80 mem_bfd_iovec_open (struct bfd *abfd, void *open_closure)
81 {
82   return open_closure;
83 }
84
85 /* Closing the file is just freeing the base/size pair on our side.  */
86
87 static int
88 mem_bfd_iovec_close (struct bfd *abfd, void *stream)
89 {
90   xfree (stream);
91   return 1;
92 }
93
94 /* For reading the file, we just need to pass through to target_read_memory and
95    fix up the arguments and return values.  */
96
97 static file_ptr
98 mem_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
99                      file_ptr nbytes, file_ptr offset)
100 {
101   int err;
102   struct target_buffer *buffer = (struct target_buffer *) stream;
103
104   /* If this read will read all of the file, limit it to just the rest.  */
105   if (offset + nbytes > buffer->size)
106     nbytes = buffer->size - offset;
107
108   /* If there are no more bytes left, we've reached EOF.  */
109   if (nbytes == 0)
110     return 0;
111
112   err = target_read_memory (buffer->base + offset, (gdb_byte *) buf, nbytes);
113   if (err)
114     return -1;
115
116   return nbytes;
117 }
118
119 /* For statting the file, we only support the st_size attribute.  */
120
121 static int
122 mem_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
123 {
124   struct target_buffer *buffer = (struct target_buffer*) stream;
125
126   sb->st_size = buffer->size;
127   return 0;
128 }
129
130 /* One reader that has been loaded successfully, and can potentially be used to
131    parse debug info.  */
132
133 static struct jit_reader
134 {
135   struct gdb_reader_funcs *functions;
136   void *handle;
137 } *loaded_jit_reader = NULL;
138
139 typedef struct gdb_reader_funcs * (reader_init_fn_type) (void);
140 static const char *reader_init_fn_sym = "gdb_init_reader";
141
142 /* Try to load FILE_NAME as a JIT debug info reader.  */
143
144 static struct jit_reader *
145 jit_reader_load (const char *file_name)
146 {
147   void *so;
148   reader_init_fn_type *init_fn;
149   struct jit_reader *new_reader = NULL;
150   struct gdb_reader_funcs *funcs = NULL;
151   struct cleanup *old_cleanups;
152
153   if (jit_debug)
154     fprintf_unfiltered (gdb_stdlog, _("Opening shared object %s.\n"),
155                         file_name);
156   so = gdb_dlopen (file_name);
157   old_cleanups = make_cleanup_dlclose (so);
158
159   init_fn = gdb_dlsym (so, reader_init_fn_sym);
160   if (!init_fn)
161     error (_("Could not locate initialization function: %s."),
162           reader_init_fn_sym);
163
164   if (gdb_dlsym (so, "plugin_is_GPL_compatible") == NULL)
165     error (_("Reader not GPL compatible."));
166
167   funcs = init_fn ();
168   if (funcs->reader_version != GDB_READER_INTERFACE_VERSION)
169     error (_("Reader version does not match GDB version."));
170
171   new_reader = XZALLOC (struct jit_reader);
172   new_reader->functions = funcs;
173   new_reader->handle = so;
174
175   discard_cleanups (old_cleanups);
176   return new_reader;
177 }
178
179 /* Provides the jit-reader-load command.  */
180
181 static void
182 jit_reader_load_command (char *args, int from_tty)
183 {
184   char *so_name;
185   int len;
186   struct cleanup *prev_cleanup;
187
188   if (args == NULL)
189     error (_("No reader name provided."));
190
191   if (loaded_jit_reader != NULL)
192     error (_("JIT reader already loaded.  Run jit-reader-unload first."));
193
194   so_name = xstrprintf ("%s/%s", jit_reader_dir, args);
195   prev_cleanup = make_cleanup (xfree, so_name);
196
197   loaded_jit_reader = jit_reader_load (so_name);
198   do_cleanups (prev_cleanup);
199 }
200
201 /* Provides the jit-reader-unload command.  */
202
203 static void
204 jit_reader_unload_command (char *args, int from_tty)
205 {
206   if (!loaded_jit_reader)
207     error (_("No JIT reader loaded."));
208
209   loaded_jit_reader->functions->destroy (loaded_jit_reader->functions);
210
211   gdb_dlclose (loaded_jit_reader->handle);
212   xfree (loaded_jit_reader);
213   loaded_jit_reader = NULL;
214 }
215
216 /* Open a BFD from the target's memory.  */
217
218 static struct bfd *
219 bfd_open_from_target_memory (CORE_ADDR addr, ULONGEST size, char *target)
220 {
221   const char *filename = xstrdup ("<in-memory>");
222   struct target_buffer *buffer = xmalloc (sizeof (struct target_buffer));
223
224   buffer->base = addr;
225   buffer->size = size;
226   return bfd_openr_iovec (filename, target,
227                           mem_bfd_iovec_open,
228                           buffer,
229                           mem_bfd_iovec_pread,
230                           mem_bfd_iovec_close,
231                           mem_bfd_iovec_stat);
232 }
233
234 /* Per-inferior structure recording the addresses in the inferior.  */
235
236 struct jit_inferior_data
237 {
238   CORE_ADDR breakpoint_addr;  /* &__jit_debug_register_code()  */
239   CORE_ADDR descriptor_addr;  /* &__jit_debug_descriptor  */
240 };
241
242 /* Remember a mapping from entry_addr to objfile.  */
243
244 static void
245 add_objfile_entry (struct objfile *objfile, CORE_ADDR entry)
246 {
247   CORE_ADDR *entry_addr_ptr;
248
249   entry_addr_ptr = xmalloc (sizeof (CORE_ADDR));
250   *entry_addr_ptr = entry;
251   set_objfile_data (objfile, jit_objfile_data, entry_addr_ptr);
252 }
253
254 /* Return jit_inferior_data for current inferior.  Allocate if not already
255    present.  */
256
257 static struct jit_inferior_data *
258 get_jit_inferior_data (void)
259 {
260   struct inferior *inf;
261   struct jit_inferior_data *inf_data;
262
263   inf = current_inferior ();
264   inf_data = inferior_data (inf, jit_inferior_data);
265   if (inf_data == NULL)
266     {
267       inf_data = XZALLOC (struct jit_inferior_data);
268       set_inferior_data (inf, jit_inferior_data, inf_data);
269     }
270
271   return inf_data;
272 }
273
274 static void
275 jit_inferior_data_cleanup (struct inferior *inf, void *arg)
276 {
277   xfree (arg);
278 }
279
280 /* Helper function for reading the global JIT descriptor from remote
281    memory.  */
282
283 static void
284 jit_read_descriptor (struct gdbarch *gdbarch,
285                      struct jit_descriptor *descriptor,
286                      CORE_ADDR descriptor_addr)
287 {
288   int err;
289   struct type *ptr_type;
290   int ptr_size;
291   int desc_size;
292   gdb_byte *desc_buf;
293   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
294
295   /* Figure out how big the descriptor is on the remote and how to read it.  */
296   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
297   ptr_size = TYPE_LENGTH (ptr_type);
298   desc_size = 8 + 2 * ptr_size;  /* Two 32-bit ints and two pointers.  */
299   desc_buf = alloca (desc_size);
300
301   /* Read the descriptor.  */
302   err = target_read_memory (descriptor_addr, desc_buf, desc_size);
303   if (err)
304     error (_("Unable to read JIT descriptor from remote memory!"));
305
306   /* Fix the endianness to match the host.  */
307   descriptor->version = extract_unsigned_integer (&desc_buf[0], 4, byte_order);
308   descriptor->action_flag =
309       extract_unsigned_integer (&desc_buf[4], 4, byte_order);
310   descriptor->relevant_entry = extract_typed_address (&desc_buf[8], ptr_type);
311   descriptor->first_entry =
312       extract_typed_address (&desc_buf[8 + ptr_size], ptr_type);
313 }
314
315 /* Helper function for reading a JITed code entry from remote memory.  */
316
317 static void
318 jit_read_code_entry (struct gdbarch *gdbarch,
319                      CORE_ADDR code_addr, struct jit_code_entry *code_entry)
320 {
321   int err, off;
322   struct type *ptr_type;
323   int ptr_size;
324   int entry_size;
325   int align_bytes;
326   gdb_byte *entry_buf;
327   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
328
329   /* Figure out how big the entry is on the remote and how to read it.  */
330   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
331   ptr_size = TYPE_LENGTH (ptr_type);
332   entry_size = 3 * ptr_size + 8;  /* Three pointers and one 64-bit int.  */
333   entry_buf = alloca (entry_size);
334
335   /* Read the entry.  */
336   err = target_read_memory (code_addr, entry_buf, entry_size);
337   if (err)
338     error (_("Unable to read JIT code entry from remote memory!"));
339
340   /* Fix the endianness to match the host.  */
341   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
342   code_entry->next_entry = extract_typed_address (&entry_buf[0], ptr_type);
343   code_entry->prev_entry =
344       extract_typed_address (&entry_buf[ptr_size], ptr_type);
345   code_entry->symfile_addr =
346       extract_typed_address (&entry_buf[2 * ptr_size], ptr_type);
347
348   align_bytes = gdbarch_long_long_align_bit (gdbarch) / 8;
349   off = 3 * ptr_size;
350   off = (off + (align_bytes - 1)) & ~(align_bytes - 1);
351
352   code_entry->symfile_size =
353       extract_unsigned_integer (&entry_buf[off], 8, byte_order);
354 }
355
356 /* Proxy object for building a block.  */
357
358 struct gdb_block
359 {
360   /* gdb_blocks are linked into a tree structure.  Next points to the
361      next node at the same depth as this block and parent to the
362      parent gdb_block.  */
363   struct gdb_block *next, *parent;
364
365   /* Points to the "real" block that is being built out of this
366      instance.  This block will be added to a blockvector, which will
367      then be added to a symtab.  */
368   struct block *real_block;
369
370   /* The first and last code address corresponding to this block.  */
371   CORE_ADDR begin, end;
372
373   /* The name of this block (if any).  If this is non-NULL, the
374      FUNCTION symbol symbol is set to this value.  */
375   const char *name;
376 };
377
378 /* Proxy object for building a symtab.  */
379
380 struct gdb_symtab
381 {
382   /* The list of blocks in this symtab.  These will eventually be
383      converted to real blocks.  */
384   struct gdb_block *blocks;
385
386   /* The number of blocks inserted.  */
387   int nblocks;
388
389   /* A mapping between line numbers to PC.  */
390   struct linetable *linetable;
391
392   /* The source file for this symtab.  */
393   const char *file_name;
394   struct gdb_symtab *next;
395 };
396
397 /* Proxy object for building an object.  */
398
399 struct gdb_object
400 {
401   struct gdb_symtab *symtabs;
402 };
403
404 /* The type of the `private' data passed around by the callback
405    functions.  */
406
407 typedef CORE_ADDR jit_dbg_reader_data;
408
409 /* The reader calls into this function to read data off the targets
410    address space.  */
411
412 static enum gdb_status
413 jit_target_read_impl (GDB_CORE_ADDR target_mem, void *gdb_buf, int len)
414 {
415   int result = target_read_memory ((CORE_ADDR) target_mem, gdb_buf, len);
416   if (result == 0)
417     return GDB_SUCCESS;
418   else
419     return GDB_FAIL;
420 }
421
422 /* The reader calls into this function to create a new gdb_object
423    which it can then pass around to the other callbacks.  Right now,
424    all that is required is allocating the memory.  */
425
426 static struct gdb_object *
427 jit_object_open_impl (struct gdb_symbol_callbacks *cb)
428 {
429   /* CB is not required right now, but sometime in the future we might
430      need a handle to it, and we'd like to do that without breaking
431      the ABI.  */
432   return XZALLOC (struct gdb_object);
433 }
434
435 /* Readers call into this function to open a new gdb_symtab, which,
436    again, is passed around to other callbacks.  */
437
438 static struct gdb_symtab *
439 jit_symtab_open_impl (struct gdb_symbol_callbacks *cb,
440                       struct gdb_object *object,
441                       const char *file_name)
442 {
443   struct gdb_symtab *ret;
444
445   /* CB stays unused.  See comment in jit_object_open_impl.  */
446
447   ret = XZALLOC (struct gdb_symtab);
448   ret->file_name = file_name ? xstrdup (file_name) : xstrdup ("");
449   ret->next = object->symtabs;
450   object->symtabs = ret;
451   return ret;
452 }
453
454 /* Returns true if the block corresponding to old should be placed
455    before the block corresponding to new in the final blockvector.  */
456
457 static int
458 compare_block (const struct gdb_block *const old,
459                const struct gdb_block *const new)
460 {
461   if (old == NULL)
462     return 1;
463   if (old->begin < new->begin)
464     return 1;
465   else if (old->begin == new->begin)
466     {
467       if (old->end > new->end)
468         return 1;
469       else
470         return 0;
471     }
472   else
473     return 0;
474 }
475
476 /* Called by readers to open a new gdb_block.  This function also
477    inserts the new gdb_block in the correct place in the corresponding
478    gdb_symtab.  */
479
480 static struct gdb_block *
481 jit_block_open_impl (struct gdb_symbol_callbacks *cb,
482                      struct gdb_symtab *symtab, struct gdb_block *parent,
483                      GDB_CORE_ADDR begin, GDB_CORE_ADDR end, const char *name)
484 {
485   struct gdb_block *block = XZALLOC (struct gdb_block);
486
487   block->next = symtab->blocks;
488   block->begin = (CORE_ADDR) begin;
489   block->end = (CORE_ADDR) end;
490   block->name = name ? xstrdup (name) : NULL;
491   block->parent = parent;
492
493   /* Ensure that the blocks are inserted in the correct (reverse of
494      the order expected by blockvector).  */
495   if (compare_block (symtab->blocks, block))
496     {
497       symtab->blocks = block;
498     }
499   else
500     {
501       struct gdb_block *i = symtab->blocks;
502
503       for (;; i = i->next)
504         {
505           /* Guaranteed to terminate, since compare_block (NULL, _)
506              returns 1.  */
507           if (compare_block (i->next, block))
508             {
509               block->next = i->next;
510               i->next = block;
511               break;
512             }
513         }
514     }
515   symtab->nblocks++;
516
517   return block;
518 }
519
520 /* Readers call this to add a line mapping (from PC to line number) to
521    a gdb_symtab.  */
522
523 static void
524 jit_symtab_line_mapping_add_impl (struct gdb_symbol_callbacks *cb,
525                                   struct gdb_symtab *stab, int nlines,
526                                   struct gdb_line_mapping *map)
527 {
528   int i;
529
530   if (nlines < 1)
531     return;
532
533   stab->linetable = xmalloc (sizeof (struct linetable)
534                              + (nlines - 1) * sizeof (struct linetable_entry));
535   stab->linetable->nitems = nlines;
536   for (i = 0; i < nlines; i++)
537     {
538       stab->linetable->item[i].pc = (CORE_ADDR) map[i].pc;
539       stab->linetable->item[i].line = map[i].line;
540     }
541 }
542
543 /* Called by readers to close a gdb_symtab.  Does not need to do
544    anything as of now.  */
545
546 static void
547 jit_symtab_close_impl (struct gdb_symbol_callbacks *cb,
548                        struct gdb_symtab *stab)
549 {
550   /* Right now nothing needs to be done here.  We may need to do some
551      cleanup here in the future (again, without breaking the plugin
552      ABI).  */
553 }
554
555 /* Transform STAB to a proper symtab, and add it it OBJFILE.  */
556
557 static void
558 finalize_symtab (struct gdb_symtab *stab, struct objfile *objfile)
559 {
560   struct symtab *symtab;
561   struct gdb_block *gdb_block_iter, *gdb_block_iter_tmp;
562   struct block *block_iter;
563   int actual_nblocks, i, blockvector_size;
564   CORE_ADDR begin, end;
565
566   actual_nblocks = FIRST_LOCAL_BLOCK + stab->nblocks;
567
568   symtab = allocate_symtab (stab->file_name, objfile);
569   /* JIT compilers compile in memory.  */
570   symtab->dirname = NULL;
571
572   /* Copy over the linetable entry if one was provided.  */
573   if (stab->linetable)
574     {
575       int size = ((stab->linetable->nitems - 1)
576                   * sizeof (struct linetable_entry)
577                   + sizeof (struct linetable));
578       LINETABLE (symtab) = obstack_alloc (&objfile->objfile_obstack, size);
579       memcpy (LINETABLE (symtab), stab->linetable, size);
580     }
581   else
582     {
583       LINETABLE (symtab) = NULL;
584     }
585
586   blockvector_size = (sizeof (struct blockvector)
587                       + (actual_nblocks - 1) * sizeof (struct block *));
588   symtab->blockvector = obstack_alloc (&objfile->objfile_obstack,
589                                        blockvector_size);
590
591   /* (begin, end) will contain the PC range this entire blockvector
592      spans.  */
593   symtab->primary = 1;
594   BLOCKVECTOR_MAP (symtab->blockvector) = NULL;
595   begin = stab->blocks->begin;
596   end = stab->blocks->end;
597   BLOCKVECTOR_NBLOCKS (symtab->blockvector) = actual_nblocks;
598
599   /* First run over all the gdb_block objects, creating a real block
600      object for each.  Simultaneously, keep setting the real_block
601      fields.  */
602   for (i = (actual_nblocks - 1), gdb_block_iter = stab->blocks;
603        i >= FIRST_LOCAL_BLOCK;
604        i--, gdb_block_iter = gdb_block_iter->next)
605     {
606       struct block *new_block = allocate_block (&objfile->objfile_obstack);
607       struct symbol *block_name = obstack_alloc (&objfile->objfile_obstack,
608                                                  sizeof (struct symbol));
609
610       BLOCK_DICT (new_block) = dict_create_linear (&objfile->objfile_obstack,
611                                                    NULL);
612       /* The address range.  */
613       BLOCK_START (new_block) = (CORE_ADDR) gdb_block_iter->begin;
614       BLOCK_END (new_block) = (CORE_ADDR) gdb_block_iter->end;
615
616       /* The name.  */
617       memset (block_name, 0, sizeof (struct symbol));
618       SYMBOL_DOMAIN (block_name) = VAR_DOMAIN;
619       SYMBOL_CLASS (block_name) = LOC_BLOCK;
620       SYMBOL_SYMTAB (block_name) = symtab;
621       SYMBOL_BLOCK_VALUE (block_name) = new_block;
622
623       block_name->ginfo.name = obsavestring (gdb_block_iter->name,
624                                              strlen (gdb_block_iter->name),
625                                              &objfile->objfile_obstack);
626
627       BLOCK_FUNCTION (new_block) = block_name;
628
629       BLOCKVECTOR_BLOCK (symtab->blockvector, i) = new_block;
630       if (begin > BLOCK_START (new_block))
631         begin = BLOCK_START (new_block);
632       if (end < BLOCK_END (new_block))
633         end = BLOCK_END (new_block);
634
635       gdb_block_iter->real_block = new_block;
636     }
637
638   /* Now add the special blocks.  */
639   block_iter = NULL;
640   for (i = 0; i < FIRST_LOCAL_BLOCK; i++)
641     {
642       struct block *new_block = allocate_block (&objfile->objfile_obstack);
643       BLOCK_DICT (new_block) = dict_create_linear (&objfile->objfile_obstack,
644                                                    NULL);
645       BLOCK_SUPERBLOCK (new_block) = block_iter;
646       block_iter = new_block;
647
648       BLOCK_START (new_block) = (CORE_ADDR) begin;
649       BLOCK_END (new_block) = (CORE_ADDR) end;
650
651       BLOCKVECTOR_BLOCK (symtab->blockvector, i) = new_block;
652     }
653
654   /* Fill up the superblock fields for the real blocks, using the
655      real_block fields populated earlier.  */
656   for (gdb_block_iter = stab->blocks;
657        gdb_block_iter;
658        gdb_block_iter = gdb_block_iter->next)
659     {
660       if (gdb_block_iter->parent != NULL)
661         BLOCK_SUPERBLOCK (gdb_block_iter->real_block) =
662           gdb_block_iter->parent->real_block;
663     }
664
665   /* Free memory.  */
666   gdb_block_iter = stab->blocks;
667
668   for (gdb_block_iter = stab->blocks, gdb_block_iter_tmp = gdb_block_iter->next;
669        gdb_block_iter;
670        gdb_block_iter = gdb_block_iter_tmp)
671     {
672       xfree ((void *) gdb_block_iter->name);
673       xfree (gdb_block_iter);
674     }
675   xfree (stab->linetable);
676   xfree ((char *) stab->file_name);
677   xfree (stab);
678 }
679
680 /* Called when closing a gdb_objfile.  Converts OBJ to a proper
681    objfile.  */
682
683 static void
684 jit_object_close_impl (struct gdb_symbol_callbacks *cb,
685                        struct gdb_object *obj)
686 {
687   struct gdb_symtab *i, *j;
688   struct objfile *objfile;
689   jit_dbg_reader_data *priv_data;
690
691   priv_data = cb->priv_data;
692
693   objfile = allocate_objfile (NULL, 0);
694   objfile->gdbarch = target_gdbarch;
695
696   objfile->msymbols = obstack_alloc (&objfile->objfile_obstack,
697                                      sizeof (struct minimal_symbol));
698   memset (objfile->msymbols, 0, sizeof (struct minimal_symbol));
699
700   xfree (objfile->name);
701   objfile->name = xstrdup ("<< JIT compiled code >>");
702
703   j = NULL;
704   for (i = obj->symtabs; i; i = j)
705     {
706       j = i->next;
707       finalize_symtab (i, objfile);
708     }
709   add_objfile_entry (objfile, *priv_data);
710   xfree (obj);
711 }
712
713 /* Try to read CODE_ENTRY using the loaded jit reader (if any).
714    ENTRY_ADDR is the address of the object file (in the target's
715    address space) being read.  */
716
717 static int
718 jit_reader_try_read_symtab (struct jit_code_entry *code_entry,
719                             CORE_ADDR entry_addr)
720 {
721   void *gdb_mem;
722   int status;
723   struct jit_dbg_reader *i;
724   jit_dbg_reader_data priv_data;
725   struct gdb_reader_funcs *funcs;
726   volatile struct gdb_exception e;
727   struct gdb_symbol_callbacks callbacks =
728     {
729       jit_object_open_impl,
730       jit_symtab_open_impl,
731       jit_block_open_impl,
732       jit_symtab_close_impl,
733       jit_object_close_impl,
734
735       jit_symtab_line_mapping_add_impl,
736       jit_target_read_impl,
737
738       &priv_data
739     };
740
741   priv_data = entry_addr;
742
743   if (!loaded_jit_reader)
744     return 0;
745
746   gdb_mem = xmalloc (code_entry->symfile_size);
747
748   status = 1;
749   TRY_CATCH (e, RETURN_MASK_ALL)
750     if (target_read_memory (code_entry->symfile_addr, gdb_mem,
751                             code_entry->symfile_size))
752       status = 0;
753   if (e.reason < 0)
754     status = 0;
755
756   if (status)
757     {
758       funcs = loaded_jit_reader->functions;
759       if (funcs->read (funcs, &callbacks, gdb_mem, code_entry->symfile_size)
760           != GDB_SUCCESS)
761         status = 0;
762     }
763
764   xfree (gdb_mem);
765   if (jit_debug && status == 0)
766     fprintf_unfiltered (gdb_stdlog,
767                         "Could not read symtab using the loaded JIT reader.\n");
768   return status;
769 }
770
771 /* Try to read CODE_ENTRY using BFD.  ENTRY_ADDR is the address of the
772    object file (in the target's address space) being read.  */
773
774 static void
775 jit_bfd_try_read_symtab (struct jit_code_entry *code_entry,
776                          CORE_ADDR entry_addr,
777                          struct gdbarch *gdbarch)
778 {
779   bfd *nbfd;
780   struct section_addr_info *sai;
781   struct bfd_section *sec;
782   struct objfile *objfile;
783   struct cleanup *old_cleanups;
784   int i;
785   const struct bfd_arch_info *b;
786
787   if (jit_debug)
788     fprintf_unfiltered (gdb_stdlog,
789                         "jit_register_code, symfile_addr = %s, "
790                         "symfile_size = %s\n",
791                         paddress (gdbarch, code_entry->symfile_addr),
792                         pulongest (code_entry->symfile_size));
793
794   nbfd = bfd_open_from_target_memory (code_entry->symfile_addr,
795                                       code_entry->symfile_size, gnutarget);
796   if (nbfd == NULL)
797     {
798       puts_unfiltered (_("Error opening JITed symbol file, ignoring it.\n"));
799       return;
800     }
801
802   /* Check the format.  NOTE: This initializes important data that GDB uses!
803      We would segfault later without this line.  */
804   if (!bfd_check_format (nbfd, bfd_object))
805     {
806       printf_unfiltered (_("\
807 JITed symbol file is not an object file, ignoring it.\n"));
808       bfd_close (nbfd);
809       return;
810     }
811
812   /* Check bfd arch.  */
813   b = gdbarch_bfd_arch_info (gdbarch);
814   if (b->compatible (b, bfd_get_arch_info (nbfd)) != b)
815     warning (_("JITed object file architecture %s is not compatible "
816                "with target architecture %s."), bfd_get_arch_info
817              (nbfd)->printable_name, b->printable_name);
818
819   /* Read the section address information out of the symbol file.  Since the
820      file is generated by the JIT at runtime, it should all of the absolute
821      addresses that we care about.  */
822   sai = alloc_section_addr_info (bfd_count_sections (nbfd));
823   old_cleanups = make_cleanup_free_section_addr_info (sai);
824   i = 0;
825   for (sec = nbfd->sections; sec != NULL; sec = sec->next)
826     if ((bfd_get_section_flags (nbfd, sec) & (SEC_ALLOC|SEC_LOAD)) != 0)
827       {
828         /* We assume that these virtual addresses are absolute, and do not
829            treat them as offsets.  */
830         sai->other[i].addr = bfd_get_section_vma (nbfd, sec);
831         sai->other[i].name = xstrdup (bfd_get_section_name (nbfd, sec));
832         sai->other[i].sectindex = sec->index;
833         ++i;
834       }
835
836   /* This call takes ownership of NBFD.  It does not take ownership of SAI.  */
837   objfile = symbol_file_add_from_bfd (nbfd, 0, sai, OBJF_SHARED, NULL);
838
839   do_cleanups (old_cleanups);
840   add_objfile_entry (objfile, entry_addr);
841 }
842
843 /* This function registers code associated with a JIT code entry.  It uses the
844    pointer and size pair in the entry to read the symbol file from the remote
845    and then calls symbol_file_add_from_local_memory to add it as though it were
846    a symbol file added by the user.  */
847
848 static void
849 jit_register_code (struct gdbarch *gdbarch,
850                    CORE_ADDR entry_addr, struct jit_code_entry *code_entry)
851 {
852   int i, success;
853   const struct bfd_arch_info *b;
854   struct jit_inferior_data *inf_data = get_jit_inferior_data ();
855
856   if (jit_debug)
857     fprintf_unfiltered (gdb_stdlog,
858                         "jit_register_code, symfile_addr = %s, "
859                         "symfile_size = %s\n",
860                         paddress (gdbarch, code_entry->symfile_addr),
861                         pulongest (code_entry->symfile_size));
862
863   success = jit_reader_try_read_symtab (code_entry, entry_addr);
864
865   if (!success)
866     jit_bfd_try_read_symtab (code_entry, entry_addr, gdbarch);
867 }
868
869 /* This function unregisters JITed code and frees the corresponding
870    objfile.  */
871
872 static void
873 jit_unregister_code (struct objfile *objfile)
874 {
875   free_objfile (objfile);
876 }
877
878 /* Look up the objfile with this code entry address.  */
879
880 static struct objfile *
881 jit_find_objf_with_entry_addr (CORE_ADDR entry_addr)
882 {
883   struct objfile *objf;
884   CORE_ADDR *objf_entry_addr;
885
886   ALL_OBJFILES (objf)
887     {
888       objf_entry_addr = (CORE_ADDR *) objfile_data (objf, jit_objfile_data);
889       if (objf_entry_addr != NULL && *objf_entry_addr == entry_addr)
890         return objf;
891     }
892   return NULL;
893 }
894
895 /* (Re-)Initialize the jit breakpoint if necessary.
896    Return 0 on success.  */
897
898 static int
899 jit_breakpoint_re_set_internal (struct gdbarch *gdbarch,
900                                 struct jit_inferior_data *inf_data)
901 {
902   if (inf_data->breakpoint_addr == 0)
903     {
904       struct minimal_symbol *reg_symbol;
905
906       /* Lookup the registration symbol.  If it is missing, then we assume
907          we are not attached to a JIT.  */
908       reg_symbol = lookup_minimal_symbol (jit_break_name, NULL, NULL);
909       if (reg_symbol == NULL)
910         return 1;
911       inf_data->breakpoint_addr = SYMBOL_VALUE_ADDRESS (reg_symbol);
912       if (inf_data->breakpoint_addr == 0)
913         return 2;
914
915       /* If we have not read the jit descriptor yet (e.g. because the JITer
916          itself is in a shared library which just got loaded), do so now.  */
917       if (inf_data->descriptor_addr == 0)
918         jit_inferior_init (gdbarch);
919     }
920   else
921     return 0;
922
923   if (jit_debug)
924     fprintf_unfiltered (gdb_stdlog,
925                         "jit_breakpoint_re_set_internal, "
926                         "breakpoint_addr = %s\n",
927                         paddress (gdbarch, inf_data->breakpoint_addr));
928
929   /* Put a breakpoint in the registration symbol.  */
930   create_jit_event_breakpoint (gdbarch, inf_data->breakpoint_addr);
931
932   return 0;
933 }
934
935 /* The private data passed around in the frame unwind callback
936    functions.  */
937
938 struct jit_unwind_private
939 {
940   /* Cached register values.  See jit_frame_sniffer to see how this
941      works.  */
942   struct gdb_reg_value **registers;
943
944   /* The frame being unwound.  */
945   struct frame_info *this_frame;
946 };
947
948 /* Sets the value of a particular register in this frame.  */
949
950 static void
951 jit_unwind_reg_set_impl (struct gdb_unwind_callbacks *cb, int dwarf_regnum,
952                          struct gdb_reg_value *value)
953 {
954   struct jit_unwind_private *priv;
955   int gdb_reg;
956
957   priv = cb->priv_data;
958
959   gdb_reg = gdbarch_dwarf2_reg_to_regnum (get_frame_arch (priv->this_frame),
960                                           dwarf_regnum);
961   if (gdb_reg == -1)
962     {
963       if (jit_debug)
964         fprintf_unfiltered (gdb_stdlog,
965                             _("Could not recognize DWARF regnum %d"),
966                             dwarf_regnum);
967       return;
968     }
969
970   gdb_assert (priv->registers);
971   priv->registers[gdb_reg] = value;
972 }
973
974 static void
975 reg_value_free_impl (struct gdb_reg_value *value)
976 {
977   xfree (value);
978 }
979
980 /* Get the value of register REGNUM in the previous frame.  */
981
982 static struct gdb_reg_value *
983 jit_unwind_reg_get_impl (struct gdb_unwind_callbacks *cb, int regnum)
984 {
985   struct jit_unwind_private *priv;
986   struct gdb_reg_value *value;
987   int gdb_reg, size;
988   struct gdbarch *frame_arch;
989
990   priv = cb->priv_data;
991   frame_arch = get_frame_arch (priv->this_frame);
992
993   gdb_reg = gdbarch_dwarf2_reg_to_regnum (frame_arch, regnum);
994   size = register_size (frame_arch, gdb_reg);
995   value = xmalloc (sizeof (struct gdb_reg_value) + size - 1);
996   value->defined = frame_register_read (priv->this_frame, gdb_reg,
997                                         value->value);
998   value->size = size;
999   value->free = reg_value_free_impl;
1000   return value;
1001 }
1002
1003 /* gdb_reg_value has a free function, which must be called on each
1004    saved register value.  */
1005
1006 static void
1007 jit_dealloc_cache (struct frame_info *this_frame, void *cache)
1008 {
1009   struct jit_unwind_private *priv_data = cache;
1010   struct gdbarch *frame_arch;
1011   int i;
1012
1013   gdb_assert (priv_data->registers);
1014   frame_arch = get_frame_arch (priv_data->this_frame);
1015
1016   for (i = 0; i < gdbarch_num_regs (frame_arch); i++)
1017     if (priv_data->registers[i] && priv_data->registers[i]->free)
1018       priv_data->registers[i]->free (priv_data->registers[i]);
1019
1020   xfree (priv_data->registers);
1021   xfree (priv_data);
1022 }
1023
1024 /* The frame sniffer for the pseudo unwinder.
1025
1026    While this is nominally a frame sniffer, in the case where the JIT
1027    reader actually recognizes the frame, it does a lot more work -- it
1028    unwinds the frame and saves the corresponding register values in
1029    the cache.  jit_frame_prev_register simply returns the saved
1030    register values.  */
1031
1032 static int
1033 jit_frame_sniffer (const struct frame_unwind *self,
1034                    struct frame_info *this_frame, void **cache)
1035 {
1036   struct jit_inferior_data *inf_data;
1037   struct jit_unwind_private *priv_data;
1038   struct jit_dbg_reader *iter;
1039   struct gdb_unwind_callbacks callbacks;
1040   struct gdb_reader_funcs *funcs;
1041
1042   inf_data = get_jit_inferior_data ();
1043
1044   callbacks.reg_get = jit_unwind_reg_get_impl;
1045   callbacks.reg_set = jit_unwind_reg_set_impl;
1046   callbacks.target_read = jit_target_read_impl;
1047
1048   if (loaded_jit_reader == NULL)
1049     return 0;
1050
1051   funcs = loaded_jit_reader->functions;
1052
1053   gdb_assert (!*cache);
1054
1055   *cache = XZALLOC (struct jit_unwind_private);
1056   priv_data = *cache;
1057   priv_data->registers =
1058     XCALLOC (gdbarch_num_regs (get_frame_arch (this_frame)),
1059              struct gdb_reg_value *);
1060   priv_data->this_frame = this_frame;
1061
1062   callbacks.priv_data = priv_data;
1063
1064   /* Try to coax the provided unwinder to unwind the stack */
1065   if (funcs->unwind (funcs, &callbacks) == GDB_SUCCESS)
1066     {
1067       if (jit_debug)
1068         fprintf_unfiltered (gdb_stdlog, _("Successfully unwound frame using "
1069                                           "JIT reader.\n"));
1070       return 1;
1071     }
1072   if (jit_debug)
1073     fprintf_unfiltered (gdb_stdlog, _("Could not unwind frame using "
1074                                       "JIT reader.\n"));
1075
1076   jit_dealloc_cache (this_frame, *cache);
1077   *cache = NULL;
1078
1079   return 0;
1080 }
1081
1082
1083 /* The frame_id function for the pseudo unwinder.  Relays the call to
1084    the loaded plugin.  */
1085
1086 static void
1087 jit_frame_this_id (struct frame_info *this_frame, void **cache,
1088                    struct frame_id *this_id)
1089 {
1090   struct jit_unwind_private private;
1091   struct gdb_frame_id frame_id;
1092   struct gdb_reader_funcs *funcs;
1093   struct gdb_unwind_callbacks callbacks;
1094
1095   private.registers = NULL;
1096   private.this_frame = this_frame;
1097
1098   /* We don't expect the frame_id function to set any registers, so we
1099      set reg_set to NULL.  */
1100   callbacks.reg_get = jit_unwind_reg_get_impl;
1101   callbacks.reg_set = NULL;
1102   callbacks.target_read = jit_target_read_impl;
1103   callbacks.priv_data = &private;
1104
1105   gdb_assert (loaded_jit_reader);
1106   funcs = loaded_jit_reader->functions;
1107
1108   frame_id = funcs->get_frame_id (funcs, &callbacks);
1109   *this_id = frame_id_build (frame_id.stack_address, frame_id.code_address);
1110 }
1111
1112 /* Pseudo unwinder function.  Reads the previously fetched value for
1113    the register from the cache.  */
1114
1115 static struct value *
1116 jit_frame_prev_register (struct frame_info *this_frame, void **cache, int reg)
1117 {
1118   struct jit_unwind_private *priv = *cache;
1119   struct gdb_reg_value *value;
1120
1121   if (priv == NULL)
1122     return frame_unwind_got_optimized (this_frame, reg);
1123
1124   gdb_assert (priv->registers);
1125   value = priv->registers[reg];
1126   if (value && value->defined)
1127     return frame_unwind_got_bytes (this_frame, reg, value->value);
1128   else
1129     return frame_unwind_got_optimized (this_frame, reg);
1130 }
1131
1132 /* Relay everything back to the unwinder registered by the JIT debug
1133    info reader.*/
1134
1135 static const struct frame_unwind jit_frame_unwind =
1136 {
1137   NORMAL_FRAME,
1138   default_frame_unwind_stop_reason,
1139   jit_frame_this_id,
1140   jit_frame_prev_register,
1141   NULL,
1142   jit_frame_sniffer,
1143   jit_dealloc_cache
1144 };
1145
1146
1147 /* This is the information that is stored at jit_gdbarch_data for each
1148    architecture.  */
1149
1150 struct jit_gdbarch_data_type
1151 {
1152   /* Has the (pseudo) unwinder been prepended? */
1153   int unwinder_registered;
1154 };
1155
1156 /* Check GDBARCH and prepend the pseudo JIT unwinder if needed.  */
1157
1158 static void
1159 jit_prepend_unwinder (struct gdbarch *gdbarch)
1160 {
1161   struct jit_gdbarch_data_type *data;
1162
1163   data = gdbarch_data (gdbarch, jit_gdbarch_data);
1164   if (!data->unwinder_registered)
1165     {
1166       frame_unwind_prepend_unwinder (gdbarch, &jit_frame_unwind);
1167       data->unwinder_registered = 1;
1168     }
1169 }
1170
1171 /* Register any already created translations.  */
1172
1173 static void
1174 jit_inferior_init (struct gdbarch *gdbarch)
1175 {
1176   struct jit_descriptor descriptor;
1177   struct jit_code_entry cur_entry;
1178   struct jit_inferior_data *inf_data;
1179   CORE_ADDR cur_entry_addr;
1180
1181   if (jit_debug)
1182     fprintf_unfiltered (gdb_stdlog, "jit_inferior_init\n");
1183
1184   jit_prepend_unwinder (gdbarch);
1185
1186   inf_data = get_jit_inferior_data ();
1187   if (jit_breakpoint_re_set_internal (gdbarch, inf_data) != 0)
1188     return;
1189
1190   if (inf_data->descriptor_addr == 0)
1191     {
1192       struct minimal_symbol *desc_symbol;
1193
1194       /* Lookup the descriptor symbol and cache the addr.  If it is
1195          missing, we assume we are not attached to a JIT and return early.  */
1196       desc_symbol = lookup_minimal_symbol (jit_descriptor_name, NULL, NULL);
1197       if (desc_symbol == NULL)
1198         return;
1199
1200       inf_data->descriptor_addr = SYMBOL_VALUE_ADDRESS (desc_symbol);
1201       if (inf_data->descriptor_addr == 0)
1202         return;
1203     }
1204
1205   if (jit_debug)
1206     fprintf_unfiltered (gdb_stdlog,
1207                         "jit_inferior_init, descriptor_addr = %s\n",
1208                         paddress (gdbarch, inf_data->descriptor_addr));
1209
1210   /* Read the descriptor so we can check the version number and load
1211      any already JITed functions.  */
1212   jit_read_descriptor (gdbarch, &descriptor, inf_data->descriptor_addr);
1213
1214   /* Check that the version number agrees with that we support.  */
1215   if (descriptor.version != 1)
1216     error (_("Unsupported JIT protocol version in descriptor!"));
1217
1218   /* If we've attached to a running program, we need to check the descriptor
1219      to register any functions that were already generated.  */
1220   for (cur_entry_addr = descriptor.first_entry;
1221        cur_entry_addr != 0;
1222        cur_entry_addr = cur_entry.next_entry)
1223     {
1224       jit_read_code_entry (gdbarch, cur_entry_addr, &cur_entry);
1225
1226       /* This hook may be called many times during setup, so make sure we don't
1227          add the same symbol file twice.  */
1228       if (jit_find_objf_with_entry_addr (cur_entry_addr) != NULL)
1229         continue;
1230
1231       jit_register_code (gdbarch, cur_entry_addr, &cur_entry);
1232     }
1233 }
1234
1235 /* Exported routine to call when an inferior has been created.  */
1236
1237 void
1238 jit_inferior_created_hook (void)
1239 {
1240   jit_inferior_init (target_gdbarch);
1241 }
1242
1243 /* Exported routine to call to re-set the jit breakpoints,
1244    e.g. when a program is rerun.  */
1245
1246 void
1247 jit_breakpoint_re_set (void)
1248 {
1249   jit_breakpoint_re_set_internal (target_gdbarch,
1250                                   get_jit_inferior_data ());
1251 }
1252
1253 /* Reset inferior_data, so sybols will be looked up again, and jit_breakpoint
1254    will be reset.  */
1255
1256 static void
1257 jit_reset_inferior_data_and_breakpoints (void)
1258 {
1259   struct jit_inferior_data *inf_data;
1260
1261   /* Force jit_inferior_init to re-lookup of jit symbol addresses.  */
1262   inf_data = get_jit_inferior_data ();
1263   inf_data->breakpoint_addr = 0;
1264   inf_data->descriptor_addr = 0;
1265
1266   /* Remove any existing JIT breakpoint(s).  */
1267   remove_jit_event_breakpoints ();
1268
1269   jit_inferior_init (target_gdbarch);
1270 }
1271
1272 /* Wrapper to match the observer function pointer prototype.  */
1273
1274 static void
1275 jit_inferior_created_observer (struct target_ops *objfile, int from_tty)
1276 {
1277   jit_reset_inferior_data_and_breakpoints ();
1278 }
1279
1280 /* This function cleans up any code entries left over when the
1281    inferior exits.  We get left over code when the inferior exits
1282    without unregistering its code, for example when it crashes.  */
1283
1284 static void
1285 jit_inferior_exit_hook (struct inferior *inf)
1286 {
1287   struct objfile *objf;
1288   struct objfile *temp;
1289
1290   ALL_OBJFILES_SAFE (objf, temp)
1291     if (objfile_data (objf, jit_objfile_data) != NULL)
1292       jit_unregister_code (objf);
1293 }
1294
1295 static void
1296 jit_executable_changed_observer (void)
1297 {
1298   jit_reset_inferior_data_and_breakpoints ();
1299 }
1300
1301 void
1302 jit_event_handler (struct gdbarch *gdbarch)
1303 {
1304   struct jit_descriptor descriptor;
1305   struct jit_code_entry code_entry;
1306   CORE_ADDR entry_addr;
1307   struct objfile *objf;
1308
1309   /* Read the descriptor from remote memory.  */
1310   jit_read_descriptor (gdbarch, &descriptor,
1311                        get_jit_inferior_data ()->descriptor_addr);
1312   entry_addr = descriptor.relevant_entry;
1313
1314   /* Do the corresponding action.  */
1315   switch (descriptor.action_flag)
1316     {
1317     case JIT_NOACTION:
1318       break;
1319     case JIT_REGISTER:
1320       jit_read_code_entry (gdbarch, entry_addr, &code_entry);
1321       jit_register_code (gdbarch, entry_addr, &code_entry);
1322       break;
1323     case JIT_UNREGISTER:
1324       objf = jit_find_objf_with_entry_addr (entry_addr);
1325       if (objf == NULL)
1326         printf_unfiltered (_("Unable to find JITed code "
1327                              "entry at address: %s\n"),
1328                            paddress (gdbarch, entry_addr));
1329       else
1330         jit_unregister_code (objf);
1331
1332       break;
1333     default:
1334       error (_("Unknown action_flag value in JIT descriptor!"));
1335       break;
1336     }
1337 }
1338
1339 /* Called to free the data allocated to the jit_inferior_data slot.  */
1340
1341 static void
1342 free_objfile_data (struct objfile *objfile, void *data)
1343 {
1344   xfree (data);
1345 }
1346
1347 /* Initialize the jit_gdbarch_data slot with an instance of struct
1348    jit_gdbarch_data_type */
1349
1350 static void *
1351 jit_gdbarch_data_init (struct obstack *obstack)
1352 {
1353   struct jit_gdbarch_data_type *data;
1354
1355   data = obstack_alloc (obstack, sizeof (struct jit_gdbarch_data_type));
1356   data->unwinder_registered = 0;
1357   return data;
1358 }
1359
1360 /* Provide a prototype to silence -Wmissing-prototypes.  */
1361
1362 extern void _initialize_jit (void);
1363
1364 void
1365 _initialize_jit (void)
1366 {
1367   jit_reader_dir = relocate_gdb_directory (JIT_READER_DIR,
1368                                            JIT_READER_DIR_RELOCATABLE);
1369   add_setshow_zinteger_cmd ("jit", class_maintenance, &jit_debug,
1370                             _("Set JIT debugging."),
1371                             _("Show JIT debugging."),
1372                             _("When non-zero, JIT debugging is enabled."),
1373                             NULL,
1374                             show_jit_debug,
1375                             &setdebuglist, &showdebuglist);
1376
1377   observer_attach_inferior_created (jit_inferior_created_observer);
1378   observer_attach_inferior_exit (jit_inferior_exit_hook);
1379   observer_attach_executable_changed (jit_executable_changed_observer);
1380   jit_objfile_data =
1381     register_objfile_data_with_cleanup (NULL, free_objfile_data);
1382   jit_inferior_data =
1383     register_inferior_data_with_cleanup (jit_inferior_data_cleanup);
1384   jit_gdbarch_data = gdbarch_data_register_pre_init (jit_gdbarch_data_init);
1385   if (is_dl_available ())
1386     {
1387       add_com ("jit-reader-load", no_class, jit_reader_load_command, _("\
1388 Load FILE as debug info reader and unwinder for JIT compiled code.\n\
1389 Usage: jit-reader-load FILE\n\
1390 Try to load file FILE as a debug info reader (and unwinder) for\n\
1391 JIT compiled code.  The file is loaded from " JIT_READER_DIR ",\n\
1392 relocated relative to the GDB executable if required."));
1393       add_com ("jit-reader-unload", no_class, jit_reader_unload_command, _("\
1394 Unload the currently loaded JIT debug info reader.\n\
1395 Usage: jit-reader-unload FILE\n\n\
1396 Do \"help jit-reader-load\" for info on loading debug info readers."));
1397     }
1398 }