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