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