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