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