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