More updated translations
[binutils-gdb.git] / gdb / jit.c
blobd55e371b02a9ffcea72bc70ce3912d7dce12642e
1 /* Handle JIT code generation in the inferior for GDB, the GNU Debugger.
3 Copyright (C) 2009-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
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>
47 static std::string jit_reader_dir;
49 static const char jit_break_name[] = "__jit_debug_register_code";
51 static const char jit_descriptor_name[] = "__jit_debug_descriptor";
53 static void jit_inferior_created_hook (inferior *inf);
54 static void jit_inferior_exit_hook (struct inferior *inf);
56 /* True if we want to see trace of jit level stuff. */
58 static bool jit_debug = false;
60 /* Print a "jit" debug statement. */
62 #define jit_debug_printf(fmt, ...) \
63 debug_prefixed_printf_cond (jit_debug, "jit", fmt, ##__VA_ARGS__)
65 static void
66 show_jit_debug (struct ui_file *file, int from_tty,
67 struct cmd_list_element *c, const char *value)
69 gdb_printf (file, _("JIT debugging is %s.\n"), value);
72 /* Implementation of the "maintenance info jit" command. */
74 static void
75 maint_info_jit_cmd (const char *args, int from_tty)
77 inferior *inf = current_inferior ();
78 bool printed_header = false;
80 std::optional<ui_out_emit_table> table_emitter;
82 /* Print a line for each JIT-ed objfile. */
83 for (objfile *obj : inf->pspace->objfiles ())
85 if (obj->jited_data == nullptr)
86 continue;
88 if (!printed_header)
90 table_emitter.emplace (current_uiout, 3, -1, "jit-created-objfiles");
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);
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 ();
107 printed_header = true;
110 ui_out_emit_tuple tuple_emitter (current_uiout, "jit-objfile");
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");
122 struct jit_reader
124 jit_reader (struct gdb_reader_funcs *f, gdb_dlhandle_up &&h)
125 : functions (f), handle (std::move (h))
129 ~jit_reader ()
131 functions->destroy (functions);
134 DISABLE_COPY_AND_ASSIGN (jit_reader);
136 struct gdb_reader_funcs *functions;
137 gdb_dlhandle_up handle;
140 /* One reader that has been loaded successfully, and can potentially be used to
141 parse debug info. */
143 static struct jit_reader *loaded_jit_reader = NULL;
145 typedef struct gdb_reader_funcs * (reader_init_fn_type) (void);
146 static const char reader_init_fn_sym[] = "gdb_init_reader";
148 /* Try to load FILE_NAME as a JIT debug info reader. */
150 static struct jit_reader *
151 jit_reader_load (const char *file_name)
153 reader_init_fn_type *init_fn;
154 struct gdb_reader_funcs *funcs = NULL;
156 jit_debug_printf ("Opening shared object %s", file_name);
158 gdb_dlhandle_up so = gdb_dlopen (file_name);
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);
165 if (gdb_dlsym (so, "plugin_is_GPL_compatible") == NULL)
166 error (_("Reader not GPL compatible."));
168 funcs = init_fn ();
169 if (funcs->reader_version != GDB_READER_INTERFACE_VERSION)
170 error (_("Reader version does not match GDB version."));
172 return new jit_reader (funcs, std::move (so));
175 /* Provides the jit-reader-load command. */
177 static void
178 jit_reader_load_command (const char *args, int from_tty)
180 if (args == NULL)
181 error (_("No reader name provided."));
182 gdb::unique_xmalloc_ptr<char> file (tilde_expand (args));
184 if (loaded_jit_reader != NULL)
185 error (_("JIT reader already loaded. Run jit-reader-unload first."));
187 if (!IS_ABSOLUTE_PATH (file.get ()))
188 file = xstrprintf ("%s%s%s", jit_reader_dir.c_str (),
189 SLASH_STRING, file.get ());
191 loaded_jit_reader = jit_reader_load (file.get ());
192 reinit_frame_cache ();
193 jit_inferior_created_hook (current_inferior ());
196 /* Provides the jit-reader-unload command. */
198 static void
199 jit_reader_unload_command (const char *args, int from_tty)
201 if (!loaded_jit_reader)
202 error (_("No JIT reader loaded."));
204 reinit_frame_cache ();
205 jit_inferior_exit_hook (current_inferior ());
207 delete loaded_jit_reader;
208 loaded_jit_reader = NULL;
211 /* Destructor for jiter_objfile_data. */
213 jiter_objfile_data::~jiter_objfile_data ()
215 if (this->jit_breakpoint != nullptr)
216 delete_breakpoint (this->jit_breakpoint);
219 /* Fetch the jiter_objfile_data associated with OBJF. If no data exists
220 yet, make a new structure and attach it. */
222 static jiter_objfile_data *
223 get_jiter_objfile_data (objfile *objf)
225 if (objf->jiter_data == nullptr)
226 objf->jiter_data = std::make_unique<jiter_objfile_data> ();
228 return objf->jiter_data.get ();
231 /* Remember OBJFILE has been created for struct jit_code_entry located
232 at inferior address ENTRY. */
234 static void
235 add_objfile_entry (struct objfile *objfile, CORE_ADDR entry,
236 CORE_ADDR symfile_addr, ULONGEST symfile_size)
238 gdb_assert (objfile->jited_data == nullptr);
240 objfile->jited_data = std::make_unique<jited_objfile_data> (entry,
241 symfile_addr,
242 symfile_size);
245 /* Helper function for reading the global JIT descriptor from remote
246 memory. Returns true if all went well, false otherwise. */
248 static bool
249 jit_read_descriptor (gdbarch *gdbarch,
250 jit_descriptor *descriptor,
251 objfile *jiter)
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);
260 gdb_assert (jiter != nullptr);
261 jiter_objfile_data *objf_data = jiter->jiter_data.get ();
262 gdb_assert (objf_data != nullptr);
264 CORE_ADDR addr = objf_data->descriptor->value_address (jiter);
266 jit_debug_printf ("descriptor_addr = %s", paddress (gdbarch, addr));
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);
274 /* Read the descriptor. */
275 err = target_read_memory (addr, desc_buf, desc_size);
276 if (err)
278 gdb_printf (gdb_stderr, _("Unable to read JIT descriptor from "
279 "remote memory\n"));
280 return false;
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);
291 return true;
294 /* Helper function for reading a JITed code entry from remote memory. */
296 static void
297 jit_read_code_entry (struct gdbarch *gdbarch,
298 CORE_ADDR code_addr, struct jit_code_entry *code_entry)
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);
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 ();
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);
317 entry_size = off + 8; /* Three pointers and one 64-bit int. */
318 entry_buf = (gdb_byte *) alloca (entry_size);
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!"));
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);
336 /* Proxy object for building a block. */
338 struct gdb_block
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)
348 /* The parent of this block. */
349 struct gdb_block *parent;
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;
356 /* The first and last code address corresponding to this block. */
357 CORE_ADDR begin, end;
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;
364 /* Proxy object for building a symtab. */
366 struct gdb_symtab
368 explicit gdb_symtab (const char *file_name)
369 : file_name (file_name != nullptr ? file_name : "")
372 /* The list of blocks in this symtab. These will eventually be
373 converted to real blocks.
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;
381 /* The number of blocks inserted. */
382 int nblocks = 0;
384 /* A mapping between line numbers to PC. */
385 gdb::unique_xmalloc_ptr<struct linetable> linetable;
387 /* The source file for this symtab. */
388 std::string file_name;
391 /* Proxy object for building an object. */
393 struct gdb_object
395 /* Symtabs of this object.
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;
404 /* The type of the `private' data passed around by the callback
405 functions. */
407 struct jit_dbg_reader_data
409 /* Address of the jit_code_entry in the inferior's address space. */
410 CORE_ADDR entry_addr;
412 /* The code entry, copied in our address space. */
413 const jit_code_entry &entry;
415 struct gdbarch *gdbarch;
418 /* The reader calls into this function to read data off the targets
419 address space. */
421 static enum gdb_status
422 jit_target_read_impl (GDB_CORE_ADDR target_mem, void *gdb_buf, int len)
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;
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. */
436 static struct gdb_object *
437 jit_object_open_impl (struct gdb_symbol_callbacks *cb)
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;
445 /* Readers call into this function to open a new gdb_symtab, which,
446 again, is passed around to other callbacks. */
448 static struct gdb_symtab *
449 jit_symtab_open_impl (struct gdb_symbol_callbacks *cb,
450 struct gdb_object *object,
451 const char *file_name)
453 /* CB stays unused. See comment in jit_object_open_impl. */
455 object->symtabs.emplace_front (file_name);
456 return &object->symtabs.front ();
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. */
463 static struct gdb_block *
464 jit_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)
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++;
473 return &symtab->blocks.front ();
476 /* Readers call this to add a line mapping (from PC to line number) to
477 a gdb_symtab. */
479 static void
480 jit_symtab_line_mapping_add_impl (struct gdb_symbol_callbacks *cb,
481 struct gdb_symtab *stab, int nlines,
482 struct gdb_line_mapping *map)
484 int i;
485 int alloc_len;
487 if (nlines < 1)
488 return;
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++)
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;
503 /* Called by readers to close a gdb_symtab. Does not need to do
504 anything as of now. */
506 static void
507 jit_symtab_close_impl (struct gdb_symbol_callbacks *cb,
508 struct gdb_symtab *stab)
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). */
515 /* Transform STAB to a proper symtab, and add it it OBJFILE. */
517 static void
518 finalize_symtab (struct gdb_symtab *stab, struct objfile *objfile)
520 struct compunit_symtab *cust;
521 size_t blockvector_size;
522 CORE_ADDR begin, end;
523 struct blockvector *bv;
525 int actual_nblocks = FIRST_LOCAL_BLOCK + stab->nblocks;
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)
530 if (a.begin != b.begin)
531 return a.begin < b.begin;
533 return a.end > b.end;
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);
540 /* JIT compilers compile in memory. */
541 cust->set_dirname (nullptr);
543 /* Copy over the linetable entry if one was provided. */
544 if (stab->linetable)
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);
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);
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);
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)
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;
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);
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);
592 block_name->m_name = obstack_strdup (&objfile->objfile_obstack,
593 gdb_block_iter.name.get ());
595 new_block->set_function (block_name);
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 ();
603 gdb_block_iter.real_block = new_block;
605 block_idx++;
608 /* Now add the special blocks. */
609 struct block *block_iter = NULL;
610 for (enum block_enum i : { GLOBAL_BLOCK, STATIC_BLOCK })
612 struct block *new_block;
614 if (i == GLOBAL_BLOCK)
615 new_block = new (&objfile->objfile_obstack) global_block;
616 else
617 new_block = new (&objfile->objfile_obstack) block;
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;
624 new_block->set_start (begin);
625 new_block->set_end (end);
627 bv->set_block (i, new_block);
629 if (i == GLOBAL_BLOCK)
630 new_block->as_global_block ()->set_compunit (cust);
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)
637 if (gdb_block_iter.parent != NULL)
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);
645 else
647 /* And if not, we set a default parent block. */
648 gdb_block_iter.real_block->set_superblock (bv->static_block ());
653 /* Called when closing a gdb_objfile. Converts OBJ to a proper
654 objfile. */
656 static void
657 jit_object_close_impl (struct gdb_symbol_callbacks *cb,
658 struct gdb_object *obj)
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));
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;
672 for (gdb_symtab &symtab : obj->symtabs)
673 finalize_symtab (&symtab, objfile);
675 add_objfile_entry (objfile, priv_data->entry_addr,
676 priv_data->entry.symfile_addr,
677 priv_data->entry.symfile_size);
679 delete obj;
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. */
686 static int
687 jit_reader_try_read_symtab (gdbarch *gdbarch, jit_code_entry *code_entry,
688 CORE_ADDR entry_addr)
690 int status;
691 jit_dbg_reader_data priv_data
693 entry_addr,
694 *code_entry,
695 gdbarch
697 struct gdb_reader_funcs *funcs;
698 struct gdb_symbol_callbacks callbacks =
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,
706 jit_symtab_line_mapping_add_impl,
707 jit_target_read_impl,
709 &priv_data
712 if (!loaded_jit_reader)
713 return 0;
715 gdb::byte_vector gdb_mem (code_entry->symfile_size);
717 status = 1;
720 if (target_read_memory (code_entry->symfile_addr, gdb_mem.data (),
721 code_entry->symfile_size))
722 status = 0;
724 catch (const gdb_exception_error &e)
726 status = 0;
729 if (status)
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;
738 if (status == 0)
739 jit_debug_printf ("Could not read symtab using the loaded JIT reader.");
741 return status;
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. */
747 static void
748 jit_bfd_try_read_symtab (struct jit_code_entry *code_entry,
749 CORE_ADDR entry_addr,
750 struct gdbarch *gdbarch)
752 struct bfd_section *sec;
753 struct objfile *objfile;
754 const struct bfd_arch_info *b;
756 jit_debug_printf ("symfile_addr = %s, symfile_size = %s",
757 paddress (gdbarch, code_entry->symfile_addr),
758 pulongest (code_entry->symfile_size));
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)
764 gdb_puts (_("Error opening JITed symbol file, ignoring it.\n"),
765 gdb_stderr);
766 return;
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))
773 gdb_printf (gdb_stderr, _("\
774 JITed symbol file is not an object file, ignoring it.\n"));
775 return;
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);
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)
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);
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);
806 add_objfile_entry (objfile, entry_addr, code_entry->symfile_addr,
807 code_entry->symfile_size);
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. */
815 static void
816 jit_register_code (struct gdbarch *gdbarch,
817 CORE_ADDR entry_addr, struct jit_code_entry *code_entry)
819 int success;
821 jit_debug_printf ("symfile_addr = %s, symfile_size = %s",
822 paddress (gdbarch, code_entry->symfile_addr),
823 pulongest (code_entry->symfile_size));
825 success = jit_reader_try_read_symtab (gdbarch, code_entry, entry_addr);
827 if (!success)
828 jit_bfd_try_read_symtab (code_entry, entry_addr, gdbarch);
831 /* Look up the objfile with this code entry address. */
833 static struct objfile *
834 jit_find_objf_with_entry_addr (CORE_ADDR entry_addr)
836 for (objfile *objf : current_program_space->objfiles ())
838 if (objf->jited_data != nullptr && objf->jited_data->addr == entry_addr)
839 return objf;
842 return NULL;
845 /* This is called when a breakpoint is deleted. It updates the
846 inferior's cache, if needed. */
848 static void
849 jit_breakpoint_deleted (struct breakpoint *b)
851 if (b->type != bp_jit_event)
852 return;
854 for (bp_location &iter : b->locations ())
856 for (objfile *objf : iter.pspace->objfiles ())
858 jiter_objfile_data *jiter_data = objf->jiter_data.get ();
860 if (jiter_data != nullptr
861 && jiter_data->jit_breakpoint == iter.owner)
863 jiter_data->cached_code_address = 0;
864 jiter_data->jit_breakpoint = nullptr;
870 /* (Re-)Initialize the jit breakpoints for JIT-producing objfiles in
871 PSPACE. */
873 static void
874 jit_breakpoint_re_set_internal (struct gdbarch *gdbarch, program_space *pspace)
876 for (objfile *the_objfile : pspace->objfiles ())
878 /* Skip separate debug objects. */
879 if (the_objfile->separate_debug_objfile_backlink != nullptr)
880 continue;
882 if (the_objfile->skip_jit_symbol_lookup)
883 continue;
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)
892 /* No need to repeat the lookup the next time. */
893 the_objfile->skip_jit_symbol_lookup = true;
894 continue;
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)
903 /* No need to repeat the lookup the next time. */
904 the_objfile->skip_jit_symbol_lookup = true;
905 continue;
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;
913 CORE_ADDR addr = objf_data->register_code->value_address (the_objfile);
914 jit_debug_printf ("breakpoint_addr = %s", paddress (gdbarch, addr));
916 /* Check if we need to re-create the breakpoint. */
917 if (objf_data->cached_code_address == addr)
918 continue;
920 /* Delete the old breakpoint. */
921 if (objf_data->jit_breakpoint != nullptr)
922 delete_breakpoint (objf_data->jit_breakpoint);
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);
930 /* The private data passed around in the frame unwind callback
931 functions. */
933 struct jit_unwind_private
935 /* Cached register values. See jit_frame_sniffer to see how this
936 works. */
937 std::unique_ptr<detached_regcache> regcache;
939 /* The frame being unwound. */
940 frame_info_ptr this_frame;
943 /* Sets the value of a particular register in this frame. */
945 static void
946 jit_unwind_reg_set_impl (struct gdb_unwind_callbacks *cb, int dwarf_regnum,
947 struct gdb_reg_value *value)
949 struct jit_unwind_private *priv;
950 int gdb_reg;
952 priv = (struct jit_unwind_private *) cb->priv_data;
954 gdb_reg = gdbarch_dwarf2_reg_to_regnum (get_frame_arch (priv->this_frame),
955 dwarf_regnum);
956 if (gdb_reg == -1)
958 jit_debug_printf ("Could not recognize DWARF regnum %d", dwarf_regnum);
959 value->free (value);
960 return;
963 priv->regcache->raw_supply (gdb_reg, value->value);
964 value->free (value);
967 static void
968 reg_value_free_impl (struct gdb_reg_value *value)
970 xfree (value);
973 /* Get the value of register REGNUM in the previous frame. */
975 static struct gdb_reg_value *
976 jit_unwind_reg_get_impl (struct gdb_unwind_callbacks *cb, int regnum)
978 struct jit_unwind_private *priv;
979 struct gdb_reg_value *value;
980 int gdb_reg, size;
981 struct gdbarch *frame_arch;
983 priv = (struct jit_unwind_private *) cb->priv_data;
984 frame_arch = get_frame_arch (priv->this_frame);
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;
999 /* gdb_reg_value has a free function, which must be called on each
1000 saved register value. */
1002 static void
1003 jit_dealloc_cache (frame_info *this_frame, void *cache)
1005 struct jit_unwind_private *priv_data = (struct jit_unwind_private *) cache;
1006 delete priv_data;
1009 /* The frame sniffer for the pseudo unwinder.
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. */
1017 static int
1018 jit_frame_sniffer (const struct frame_unwind *self,
1019 const frame_info_ptr &this_frame, void **cache)
1021 struct jit_unwind_private *priv_data;
1022 struct gdb_unwind_callbacks callbacks;
1023 struct gdb_reader_funcs *funcs;
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;
1029 if (loaded_jit_reader == NULL)
1030 return 0;
1032 funcs = loaded_jit_reader->functions;
1034 gdb_assert (!*cache);
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;
1043 callbacks.priv_data = priv_data;
1045 /* Try to coax the provided unwinder to unwind the stack */
1046 if (funcs->unwind (funcs, &callbacks) == GDB_SUCCESS)
1048 jit_debug_printf ("Successfully unwound frame using JIT reader.");
1049 return 1;
1052 jit_debug_printf ("Could not unwind frame using JIT reader.");
1054 jit_dealloc_cache (this_frame.get (), *cache);
1055 *cache = NULL;
1057 return 0;
1061 /* The frame_id function for the pseudo unwinder. Relays the call to
1062 the loaded plugin. */
1064 static void
1065 jit_frame_this_id (const frame_info_ptr &this_frame, void **cache,
1066 struct frame_id *this_id)
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;
1073 priv.regcache.reset ();
1074 priv.this_frame = this_frame;
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;
1083 gdb_assert (loaded_jit_reader);
1084 funcs = loaded_jit_reader->functions;
1086 frame_id = funcs->get_frame_id (funcs, &callbacks);
1087 *this_id = frame_id_build (frame_id.stack_address, frame_id.code_address);
1090 /* Pseudo unwinder function. Reads the previously fetched value for
1091 the register from the cache. */
1093 static struct value *
1094 jit_frame_prev_register (const frame_info_ptr &this_frame, void **cache, int reg)
1096 struct jit_unwind_private *priv = (struct jit_unwind_private *) *cache;
1097 struct gdbarch *gdbarch;
1099 if (priv == NULL)
1100 return frame_unwind_got_optimized (this_frame, reg);
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);
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);
1112 /* Relay everything back to the unwinder registered by the JIT debug
1113 info reader.*/
1115 static 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
1128 /* This is the information that is stored at jit_gdbarch_data for each
1129 architecture. */
1131 struct jit_gdbarch_data_type
1133 /* Has the (pseudo) unwinder been pretended? */
1134 int unwinder_registered = 0;
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. */
1141 static const registry<gdbarch>::key<jit_gdbarch_data_type> jit_gdbarch_data;
1143 /* Check GDBARCH and prepend the pseudo JIT unwinder if needed. */
1145 static void
1146 jit_prepend_unwinder (struct gdbarch *gdbarch)
1148 struct jit_gdbarch_data_type *data = jit_gdbarch_data.get (gdbarch);
1149 if (data == nullptr)
1150 data = jit_gdbarch_data.emplace (gdbarch);
1152 if (!data->unwinder_registered)
1154 frame_unwind_prepend_unwinder (gdbarch, &jit_frame_unwind);
1155 data->unwinder_registered = 1;
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. */
1164 static void
1165 jit_inferior_init (inferior *inf)
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;
1173 jit_debug_printf ("called");
1175 jit_prepend_unwinder (gdbarch);
1177 jit_breakpoint_re_set_internal (gdbarch, pspace);
1179 for (objfile *jiter : pspace->objfiles ())
1181 if (jiter->jiter_data == nullptr)
1182 continue;
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;
1189 /* Check that the version number agrees with that we support. */
1190 if (descriptor.version != 1)
1192 gdb_printf (gdb_stderr,
1193 _("Unsupported JIT protocol version %ld "
1194 "in descriptor (expected 1)\n"),
1195 (long) descriptor.version);
1196 continue;
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)
1206 jit_read_code_entry (gdbarch, cur_entry_addr, &cur_entry);
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;
1213 jit_register_code (gdbarch, cur_entry_addr, &cur_entry);
1218 /* inferior_created observer. */
1220 static void
1221 jit_inferior_created_hook (inferior *inf)
1223 jit_inferior_init (inf);
1226 /* inferior_execd observer. */
1228 static void
1229 jit_inferior_execd_hook (inferior *exec_inf, inferior *follow_inf)
1231 jit_inferior_init (follow_inf);
1234 /* Exported routine to call to re-set the jit breakpoints,
1235 e.g. when a program is rerun. */
1237 void
1238 jit_breakpoint_re_set (void)
1240 jit_breakpoint_re_set_internal (current_inferior ()->arch (),
1241 current_program_space);
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. */
1248 static void
1249 jit_inferior_exit_hook (struct inferior *inf)
1251 for (objfile *objf : current_program_space->objfiles_safe ())
1253 if (objf->jited_data != nullptr && objf->jited_data->addr != 0)
1254 objf->unlink ();
1258 void
1259 jit_event_handler (gdbarch *gdbarch, objfile *jiter)
1261 struct jit_descriptor descriptor;
1263 /* If we get a JIT breakpoint event for this objfile, it is necessarily a
1264 JITer. */
1265 gdb_assert (jiter->jiter_data != nullptr);
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;
1272 /* Do the corresponding action. */
1273 switch (descriptor.action_flag)
1275 case JIT_NOACTION:
1276 break;
1278 case JIT_REGISTER:
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;
1286 case JIT_UNREGISTER:
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 ();
1297 break;
1300 default:
1301 error (_("Unknown action_flag value in JIT descriptor!"));
1302 break;
1306 /* Implementation of "show jit-reader-directory". */
1308 static void
1309 show_jit_reader_directory (const char *args, int from_tty)
1311 gdb_printf (_("JIT reader directory is %ps.\n"),
1312 styled_string (file_name_style.style (),
1313 jit_reader_dir.c_str ()));
1316 void _initialize_jit ();
1317 void
1318 _initialize_jit ()
1320 jit_reader_dir = relocate_gdb_directory (JIT_READER_DIR,
1321 JIT_READER_DIR_RELOCATABLE);
1322 add_setshow_boolean_cmd ("jit", class_maintenance, &jit_debug,
1323 _("Set JIT debugging."),
1324 _("Show JIT debugging."),
1325 _("When set, JIT debugging is enabled."),
1326 NULL,
1327 show_jit_debug,
1328 &setdebuglist, &showdebuglist);
1330 add_cmd ("jit", class_maintenance, maint_info_jit_cmd,
1331 _("Print information about JIT-ed code objects."),
1332 &maintenanceinfolist);
1334 gdb::observers::inferior_created.attach (jit_inferior_created_hook, "jit");
1335 gdb::observers::inferior_execd.attach (jit_inferior_execd_hook, "jit");
1336 gdb::observers::inferior_exit.attach (jit_inferior_exit_hook, "jit");
1337 gdb::observers::breakpoint_deleted.attach (jit_breakpoint_deleted, "jit");
1339 if (is_dl_available ())
1341 struct cmd_list_element *c;
1343 c = add_com ("jit-reader-load", no_class, jit_reader_load_command, _("\
1344 Load FILE as debug info reader and unwinder for JIT compiled code.\n\
1345 Usage: jit-reader-load FILE\n\
1346 Try to load file FILE as a debug info reader (and unwinder) for\n\
1347 JIT compiled code. If FILE is not an absolute file name, it is found\n\
1348 relative to a built-in directory. See \"show jit-reader-directory\"."));
1349 set_cmd_completer (c, deprecated_filename_completer);
1351 c = add_com ("jit-reader-unload", no_class,
1352 jit_reader_unload_command, _("\
1353 Unload the currently loaded JIT debug info reader.\n\
1354 Usage: jit-reader-unload\n\n\
1355 Do \"help jit-reader-load\" for info on loading debug info readers."));
1356 set_cmd_completer (c, noop_completer);
1358 add_cmd ("jit-reader-directory", class_obscure,
1359 show_jit_reader_directory,
1360 _("Show the JIT reader directory.\n\
1361 This is the directory used by \"jit-reader-load\" when given\n\
1362 a relative file name."), &showlist);