Automatic date update in version.in
[binutils-gdb.git] / gdb / btrace.c
blobb5a047b245b014a23c6d36fe01157ca16202b25e
1 /* Branch trace support for GDB, the GNU debugger.
3 Copyright (C) 2013-2024 Free Software Foundation, Inc.
5 Contributed by Intel Corp. <markus.t.metzger@intel.com>
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "defs.h"
23 #include "btrace.h"
24 #include "gdbthread.h"
25 #include "inferior.h"
26 #include "target.h"
27 #include "record.h"
28 #include "symtab.h"
29 #include "disasm.h"
30 #include "source.h"
31 #include "filenames.h"
32 #include "regcache.h"
33 #include "gdbsupport/rsp-low.h"
34 #include "gdbcmd.h"
35 #include "cli/cli-utils.h"
36 #include "gdbarch.h"
38 /* For maintenance commands. */
39 #include "record-btrace.h"
41 #include <inttypes.h>
42 #include <ctype.h>
43 #include <algorithm>
45 /* Command lists for btrace maintenance commands. */
46 static struct cmd_list_element *maint_btrace_cmdlist;
47 static struct cmd_list_element *maint_btrace_set_cmdlist;
48 static struct cmd_list_element *maint_btrace_show_cmdlist;
49 static struct cmd_list_element *maint_btrace_pt_set_cmdlist;
50 static struct cmd_list_element *maint_btrace_pt_show_cmdlist;
52 /* Control whether to skip PAD packets when computing the packet history. */
53 static bool maint_btrace_pt_skip_pad = true;
55 static void btrace_add_pc (struct thread_info *tp);
57 /* Print a record debug message. Use do ... while (0) to avoid ambiguities
58 when used in if statements. */
60 #define DEBUG(msg, args...) \
61 do \
62 { \
63 if (record_debug != 0) \
64 gdb_printf (gdb_stdlog, \
65 "[btrace] " msg "\n", ##args); \
66 } \
67 while (0)
69 #define DEBUG_FTRACE(msg, args...) DEBUG ("[ftrace] " msg, ##args)
71 /* Return the function name of a recorded function segment for printing.
72 This function never returns NULL. */
74 static const char *
75 ftrace_print_function_name (const struct btrace_function *bfun)
77 struct minimal_symbol *msym;
78 struct symbol *sym;
80 msym = bfun->msym;
81 sym = bfun->sym;
83 if (sym != NULL)
84 return sym->print_name ();
86 if (msym != NULL)
87 return msym->print_name ();
89 return "<unknown>";
92 /* Return the file name of a recorded function segment for printing.
93 This function never returns NULL. */
95 static const char *
96 ftrace_print_filename (const struct btrace_function *bfun)
98 struct symbol *sym;
99 const char *filename;
101 sym = bfun->sym;
103 if (sym != NULL)
104 filename = symtab_to_filename_for_display (sym->symtab ());
105 else
106 filename = "<unknown>";
108 return filename;
111 /* Return a string representation of the address of an instruction.
112 This function never returns NULL. */
114 static const char *
115 ftrace_print_insn_addr (const struct btrace_insn *insn)
117 if (insn == NULL)
118 return "<nil>";
120 return core_addr_to_string_nz (insn->pc);
123 /* Print an ftrace debug status message. */
125 static void
126 ftrace_debug (const struct btrace_function *bfun, const char *prefix)
128 const char *fun, *file;
129 unsigned int ibegin, iend;
130 int level;
132 fun = ftrace_print_function_name (bfun);
133 file = ftrace_print_filename (bfun);
134 level = bfun->level;
136 ibegin = bfun->insn_offset;
137 iend = ibegin + bfun->insn.size ();
139 DEBUG_FTRACE ("%s: fun = %s, file = %s, level = %d, insn = [%u; %u)",
140 prefix, fun, file, level, ibegin, iend);
143 /* Return the number of instructions in a given function call segment. */
145 static unsigned int
146 ftrace_call_num_insn (const struct btrace_function* bfun)
148 if (bfun == NULL)
149 return 0;
151 /* A gap is always counted as one instruction. */
152 if (bfun->errcode != 0)
153 return 1;
155 return bfun->insn.size ();
158 /* Return the function segment with the given NUMBER or NULL if no such segment
159 exists. BTINFO is the branch trace information for the current thread. */
161 static struct btrace_function *
162 ftrace_find_call_by_number (struct btrace_thread_info *btinfo,
163 unsigned int number)
165 if (number == 0 || number > btinfo->functions.size ())
166 return NULL;
168 return &btinfo->functions[number - 1];
171 /* A const version of the function above. */
173 static const struct btrace_function *
174 ftrace_find_call_by_number (const struct btrace_thread_info *btinfo,
175 unsigned int number)
177 if (number == 0 || number > btinfo->functions.size ())
178 return NULL;
180 return &btinfo->functions[number - 1];
183 /* Return non-zero if BFUN does not match MFUN and FUN,
184 return zero otherwise. */
186 static int
187 ftrace_function_switched (const struct btrace_function *bfun,
188 const struct minimal_symbol *mfun,
189 const struct symbol *fun)
191 struct minimal_symbol *msym;
192 struct symbol *sym;
194 msym = bfun->msym;
195 sym = bfun->sym;
197 /* If the minimal symbol changed, we certainly switched functions. */
198 if (mfun != NULL && msym != NULL
199 && strcmp (mfun->linkage_name (), msym->linkage_name ()) != 0)
200 return 1;
202 /* If the symbol changed, we certainly switched functions. */
203 if (fun != NULL && sym != NULL)
205 const char *bfname, *fname;
207 /* Check the function name. */
208 if (strcmp (fun->linkage_name (), sym->linkage_name ()) != 0)
209 return 1;
211 /* Check the location of those functions, as well. */
212 bfname = symtab_to_fullname (sym->symtab ());
213 fname = symtab_to_fullname (fun->symtab ());
214 if (filename_cmp (fname, bfname) != 0)
215 return 1;
218 /* If we lost symbol information, we switched functions. */
219 if (!(msym == NULL && sym == NULL) && mfun == NULL && fun == NULL)
220 return 1;
222 /* If we gained symbol information, we switched functions. */
223 if (msym == NULL && sym == NULL && !(mfun == NULL && fun == NULL))
224 return 1;
226 return 0;
229 /* Allocate and initialize a new branch trace function segment at the end of
230 the trace.
231 BTINFO is the branch trace information for the current thread.
232 MFUN and FUN are the symbol information we have for this function.
233 This invalidates all struct btrace_function pointer currently held. */
235 static struct btrace_function *
236 ftrace_new_function (struct btrace_thread_info *btinfo,
237 struct minimal_symbol *mfun,
238 struct symbol *fun)
240 int level;
241 unsigned int number, insn_offset;
243 if (btinfo->functions.empty ())
245 /* Start counting NUMBER and INSN_OFFSET at one. */
246 level = 0;
247 number = 1;
248 insn_offset = 1;
250 else
252 const struct btrace_function *prev = &btinfo->functions.back ();
253 level = prev->level;
254 number = prev->number + 1;
255 insn_offset = prev->insn_offset + ftrace_call_num_insn (prev);
258 return &btinfo->functions.emplace_back (mfun, fun, number, insn_offset,
259 level);
262 /* Update the UP field of a function segment. */
264 static void
265 ftrace_update_caller (struct btrace_function *bfun,
266 struct btrace_function *caller,
267 btrace_function_flags flags)
269 if (bfun->up != 0)
270 ftrace_debug (bfun, "updating caller");
272 bfun->up = caller->number;
273 bfun->flags = flags;
275 ftrace_debug (bfun, "set caller");
276 ftrace_debug (caller, "..to");
279 /* Fix up the caller for all segments of a function. */
281 static void
282 ftrace_fixup_caller (struct btrace_thread_info *btinfo,
283 struct btrace_function *bfun,
284 struct btrace_function *caller,
285 btrace_function_flags flags)
287 unsigned int prev, next;
289 prev = bfun->prev;
290 next = bfun->next;
291 ftrace_update_caller (bfun, caller, flags);
293 /* Update all function segments belonging to the same function. */
294 for (; prev != 0; prev = bfun->prev)
296 bfun = ftrace_find_call_by_number (btinfo, prev);
297 ftrace_update_caller (bfun, caller, flags);
300 for (; next != 0; next = bfun->next)
302 bfun = ftrace_find_call_by_number (btinfo, next);
303 ftrace_update_caller (bfun, caller, flags);
307 /* Add a new function segment for a call at the end of the trace.
308 BTINFO is the branch trace information for the current thread.
309 MFUN and FUN are the symbol information we have for this function. */
311 static struct btrace_function *
312 ftrace_new_call (struct btrace_thread_info *btinfo,
313 struct minimal_symbol *mfun,
314 struct symbol *fun)
316 const unsigned int length = btinfo->functions.size ();
317 struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
319 bfun->up = length;
320 bfun->level += 1;
322 ftrace_debug (bfun, "new call");
324 return bfun;
327 /* Add a new function segment for a tail call at the end of the trace.
328 BTINFO is the branch trace information for the current thread.
329 MFUN and FUN are the symbol information we have for this function. */
331 static struct btrace_function *
332 ftrace_new_tailcall (struct btrace_thread_info *btinfo,
333 struct minimal_symbol *mfun,
334 struct symbol *fun)
336 const unsigned int length = btinfo->functions.size ();
337 struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
339 bfun->up = length;
340 bfun->level += 1;
341 bfun->flags |= BFUN_UP_LINKS_TO_TAILCALL;
343 ftrace_debug (bfun, "new tail call");
345 return bfun;
348 /* Return the caller of BFUN or NULL if there is none. This function skips
349 tail calls in the call chain. BTINFO is the branch trace information for
350 the current thread. */
351 static struct btrace_function *
352 ftrace_get_caller (struct btrace_thread_info *btinfo,
353 struct btrace_function *bfun)
355 for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
356 if ((bfun->flags & BFUN_UP_LINKS_TO_TAILCALL) == 0)
357 return ftrace_find_call_by_number (btinfo, bfun->up);
359 return NULL;
362 /* Find the innermost caller in the back trace of BFUN with MFUN/FUN
363 symbol information. BTINFO is the branch trace information for the current
364 thread. */
366 static struct btrace_function *
367 ftrace_find_caller (struct btrace_thread_info *btinfo,
368 struct btrace_function *bfun,
369 struct minimal_symbol *mfun,
370 struct symbol *fun)
372 for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
374 /* Skip functions with incompatible symbol information. */
375 if (ftrace_function_switched (bfun, mfun, fun))
376 continue;
378 /* This is the function segment we're looking for. */
379 break;
382 return bfun;
385 /* Find the innermost caller in the back trace of BFUN, skipping all
386 function segments that do not end with a call instruction (e.g.
387 tail calls ending with a jump). BTINFO is the branch trace information for
388 the current thread. */
390 static struct btrace_function *
391 ftrace_find_call (struct btrace_thread_info *btinfo,
392 struct btrace_function *bfun)
394 for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
396 /* Skip gaps. */
397 if (bfun->errcode != 0)
398 continue;
400 btrace_insn &last = bfun->insn.back ();
402 if (last.iclass == BTRACE_INSN_CALL)
403 break;
406 return bfun;
409 /* Add a continuation segment for a function into which we return at the end of
410 the trace.
411 BTINFO is the branch trace information for the current thread.
412 MFUN and FUN are the symbol information we have for this function. */
414 static struct btrace_function *
415 ftrace_new_return (struct btrace_thread_info *btinfo,
416 struct minimal_symbol *mfun,
417 struct symbol *fun)
419 struct btrace_function *prev, *bfun, *caller;
421 bfun = ftrace_new_function (btinfo, mfun, fun);
422 prev = ftrace_find_call_by_number (btinfo, bfun->number - 1);
424 /* It is important to start at PREV's caller. Otherwise, we might find
425 PREV itself, if PREV is a recursive function. */
426 caller = ftrace_find_call_by_number (btinfo, prev->up);
427 caller = ftrace_find_caller (btinfo, caller, mfun, fun);
428 if (caller != NULL)
430 /* The caller of PREV is the preceding btrace function segment in this
431 function instance. */
432 gdb_assert (caller->next == 0);
434 caller->next = bfun->number;
435 bfun->prev = caller->number;
437 /* Maintain the function level. */
438 bfun->level = caller->level;
440 /* Maintain the call stack. */
441 bfun->up = caller->up;
442 bfun->flags = caller->flags;
444 ftrace_debug (bfun, "new return");
446 else
448 /* We did not find a caller. This could mean that something went
449 wrong or that the call is simply not included in the trace. */
451 /* Let's search for some actual call. */
452 caller = ftrace_find_call_by_number (btinfo, prev->up);
453 caller = ftrace_find_call (btinfo, caller);
454 if (caller == NULL)
456 /* There is no call in PREV's back trace. We assume that the
457 branch trace did not include it. */
459 /* Let's find the topmost function and add a new caller for it.
460 This should handle a series of initial tail calls. */
461 while (prev->up != 0)
462 prev = ftrace_find_call_by_number (btinfo, prev->up);
464 bfun->level = prev->level - 1;
466 /* Fix up the call stack for PREV. */
467 ftrace_fixup_caller (btinfo, prev, bfun, BFUN_UP_LINKS_TO_RET);
469 ftrace_debug (bfun, "new return - no caller");
471 else
473 /* There is a call in PREV's back trace to which we should have
474 returned but didn't. Let's start a new, separate back trace
475 from PREV's level. */
476 bfun->level = prev->level - 1;
478 /* We fix up the back trace for PREV but leave other function segments
479 on the same level as they are.
480 This should handle things like schedule () correctly where we're
481 switching contexts. */
482 prev->up = bfun->number;
483 prev->flags = BFUN_UP_LINKS_TO_RET;
485 ftrace_debug (bfun, "new return - unknown caller");
489 return bfun;
492 /* Add a new function segment for a function switch at the end of the trace.
493 BTINFO is the branch trace information for the current thread.
494 MFUN and FUN are the symbol information we have for this function. */
496 static struct btrace_function *
497 ftrace_new_switch (struct btrace_thread_info *btinfo,
498 struct minimal_symbol *mfun,
499 struct symbol *fun)
501 struct btrace_function *prev, *bfun;
503 /* This is an unexplained function switch. We can't really be sure about the
504 call stack, yet the best I can think of right now is to preserve it. */
505 bfun = ftrace_new_function (btinfo, mfun, fun);
506 prev = ftrace_find_call_by_number (btinfo, bfun->number - 1);
507 bfun->up = prev->up;
508 bfun->flags = prev->flags;
510 ftrace_debug (bfun, "new switch");
512 return bfun;
515 /* Add a new function segment for a gap in the trace due to a decode error at
516 the end of the trace.
517 BTINFO is the branch trace information for the current thread.
518 ERRCODE is the format-specific error code. */
520 static struct btrace_function *
521 ftrace_new_gap (struct btrace_thread_info *btinfo, int errcode,
522 std::vector<unsigned int> &gaps)
524 struct btrace_function *bfun;
526 if (btinfo->functions.empty ())
527 bfun = ftrace_new_function (btinfo, NULL, NULL);
528 else
530 /* We hijack the previous function segment if it was empty. */
531 bfun = &btinfo->functions.back ();
532 if (bfun->errcode != 0 || !bfun->insn.empty ())
533 bfun = ftrace_new_function (btinfo, NULL, NULL);
536 bfun->errcode = errcode;
537 gaps.push_back (bfun->number);
539 ftrace_debug (bfun, "new gap");
541 return bfun;
544 /* Update the current function segment at the end of the trace in BTINFO with
545 respect to the instruction at PC. This may create new function segments.
546 Return the chronologically latest function segment, never NULL. */
548 static struct btrace_function *
549 ftrace_update_function (struct btrace_thread_info *btinfo, CORE_ADDR pc)
551 struct bound_minimal_symbol bmfun;
552 struct minimal_symbol *mfun;
553 struct symbol *fun;
554 struct btrace_function *bfun;
556 /* Try to determine the function we're in. We use both types of symbols
557 to avoid surprises when we sometimes get a full symbol and sometimes
558 only a minimal symbol. */
559 fun = find_pc_function (pc);
560 bmfun = lookup_minimal_symbol_by_pc (pc);
561 mfun = bmfun.minsym;
563 if (fun == NULL && mfun == NULL)
564 DEBUG_FTRACE ("no symbol at %s", core_addr_to_string_nz (pc));
566 /* If we didn't have a function, we create one. */
567 if (btinfo->functions.empty ())
568 return ftrace_new_function (btinfo, mfun, fun);
570 /* If we had a gap before, we create a function. */
571 bfun = &btinfo->functions.back ();
572 if (bfun->errcode != 0)
573 return ftrace_new_function (btinfo, mfun, fun);
575 /* Check the last instruction, if we have one.
576 We do this check first, since it allows us to fill in the call stack
577 links in addition to the normal flow links. */
578 btrace_insn *last = NULL;
579 if (!bfun->insn.empty ())
580 last = &bfun->insn.back ();
582 if (last != NULL)
584 switch (last->iclass)
586 case BTRACE_INSN_RETURN:
588 const char *fname;
590 /* On some systems, _dl_runtime_resolve returns to the resolved
591 function instead of jumping to it. From our perspective,
592 however, this is a tailcall.
593 If we treated it as return, we wouldn't be able to find the
594 resolved function in our stack back trace. Hence, we would
595 lose the current stack back trace and start anew with an empty
596 back trace. When the resolved function returns, we would then
597 create a stack back trace with the same function names but
598 different frame id's. This will confuse stepping. */
599 fname = ftrace_print_function_name (bfun);
600 if (strcmp (fname, "_dl_runtime_resolve") == 0)
601 return ftrace_new_tailcall (btinfo, mfun, fun);
603 return ftrace_new_return (btinfo, mfun, fun);
606 case BTRACE_INSN_CALL:
607 /* Ignore calls to the next instruction. They are used for PIC. */
608 if (last->pc + last->size == pc)
609 break;
611 return ftrace_new_call (btinfo, mfun, fun);
613 case BTRACE_INSN_JUMP:
615 CORE_ADDR start;
617 start = get_pc_function_start (pc);
619 /* A jump to the start of a function is (typically) a tail call. */
620 if (start == pc)
621 return ftrace_new_tailcall (btinfo, mfun, fun);
623 /* Some versions of _Unwind_RaiseException use an indirect
624 jump to 'return' to the exception handler of the caller
625 handling the exception instead of a return. Let's restrict
626 this heuristic to that and related functions. */
627 const char *fname = ftrace_print_function_name (bfun);
628 if (strncmp (fname, "_Unwind_", strlen ("_Unwind_")) == 0)
630 struct btrace_function *caller
631 = ftrace_find_call_by_number (btinfo, bfun->up);
632 caller = ftrace_find_caller (btinfo, caller, mfun, fun);
633 if (caller != NULL)
634 return ftrace_new_return (btinfo, mfun, fun);
637 /* If we can't determine the function for PC, we treat a jump at
638 the end of the block as tail call if we're switching functions
639 and as an intra-function branch if we don't. */
640 if (start == 0 && ftrace_function_switched (bfun, mfun, fun))
641 return ftrace_new_tailcall (btinfo, mfun, fun);
643 break;
648 /* Check if we're switching functions for some other reason. */
649 if (ftrace_function_switched (bfun, mfun, fun))
651 DEBUG_FTRACE ("switching from %s in %s at %s",
652 ftrace_print_insn_addr (last),
653 ftrace_print_function_name (bfun),
654 ftrace_print_filename (bfun));
656 return ftrace_new_switch (btinfo, mfun, fun);
659 return bfun;
662 /* Add the instruction at PC to BFUN's instructions. */
664 static void
665 ftrace_update_insns (struct btrace_function *bfun, const btrace_insn &insn)
667 bfun->insn.push_back (insn);
669 if (record_debug > 1)
670 ftrace_debug (bfun, "update insn");
673 /* Classify the instruction at PC. */
675 static enum btrace_insn_class
676 ftrace_classify_insn (struct gdbarch *gdbarch, CORE_ADDR pc)
678 enum btrace_insn_class iclass;
680 iclass = BTRACE_INSN_OTHER;
683 if (gdbarch_insn_is_call (gdbarch, pc))
684 iclass = BTRACE_INSN_CALL;
685 else if (gdbarch_insn_is_ret (gdbarch, pc))
686 iclass = BTRACE_INSN_RETURN;
687 else if (gdbarch_insn_is_jump (gdbarch, pc))
688 iclass = BTRACE_INSN_JUMP;
690 catch (const gdb_exception_error &error)
694 return iclass;
697 /* Try to match the back trace at LHS to the back trace at RHS. Returns the
698 number of matching function segments or zero if the back traces do not
699 match. BTINFO is the branch trace information for the current thread. */
701 static int
702 ftrace_match_backtrace (struct btrace_thread_info *btinfo,
703 struct btrace_function *lhs,
704 struct btrace_function *rhs)
706 int matches;
708 for (matches = 0; lhs != NULL && rhs != NULL; ++matches)
710 if (ftrace_function_switched (lhs, rhs->msym, rhs->sym))
711 return 0;
713 lhs = ftrace_get_caller (btinfo, lhs);
714 rhs = ftrace_get_caller (btinfo, rhs);
717 return matches;
720 /* Add ADJUSTMENT to the level of BFUN and succeeding function segments.
721 BTINFO is the branch trace information for the current thread. */
723 static void
724 ftrace_fixup_level (struct btrace_thread_info *btinfo,
725 struct btrace_function *bfun, int adjustment)
727 if (adjustment == 0)
728 return;
730 DEBUG_FTRACE ("fixup level (%+d)", adjustment);
731 ftrace_debug (bfun, "..bfun");
733 while (bfun != NULL)
735 bfun->level += adjustment;
736 bfun = ftrace_find_call_by_number (btinfo, bfun->number + 1);
740 /* Recompute the global level offset. Traverse the function trace and compute
741 the global level offset as the negative of the minimal function level. */
743 static void
744 ftrace_compute_global_level_offset (struct btrace_thread_info *btinfo)
746 int level = INT_MAX;
748 if (btinfo == NULL)
749 return;
751 if (btinfo->functions.empty ())
752 return;
754 unsigned int length = btinfo->functions.size() - 1;
755 for (unsigned int i = 0; i < length; ++i)
756 level = std::min (level, btinfo->functions[i].level);
758 /* The last function segment contains the current instruction, which is not
759 really part of the trace. If it contains just this one instruction, we
760 ignore the segment. */
761 struct btrace_function *last = &btinfo->functions.back();
762 if (last->insn.size () != 1)
763 level = std::min (level, last->level);
765 DEBUG_FTRACE ("setting global level offset: %d", -level);
766 btinfo->level = -level;
769 /* Connect the function segments PREV and NEXT in a bottom-to-top walk as in
770 ftrace_connect_backtrace. BTINFO is the branch trace information for the
771 current thread. */
773 static void
774 ftrace_connect_bfun (struct btrace_thread_info *btinfo,
775 struct btrace_function *prev,
776 struct btrace_function *next)
778 DEBUG_FTRACE ("connecting...");
779 ftrace_debug (prev, "..prev");
780 ftrace_debug (next, "..next");
782 /* The function segments are not yet connected. */
783 gdb_assert (prev->next == 0);
784 gdb_assert (next->prev == 0);
786 prev->next = next->number;
787 next->prev = prev->number;
789 /* We may have moved NEXT to a different function level. */
790 ftrace_fixup_level (btinfo, next, prev->level - next->level);
792 /* If we run out of back trace for one, let's use the other's. */
793 if (prev->up == 0)
795 const btrace_function_flags flags = next->flags;
797 next = ftrace_find_call_by_number (btinfo, next->up);
798 if (next != NULL)
800 DEBUG_FTRACE ("using next's callers");
801 ftrace_fixup_caller (btinfo, prev, next, flags);
804 else if (next->up == 0)
806 const btrace_function_flags flags = prev->flags;
808 prev = ftrace_find_call_by_number (btinfo, prev->up);
809 if (prev != NULL)
811 DEBUG_FTRACE ("using prev's callers");
812 ftrace_fixup_caller (btinfo, next, prev, flags);
815 else
817 /* PREV may have a tailcall caller, NEXT can't. If it does, fixup the up
818 link to add the tail callers to NEXT's back trace.
820 This removes NEXT->UP from NEXT's back trace. It will be added back
821 when connecting NEXT and PREV's callers - provided they exist.
823 If PREV's back trace consists of a series of tail calls without an
824 actual call, there will be no further connection and NEXT's caller will
825 be removed for good. To catch this case, we handle it here and connect
826 the top of PREV's back trace to NEXT's caller. */
827 if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) != 0)
829 struct btrace_function *caller;
830 btrace_function_flags next_flags, prev_flags;
832 /* We checked NEXT->UP above so CALLER can't be NULL. */
833 caller = ftrace_find_call_by_number (btinfo, next->up);
834 next_flags = next->flags;
835 prev_flags = prev->flags;
837 DEBUG_FTRACE ("adding prev's tail calls to next");
839 prev = ftrace_find_call_by_number (btinfo, prev->up);
840 ftrace_fixup_caller (btinfo, next, prev, prev_flags);
842 for (; prev != NULL; prev = ftrace_find_call_by_number (btinfo,
843 prev->up))
845 /* At the end of PREV's back trace, continue with CALLER. */
846 if (prev->up == 0)
848 DEBUG_FTRACE ("fixing up link for tailcall chain");
849 ftrace_debug (prev, "..top");
850 ftrace_debug (caller, "..up");
852 ftrace_fixup_caller (btinfo, prev, caller, next_flags);
854 /* If we skipped any tail calls, this may move CALLER to a
855 different function level.
857 Note that changing CALLER's level is only OK because we
858 know that this is the last iteration of the bottom-to-top
859 walk in ftrace_connect_backtrace.
861 Otherwise we will fix up CALLER's level when we connect it
862 to PREV's caller in the next iteration. */
863 ftrace_fixup_level (btinfo, caller,
864 prev->level - caller->level - 1);
865 break;
868 /* There's nothing to do if we find a real call. */
869 if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) == 0)
871 DEBUG_FTRACE ("will fix up link in next iteration");
872 break;
879 /* Connect function segments on the same level in the back trace at LHS and RHS.
880 The back traces at LHS and RHS are expected to match according to
881 ftrace_match_backtrace. BTINFO is the branch trace information for the
882 current thread. */
884 static void
885 ftrace_connect_backtrace (struct btrace_thread_info *btinfo,
886 struct btrace_function *lhs,
887 struct btrace_function *rhs)
889 while (lhs != NULL && rhs != NULL)
891 struct btrace_function *prev, *next;
893 gdb_assert (!ftrace_function_switched (lhs, rhs->msym, rhs->sym));
895 /* Connecting LHS and RHS may change the up link. */
896 prev = lhs;
897 next = rhs;
899 lhs = ftrace_get_caller (btinfo, lhs);
900 rhs = ftrace_get_caller (btinfo, rhs);
902 ftrace_connect_bfun (btinfo, prev, next);
906 /* Bridge the gap between two function segments left and right of a gap if their
907 respective back traces match in at least MIN_MATCHES functions. BTINFO is
908 the branch trace information for the current thread.
910 Returns non-zero if the gap could be bridged, zero otherwise. */
912 static int
913 ftrace_bridge_gap (struct btrace_thread_info *btinfo,
914 struct btrace_function *lhs, struct btrace_function *rhs,
915 int min_matches)
917 struct btrace_function *best_l, *best_r, *cand_l, *cand_r;
918 int best_matches;
920 DEBUG_FTRACE ("checking gap at insn %u (req matches: %d)",
921 rhs->insn_offset - 1, min_matches);
923 best_matches = 0;
924 best_l = NULL;
925 best_r = NULL;
927 /* We search the back traces of LHS and RHS for valid connections and connect
928 the two function segments that give the longest combined back trace. */
930 for (cand_l = lhs; cand_l != NULL;
931 cand_l = ftrace_get_caller (btinfo, cand_l))
932 for (cand_r = rhs; cand_r != NULL;
933 cand_r = ftrace_get_caller (btinfo, cand_r))
935 int matches;
937 matches = ftrace_match_backtrace (btinfo, cand_l, cand_r);
938 if (best_matches < matches)
940 best_matches = matches;
941 best_l = cand_l;
942 best_r = cand_r;
946 /* We need at least MIN_MATCHES matches. */
947 gdb_assert (min_matches > 0);
948 if (best_matches < min_matches)
949 return 0;
951 DEBUG_FTRACE ("..matches: %d", best_matches);
953 /* We will fix up the level of BEST_R and succeeding function segments such
954 that BEST_R's level matches BEST_L's when we connect BEST_L to BEST_R.
956 This will ignore the level of RHS and following if BEST_R != RHS. I.e. if
957 BEST_R is a successor of RHS in the back trace of RHS (phases 1 and 3).
959 To catch this, we already fix up the level here where we can start at RHS
960 instead of at BEST_R. We will ignore the level fixup when connecting
961 BEST_L to BEST_R as they will already be on the same level. */
962 ftrace_fixup_level (btinfo, rhs, best_l->level - best_r->level);
964 ftrace_connect_backtrace (btinfo, best_l, best_r);
966 return best_matches;
969 /* Try to bridge gaps due to overflow or decode errors by connecting the
970 function segments that are separated by the gap. */
972 static void
973 btrace_bridge_gaps (struct thread_info *tp, std::vector<unsigned int> &gaps)
975 struct btrace_thread_info *btinfo = &tp->btrace;
976 std::vector<unsigned int> remaining;
977 int min_matches;
979 DEBUG ("bridge gaps");
981 /* We require a minimum amount of matches for bridging a gap. The number of
982 required matches will be lowered with each iteration.
984 The more matches the higher our confidence that the bridging is correct.
985 For big gaps or small traces, however, it may not be feasible to require a
986 high number of matches. */
987 for (min_matches = 5; min_matches > 0; --min_matches)
989 /* Let's try to bridge as many gaps as we can. In some cases, we need to
990 skip a gap and revisit it again after we closed later gaps. */
991 while (!gaps.empty ())
993 for (const unsigned int number : gaps)
995 struct btrace_function *gap, *lhs, *rhs;
996 int bridged;
998 gap = ftrace_find_call_by_number (btinfo, number);
1000 /* We may have a sequence of gaps if we run from one error into
1001 the next as we try to re-sync onto the trace stream. Ignore
1002 all but the leftmost gap in such a sequence.
1004 Also ignore gaps at the beginning of the trace. */
1005 lhs = ftrace_find_call_by_number (btinfo, gap->number - 1);
1006 if (lhs == NULL || lhs->errcode != 0)
1007 continue;
1009 /* Skip gaps to the right. */
1010 rhs = ftrace_find_call_by_number (btinfo, gap->number + 1);
1011 while (rhs != NULL && rhs->errcode != 0)
1012 rhs = ftrace_find_call_by_number (btinfo, rhs->number + 1);
1014 /* Ignore gaps at the end of the trace. */
1015 if (rhs == NULL)
1016 continue;
1018 bridged = ftrace_bridge_gap (btinfo, lhs, rhs, min_matches);
1020 /* Keep track of gaps we were not able to bridge and try again.
1021 If we just pushed them to the end of GAPS we would risk an
1022 infinite loop in case we simply cannot bridge a gap. */
1023 if (bridged == 0)
1024 remaining.push_back (number);
1027 /* Let's see if we made any progress. */
1028 if (remaining.size () == gaps.size ())
1029 break;
1031 gaps.clear ();
1032 gaps.swap (remaining);
1035 /* We get here if either GAPS is empty or if GAPS equals REMAINING. */
1036 if (gaps.empty ())
1037 break;
1039 remaining.clear ();
1042 /* We may omit this in some cases. Not sure it is worth the extra
1043 complication, though. */
1044 ftrace_compute_global_level_offset (btinfo);
1047 /* Compute the function branch trace from BTS trace. */
1049 static void
1050 btrace_compute_ftrace_bts (struct thread_info *tp,
1051 const struct btrace_data_bts *btrace,
1052 std::vector<unsigned int> &gaps)
1054 /* We may end up doing target calls that require the current thread to be TP,
1055 for example reading memory through gdb_insn_length. Make sure TP is the
1056 current thread. */
1057 scoped_restore_current_thread restore_thread;
1058 switch_to_thread (tp);
1060 struct btrace_thread_info *btinfo;
1061 unsigned int blk;
1062 int level;
1064 gdbarch *gdbarch = current_inferior ()->arch ();
1065 btinfo = &tp->btrace;
1066 blk = btrace->blocks->size ();
1068 if (btinfo->functions.empty ())
1069 level = INT_MAX;
1070 else
1071 level = -btinfo->level;
1073 while (blk != 0)
1075 CORE_ADDR pc;
1077 blk -= 1;
1079 const btrace_block &block = btrace->blocks->at (blk);
1080 pc = block.begin;
1082 for (;;)
1084 struct btrace_function *bfun;
1085 struct btrace_insn insn;
1086 int size;
1088 /* We should hit the end of the block. Warn if we went too far. */
1089 if (block.end < pc)
1091 /* Indicate the gap in the trace. */
1092 bfun = ftrace_new_gap (btinfo, BDE_BTS_OVERFLOW, gaps);
1094 warning (_("Recorded trace may be corrupted at instruction "
1095 "%u (pc = %s)."), bfun->insn_offset - 1,
1096 core_addr_to_string_nz (pc));
1098 break;
1101 bfun = ftrace_update_function (btinfo, pc);
1103 /* Maintain the function level offset.
1104 For all but the last block, we do it here. */
1105 if (blk != 0)
1106 level = std::min (level, bfun->level);
1108 size = 0;
1111 size = gdb_insn_length (gdbarch, pc);
1113 catch (const gdb_exception_error &error)
1117 insn.pc = pc;
1118 insn.size = size;
1119 insn.iclass = ftrace_classify_insn (gdbarch, pc);
1120 insn.flags = 0;
1122 ftrace_update_insns (bfun, insn);
1124 /* We're done once we pushed the instruction at the end. */
1125 if (block.end == pc)
1126 break;
1128 /* We can't continue if we fail to compute the size. */
1129 if (size <= 0)
1131 /* Indicate the gap in the trace. We just added INSN so we're
1132 not at the beginning. */
1133 bfun = ftrace_new_gap (btinfo, BDE_BTS_INSN_SIZE, gaps);
1135 warning (_("Recorded trace may be incomplete at instruction %u "
1136 "(pc = %s)."), bfun->insn_offset - 1,
1137 core_addr_to_string_nz (pc));
1139 break;
1142 pc += size;
1144 /* Maintain the function level offset.
1145 For the last block, we do it here to not consider the last
1146 instruction.
1147 Since the last instruction corresponds to the current instruction
1148 and is not really part of the execution history, it shouldn't
1149 affect the level. */
1150 if (blk == 0)
1151 level = std::min (level, bfun->level);
1155 /* LEVEL is the minimal function level of all btrace function segments.
1156 Define the global level offset to -LEVEL so all function levels are
1157 normalized to start at zero. */
1158 btinfo->level = -level;
1161 #if defined (HAVE_LIBIPT)
1163 static enum btrace_insn_class
1164 pt_reclassify_insn (enum pt_insn_class iclass)
1166 switch (iclass)
1168 case ptic_call:
1169 return BTRACE_INSN_CALL;
1171 case ptic_return:
1172 return BTRACE_INSN_RETURN;
1174 case ptic_jump:
1175 return BTRACE_INSN_JUMP;
1177 default:
1178 return BTRACE_INSN_OTHER;
1182 /* Return the btrace instruction flags for INSN. */
1184 static btrace_insn_flags
1185 pt_btrace_insn_flags (const struct pt_insn &insn)
1187 btrace_insn_flags flags = 0;
1189 if (insn.speculative)
1190 flags |= BTRACE_INSN_FLAG_SPECULATIVE;
1192 return flags;
1195 /* Return the btrace instruction for INSN. */
1197 static btrace_insn
1198 pt_btrace_insn (const struct pt_insn &insn)
1200 return {(CORE_ADDR) insn.ip, (gdb_byte) insn.size,
1201 pt_reclassify_insn (insn.iclass),
1202 pt_btrace_insn_flags (insn)};
1205 /* Handle instruction decode events (libipt-v2). */
1207 static int
1208 handle_pt_insn_events (struct btrace_thread_info *btinfo,
1209 struct pt_insn_decoder *decoder,
1210 std::vector<unsigned int> &gaps, int status)
1212 #if defined (HAVE_PT_INSN_EVENT)
1213 while (status & pts_event_pending)
1215 struct btrace_function *bfun;
1216 struct pt_event event;
1217 uint64_t offset;
1219 status = pt_insn_event (decoder, &event, sizeof (event));
1220 if (status < 0)
1221 break;
1223 switch (event.type)
1225 default:
1226 break;
1228 case ptev_enabled:
1229 if (event.status_update != 0)
1230 break;
1232 if (event.variant.enabled.resumed == 0 && !btinfo->functions.empty ())
1234 bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1236 pt_insn_get_offset (decoder, &offset);
1238 warning (_("Non-contiguous trace at instruction %u (offset = 0x%"
1239 PRIx64 ")."), bfun->insn_offset - 1, offset);
1242 break;
1244 case ptev_overflow:
1245 bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1247 pt_insn_get_offset (decoder, &offset);
1249 warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ")."),
1250 bfun->insn_offset - 1, offset);
1252 break;
1255 #endif /* defined (HAVE_PT_INSN_EVENT) */
1257 return status;
1260 /* Handle events indicated by flags in INSN (libipt-v1). */
1262 static void
1263 handle_pt_insn_event_flags (struct btrace_thread_info *btinfo,
1264 struct pt_insn_decoder *decoder,
1265 const struct pt_insn &insn,
1266 std::vector<unsigned int> &gaps)
1268 #if defined (HAVE_STRUCT_PT_INSN_ENABLED)
1269 /* Tracing is disabled and re-enabled each time we enter the kernel. Most
1270 times, we continue from the same instruction we stopped before. This is
1271 indicated via the RESUMED instruction flag. The ENABLED instruction flag
1272 means that we continued from some other instruction. Indicate this as a
1273 trace gap except when tracing just started. */
1274 if (insn.enabled && !btinfo->functions.empty ())
1276 struct btrace_function *bfun;
1277 uint64_t offset;
1279 bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1281 pt_insn_get_offset (decoder, &offset);
1283 warning (_("Non-contiguous trace at instruction %u (offset = 0x%" PRIx64
1284 ", pc = 0x%" PRIx64 ")."), bfun->insn_offset - 1, offset,
1285 insn.ip);
1287 #endif /* defined (HAVE_STRUCT_PT_INSN_ENABLED) */
1289 #if defined (HAVE_STRUCT_PT_INSN_RESYNCED)
1290 /* Indicate trace overflows. */
1291 if (insn.resynced)
1293 struct btrace_function *bfun;
1294 uint64_t offset;
1296 bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1298 pt_insn_get_offset (decoder, &offset);
1300 warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ", pc = 0x%"
1301 PRIx64 ")."), bfun->insn_offset - 1, offset, insn.ip);
1303 #endif /* defined (HAVE_STRUCT_PT_INSN_RESYNCED) */
1306 /* Add function branch trace to BTINFO using DECODER. */
1308 static void
1309 ftrace_add_pt (struct btrace_thread_info *btinfo,
1310 struct pt_insn_decoder *decoder,
1311 int *plevel,
1312 std::vector<unsigned int> &gaps)
1314 struct btrace_function *bfun;
1315 uint64_t offset;
1316 int status;
1318 for (;;)
1320 struct pt_insn insn;
1322 status = pt_insn_sync_forward (decoder);
1323 if (status < 0)
1325 if (status != -pte_eos)
1326 warning (_("Failed to synchronize onto the Intel Processor "
1327 "Trace stream: %s."), pt_errstr (pt_errcode (status)));
1328 break;
1331 for (;;)
1333 /* Handle events from the previous iteration or synchronization. */
1334 status = handle_pt_insn_events (btinfo, decoder, gaps, status);
1335 if (status < 0)
1336 break;
1338 status = pt_insn_next (decoder, &insn, sizeof(insn));
1339 if (status < 0)
1340 break;
1342 /* Handle events indicated by flags in INSN. */
1343 handle_pt_insn_event_flags (btinfo, decoder, insn, gaps);
1345 bfun = ftrace_update_function (btinfo, insn.ip);
1347 /* Maintain the function level offset. */
1348 *plevel = std::min (*plevel, bfun->level);
1350 ftrace_update_insns (bfun, pt_btrace_insn (insn));
1353 if (status == -pte_eos)
1354 break;
1356 /* Indicate the gap in the trace. */
1357 bfun = ftrace_new_gap (btinfo, status, gaps);
1359 pt_insn_get_offset (decoder, &offset);
1361 warning (_("Decode error (%d) at instruction %u (offset = 0x%" PRIx64
1362 ", pc = 0x%" PRIx64 "): %s."), status, bfun->insn_offset - 1,
1363 offset, insn.ip, pt_errstr (pt_errcode (status)));
1367 /* A callback function to allow the trace decoder to read the inferior's
1368 memory. */
1370 static int
1371 btrace_pt_readmem_callback (gdb_byte *buffer, size_t size,
1372 const struct pt_asid *asid, uint64_t pc,
1373 void *context)
1375 int result, errcode;
1377 result = (int) size;
1380 errcode = target_read_code ((CORE_ADDR) pc, buffer, size);
1381 if (errcode != 0)
1382 result = -pte_nomap;
1384 catch (const gdb_exception_error &error)
1386 result = -pte_nomap;
1389 return result;
1392 /* Translate the vendor from one enum to another. */
1394 static enum pt_cpu_vendor
1395 pt_translate_cpu_vendor (enum btrace_cpu_vendor vendor)
1397 switch (vendor)
1399 default:
1400 return pcv_unknown;
1402 case CV_INTEL:
1403 return pcv_intel;
1407 /* Finalize the function branch trace after decode. */
1409 static void btrace_finalize_ftrace_pt (struct pt_insn_decoder *decoder,
1410 struct thread_info *tp, int level)
1412 pt_insn_free_decoder (decoder);
1414 /* LEVEL is the minimal function level of all btrace function segments.
1415 Define the global level offset to -LEVEL so all function levels are
1416 normalized to start at zero. */
1417 tp->btrace.level = -level;
1419 /* Add a single last instruction entry for the current PC.
1420 This allows us to compute the backtrace at the current PC using both
1421 standard unwind and btrace unwind.
1422 This extra entry is ignored by all record commands. */
1423 btrace_add_pc (tp);
1426 /* Compute the function branch trace from Intel Processor Trace
1427 format. */
1429 static void
1430 btrace_compute_ftrace_pt (struct thread_info *tp,
1431 const struct btrace_data_pt *btrace,
1432 std::vector<unsigned int> &gaps)
1434 /* We may end up doing target calls that require the current thread to be TP,
1435 for example reading memory through btrace_pt_readmem_callback. Make sure
1436 TP is the current thread. */
1437 scoped_restore_current_thread restore_thread;
1438 switch_to_thread (tp);
1440 struct btrace_thread_info *btinfo;
1441 struct pt_insn_decoder *decoder;
1442 struct pt_config config;
1443 int level, errcode;
1445 if (btrace->size == 0)
1446 return;
1448 btinfo = &tp->btrace;
1449 if (btinfo->functions.empty ())
1450 level = INT_MAX;
1451 else
1452 level = -btinfo->level;
1454 pt_config_init(&config);
1455 config.begin = btrace->data;
1456 config.end = btrace->data + btrace->size;
1458 /* We treat an unknown vendor as 'no errata'. */
1459 if (btrace->config.cpu.vendor != CV_UNKNOWN)
1461 config.cpu.vendor
1462 = pt_translate_cpu_vendor (btrace->config.cpu.vendor);
1463 config.cpu.family = btrace->config.cpu.family;
1464 config.cpu.model = btrace->config.cpu.model;
1465 config.cpu.stepping = btrace->config.cpu.stepping;
1467 errcode = pt_cpu_errata (&config.errata, &config.cpu);
1468 if (errcode < 0)
1469 error (_("Failed to configure the Intel Processor Trace "
1470 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
1473 decoder = pt_insn_alloc_decoder (&config);
1474 if (decoder == NULL)
1475 error (_("Failed to allocate the Intel Processor Trace decoder."));
1479 struct pt_image *image;
1481 image = pt_insn_get_image(decoder);
1482 if (image == NULL)
1483 error (_("Failed to configure the Intel Processor Trace decoder."));
1485 errcode = pt_image_set_callback(image, btrace_pt_readmem_callback, NULL);
1486 if (errcode < 0)
1487 error (_("Failed to configure the Intel Processor Trace decoder: "
1488 "%s."), pt_errstr (pt_errcode (errcode)));
1490 ftrace_add_pt (btinfo, decoder, &level, gaps);
1492 catch (const gdb_exception &error)
1494 /* Indicate a gap in the trace if we quit trace processing. */
1495 if (error.reason == RETURN_QUIT && !btinfo->functions.empty ())
1496 ftrace_new_gap (btinfo, BDE_PT_USER_QUIT, gaps);
1498 btrace_finalize_ftrace_pt (decoder, tp, level);
1500 throw;
1503 btrace_finalize_ftrace_pt (decoder, tp, level);
1506 #else /* defined (HAVE_LIBIPT) */
1508 static void
1509 btrace_compute_ftrace_pt (struct thread_info *tp,
1510 const struct btrace_data_pt *btrace,
1511 std::vector<unsigned int> &gaps)
1513 internal_error (_("Unexpected branch trace format."));
1516 #endif /* defined (HAVE_LIBIPT) */
1518 /* Compute the function branch trace from a block branch trace BTRACE for
1519 a thread given by BTINFO. If CPU is not NULL, overwrite the cpu in the
1520 branch trace configuration. This is currently only used for the PT
1521 format. */
1523 static void
1524 btrace_compute_ftrace_1 (struct thread_info *tp,
1525 struct btrace_data *btrace,
1526 const struct btrace_cpu *cpu,
1527 std::vector<unsigned int> &gaps)
1529 DEBUG ("compute ftrace");
1531 switch (btrace->format)
1533 case BTRACE_FORMAT_NONE:
1534 return;
1536 case BTRACE_FORMAT_BTS:
1537 btrace_compute_ftrace_bts (tp, &btrace->variant.bts, gaps);
1538 return;
1540 case BTRACE_FORMAT_PT:
1541 /* Overwrite the cpu we use for enabling errata workarounds. */
1542 if (cpu != nullptr)
1543 btrace->variant.pt.config.cpu = *cpu;
1545 btrace_compute_ftrace_pt (tp, &btrace->variant.pt, gaps);
1546 return;
1549 internal_error (_("Unknown branch trace format."));
1552 static void
1553 btrace_finalize_ftrace (struct thread_info *tp, std::vector<unsigned int> &gaps)
1555 if (!gaps.empty ())
1557 tp->btrace.ngaps += gaps.size ();
1558 btrace_bridge_gaps (tp, gaps);
1562 static void
1563 btrace_compute_ftrace (struct thread_info *tp, struct btrace_data *btrace,
1564 const struct btrace_cpu *cpu)
1566 std::vector<unsigned int> gaps;
1570 btrace_compute_ftrace_1 (tp, btrace, cpu, gaps);
1572 catch (const gdb_exception &error)
1574 btrace_finalize_ftrace (tp, gaps);
1576 throw;
1579 btrace_finalize_ftrace (tp, gaps);
1582 /* Add an entry for the current PC. */
1584 static void
1585 btrace_add_pc (struct thread_info *tp)
1587 struct btrace_data btrace;
1588 struct regcache *regcache;
1589 CORE_ADDR pc;
1591 regcache = get_thread_regcache (tp);
1592 pc = regcache_read_pc (regcache);
1594 btrace.format = BTRACE_FORMAT_BTS;
1595 btrace.variant.bts.blocks = new std::vector<btrace_block>;
1597 btrace.variant.bts.blocks->emplace_back (pc, pc);
1599 btrace_compute_ftrace (tp, &btrace, NULL);
1602 /* See btrace.h. */
1604 void
1605 btrace_enable (struct thread_info *tp, const struct btrace_config *conf)
1607 if (tp->btrace.target != NULL)
1608 error (_("Recording already enabled on thread %s (%s)."),
1609 print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1611 #if !defined (HAVE_LIBIPT)
1612 if (conf->format == BTRACE_FORMAT_PT)
1613 error (_("Intel Processor Trace support was disabled at compile time."));
1614 #endif /* !defined (HAVE_LIBIPT) */
1616 DEBUG ("enable thread %s (%s)", print_thread_id (tp),
1617 tp->ptid.to_string ().c_str ());
1619 tp->btrace.target = target_enable_btrace (tp, conf);
1621 if (tp->btrace.target == NULL)
1622 error (_("Failed to enable recording on thread %s (%s)."),
1623 print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1625 /* We need to undo the enable in case of errors. */
1628 /* Add an entry for the current PC so we start tracing from where we
1629 enabled it.
1631 If we can't access TP's registers, TP is most likely running. In this
1632 case, we can't really say where tracing was enabled so it should be
1633 safe to simply skip this step.
1635 This is not relevant for BTRACE_FORMAT_PT since the trace will already
1636 start at the PC at which tracing was enabled. */
1637 if (conf->format != BTRACE_FORMAT_PT
1638 && can_access_registers_thread (tp))
1639 btrace_add_pc (tp);
1641 catch (const gdb_exception &exception)
1643 btrace_disable (tp);
1645 throw;
1649 /* See btrace.h. */
1651 const struct btrace_config *
1652 btrace_conf (const struct btrace_thread_info *btinfo)
1654 if (btinfo->target == NULL)
1655 return NULL;
1657 return target_btrace_conf (btinfo->target);
1660 /* See btrace.h. */
1662 void
1663 btrace_disable (struct thread_info *tp)
1665 struct btrace_thread_info *btp = &tp->btrace;
1667 if (btp->target == NULL)
1668 error (_("Recording not enabled on thread %s (%s)."),
1669 print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1671 DEBUG ("disable thread %s (%s)", print_thread_id (tp),
1672 tp->ptid.to_string ().c_str ());
1674 target_disable_btrace (btp->target);
1675 btp->target = NULL;
1677 btrace_clear (tp);
1680 /* See btrace.h. */
1682 void
1683 btrace_teardown (struct thread_info *tp)
1685 struct btrace_thread_info *btp = &tp->btrace;
1687 if (btp->target == NULL)
1688 return;
1690 DEBUG ("teardown thread %s (%s)", print_thread_id (tp),
1691 tp->ptid.to_string ().c_str ());
1693 target_teardown_btrace (btp->target);
1694 btp->target = NULL;
1696 btrace_clear (tp);
1699 /* Stitch branch trace in BTS format. */
1701 static int
1702 btrace_stitch_bts (struct btrace_data_bts *btrace, struct thread_info *tp)
1704 struct btrace_thread_info *btinfo;
1705 struct btrace_function *last_bfun;
1706 btrace_block *first_new_block;
1708 btinfo = &tp->btrace;
1709 gdb_assert (!btinfo->functions.empty ());
1710 gdb_assert (!btrace->blocks->empty ());
1712 last_bfun = &btinfo->functions.back ();
1714 /* If the existing trace ends with a gap, we just glue the traces
1715 together. We need to drop the last (i.e. chronologically first) block
1716 of the new trace, though, since we can't fill in the start address.*/
1717 if (last_bfun->insn.empty ())
1719 btrace->blocks->pop_back ();
1720 return 0;
1723 /* Beware that block trace starts with the most recent block, so the
1724 chronologically first block in the new trace is the last block in
1725 the new trace's block vector. */
1726 first_new_block = &btrace->blocks->back ();
1727 const btrace_insn &last_insn = last_bfun->insn.back ();
1729 /* If the current PC at the end of the block is the same as in our current
1730 trace, there are two explanations:
1731 1. we executed the instruction and some branch brought us back.
1732 2. we have not made any progress.
1733 In the first case, the delta trace vector should contain at least two
1734 entries.
1735 In the second case, the delta trace vector should contain exactly one
1736 entry for the partial block containing the current PC. Remove it. */
1737 if (first_new_block->end == last_insn.pc && btrace->blocks->size () == 1)
1739 btrace->blocks->pop_back ();
1740 return 0;
1743 DEBUG ("stitching %s to %s", ftrace_print_insn_addr (&last_insn),
1744 core_addr_to_string_nz (first_new_block->end));
1746 /* Do a simple sanity check to make sure we don't accidentally end up
1747 with a bad block. This should not occur in practice. */
1748 if (first_new_block->end < last_insn.pc)
1750 warning (_("Error while trying to read delta trace. Falling back to "
1751 "a full read."));
1752 return -1;
1755 /* We adjust the last block to start at the end of our current trace. */
1756 gdb_assert (first_new_block->begin == 0);
1757 first_new_block->begin = last_insn.pc;
1759 /* We simply pop the last insn so we can insert it again as part of
1760 the normal branch trace computation.
1761 Since instruction iterators are based on indices in the instructions
1762 vector, we don't leave any pointers dangling. */
1763 DEBUG ("pruning insn at %s for stitching",
1764 ftrace_print_insn_addr (&last_insn));
1766 last_bfun->insn.pop_back ();
1768 /* The instructions vector may become empty temporarily if this has
1769 been the only instruction in this function segment.
1770 This violates the invariant but will be remedied shortly by
1771 btrace_compute_ftrace when we add the new trace. */
1773 /* The only case where this would hurt is if the entire trace consisted
1774 of just that one instruction. If we remove it, we might turn the now
1775 empty btrace function segment into a gap. But we don't want gaps at
1776 the beginning. To avoid this, we remove the entire old trace. */
1777 if (last_bfun->number == 1 && last_bfun->insn.empty ())
1778 btrace_clear (tp);
1780 return 0;
1783 /* Adjust the block trace in order to stitch old and new trace together.
1784 BTRACE is the new delta trace between the last and the current stop.
1785 TP is the traced thread.
1786 May modifx BTRACE as well as the existing trace in TP.
1787 Return 0 on success, -1 otherwise. */
1789 static int
1790 btrace_stitch_trace (struct btrace_data *btrace, struct thread_info *tp)
1792 /* If we don't have trace, there's nothing to do. */
1793 if (btrace->empty ())
1794 return 0;
1796 switch (btrace->format)
1798 case BTRACE_FORMAT_NONE:
1799 return 0;
1801 case BTRACE_FORMAT_BTS:
1802 return btrace_stitch_bts (&btrace->variant.bts, tp);
1804 case BTRACE_FORMAT_PT:
1805 /* Delta reads are not supported. */
1806 return -1;
1809 internal_error (_("Unknown branch trace format."));
1812 /* Clear the branch trace histories in BTINFO. */
1814 static void
1815 btrace_clear_history (struct btrace_thread_info *btinfo)
1817 xfree (btinfo->insn_history);
1818 xfree (btinfo->call_history);
1819 xfree (btinfo->replay);
1821 btinfo->insn_history = NULL;
1822 btinfo->call_history = NULL;
1823 btinfo->replay = NULL;
1826 /* Clear the branch trace maintenance histories in BTINFO. */
1828 static void
1829 btrace_maint_clear (struct btrace_thread_info *btinfo)
1831 switch (btinfo->data.format)
1833 default:
1834 break;
1836 case BTRACE_FORMAT_BTS:
1837 btinfo->maint.variant.bts.packet_history.begin = 0;
1838 btinfo->maint.variant.bts.packet_history.end = 0;
1839 break;
1841 #if defined (HAVE_LIBIPT)
1842 case BTRACE_FORMAT_PT:
1843 delete btinfo->maint.variant.pt.packets;
1845 btinfo->maint.variant.pt.packets = NULL;
1846 btinfo->maint.variant.pt.packet_history.begin = 0;
1847 btinfo->maint.variant.pt.packet_history.end = 0;
1848 break;
1849 #endif /* defined (HAVE_LIBIPT) */
1853 /* See btrace.h. */
1855 const char *
1856 btrace_decode_error (enum btrace_format format, int errcode)
1858 switch (format)
1860 case BTRACE_FORMAT_BTS:
1861 switch (errcode)
1863 case BDE_BTS_OVERFLOW:
1864 return _("instruction overflow");
1866 case BDE_BTS_INSN_SIZE:
1867 return _("unknown instruction");
1869 default:
1870 break;
1872 break;
1874 #if defined (HAVE_LIBIPT)
1875 case BTRACE_FORMAT_PT:
1876 switch (errcode)
1878 case BDE_PT_USER_QUIT:
1879 return _("trace decode cancelled");
1881 case BDE_PT_DISABLED:
1882 return _("disabled");
1884 case BDE_PT_OVERFLOW:
1885 return _("overflow");
1887 default:
1888 if (errcode < 0)
1889 return pt_errstr (pt_errcode (errcode));
1890 break;
1892 break;
1893 #endif /* defined (HAVE_LIBIPT) */
1895 default:
1896 break;
1899 return _("unknown");
1902 /* See btrace.h. */
1904 void
1905 btrace_fetch (struct thread_info *tp, const struct btrace_cpu *cpu)
1907 struct btrace_thread_info *btinfo;
1908 struct btrace_target_info *tinfo;
1909 struct btrace_data btrace;
1910 int errcode;
1912 DEBUG ("fetch thread %s (%s)", print_thread_id (tp),
1913 tp->ptid.to_string ().c_str ());
1915 btinfo = &tp->btrace;
1916 tinfo = btinfo->target;
1917 if (tinfo == NULL)
1918 return;
1920 /* There's no way we could get new trace while replaying.
1921 On the other hand, delta trace would return a partial record with the
1922 current PC, which is the replay PC, not the last PC, as expected. */
1923 if (btinfo->replay != NULL)
1924 return;
1926 /* With CLI usage, TP is always the current thread when we get here.
1927 However, since we can also store a gdb.Record object in Python
1928 referring to a different thread than the current one, we need to
1929 temporarily set the current thread. */
1930 scoped_restore_current_thread restore_thread;
1931 switch_to_thread (tp);
1933 /* We should not be called on running or exited threads. */
1934 gdb_assert (can_access_registers_thread (tp));
1936 /* Let's first try to extend the trace we already have. */
1937 if (!btinfo->functions.empty ())
1939 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_DELTA);
1940 if (errcode == 0)
1942 /* Success. Let's try to stitch the traces together. */
1943 errcode = btrace_stitch_trace (&btrace, tp);
1945 else
1947 /* We failed to read delta trace. Let's try to read new trace. */
1948 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_NEW);
1950 /* If we got any new trace, discard what we have. */
1951 if (errcode == 0 && !btrace.empty ())
1952 btrace_clear (tp);
1955 /* If we were not able to read the trace, we start over. */
1956 if (errcode != 0)
1958 btrace_clear (tp);
1959 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1962 else
1963 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1965 /* If we were not able to read the branch trace, signal an error. */
1966 if (errcode != 0)
1967 error (_("Failed to read branch trace."));
1969 /* Compute the trace, provided we have any. */
1970 if (!btrace.empty ())
1972 /* Store the raw trace data. The stored data will be cleared in
1973 btrace_clear, so we always append the new trace. */
1974 btrace_data_append (&btinfo->data, &btrace);
1975 btrace_maint_clear (btinfo);
1977 btrace_clear_history (btinfo);
1978 btrace_compute_ftrace (tp, &btrace, cpu);
1982 /* See btrace.h. */
1984 void
1985 btrace_clear (struct thread_info *tp)
1987 struct btrace_thread_info *btinfo;
1989 DEBUG ("clear thread %s (%s)", print_thread_id (tp),
1990 tp->ptid.to_string ().c_str ());
1992 /* Make sure btrace frames that may hold a pointer into the branch
1993 trace data are destroyed. */
1994 reinit_frame_cache ();
1996 btinfo = &tp->btrace;
1998 btinfo->functions.clear ();
1999 btinfo->ngaps = 0;
2001 /* Must clear the maint data before - it depends on BTINFO->DATA. */
2002 btrace_maint_clear (btinfo);
2003 btinfo->data.clear ();
2004 btrace_clear_history (btinfo);
2007 /* See btrace.h. */
2009 void
2010 btrace_free_objfile (struct objfile *objfile)
2012 DEBUG ("free objfile");
2014 for (thread_info *tp : all_non_exited_threads ())
2015 btrace_clear (tp);
2018 /* See btrace.h. */
2020 const struct btrace_insn *
2021 btrace_insn_get (const struct btrace_insn_iterator *it)
2023 const struct btrace_function *bfun;
2024 unsigned int index, end;
2026 index = it->insn_index;
2027 bfun = &it->btinfo->functions[it->call_index];
2029 /* Check if the iterator points to a gap in the trace. */
2030 if (bfun->errcode != 0)
2031 return NULL;
2033 /* The index is within the bounds of this function's instruction vector. */
2034 end = bfun->insn.size ();
2035 gdb_assert (0 < end);
2036 gdb_assert (index < end);
2038 return &bfun->insn[index];
2041 /* See btrace.h. */
2044 btrace_insn_get_error (const struct btrace_insn_iterator *it)
2046 return it->btinfo->functions[it->call_index].errcode;
2049 /* See btrace.h. */
2051 unsigned int
2052 btrace_insn_number (const struct btrace_insn_iterator *it)
2054 return it->btinfo->functions[it->call_index].insn_offset + it->insn_index;
2057 /* See btrace.h. */
2059 void
2060 btrace_insn_begin (struct btrace_insn_iterator *it,
2061 const struct btrace_thread_info *btinfo)
2063 if (btinfo->functions.empty ())
2064 error (_("No trace."));
2066 it->btinfo = btinfo;
2067 it->call_index = 0;
2068 it->insn_index = 0;
2071 /* See btrace.h. */
2073 void
2074 btrace_insn_end (struct btrace_insn_iterator *it,
2075 const struct btrace_thread_info *btinfo)
2077 const struct btrace_function *bfun;
2078 unsigned int length;
2080 if (btinfo->functions.empty ())
2081 error (_("No trace."));
2083 bfun = &btinfo->functions.back ();
2084 length = bfun->insn.size ();
2086 /* The last function may either be a gap or it contains the current
2087 instruction, which is one past the end of the execution trace; ignore
2088 it. */
2089 if (length > 0)
2090 length -= 1;
2092 it->btinfo = btinfo;
2093 it->call_index = bfun->number - 1;
2094 it->insn_index = length;
2097 /* See btrace.h. */
2099 unsigned int
2100 btrace_insn_next (struct btrace_insn_iterator *it, unsigned int stride)
2102 const struct btrace_function *bfun;
2103 unsigned int index, steps;
2105 bfun = &it->btinfo->functions[it->call_index];
2106 steps = 0;
2107 index = it->insn_index;
2109 while (stride != 0)
2111 unsigned int end, space, adv;
2113 end = bfun->insn.size ();
2115 /* An empty function segment represents a gap in the trace. We count
2116 it as one instruction. */
2117 if (end == 0)
2119 const struct btrace_function *next;
2121 next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2122 if (next == NULL)
2123 break;
2125 stride -= 1;
2126 steps += 1;
2128 bfun = next;
2129 index = 0;
2131 continue;
2134 gdb_assert (0 < end);
2135 gdb_assert (index < end);
2137 /* Compute the number of instructions remaining in this segment. */
2138 space = end - index;
2140 /* Advance the iterator as far as possible within this segment. */
2141 adv = std::min (space, stride);
2142 stride -= adv;
2143 index += adv;
2144 steps += adv;
2146 /* Move to the next function if we're at the end of this one. */
2147 if (index == end)
2149 const struct btrace_function *next;
2151 next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2152 if (next == NULL)
2154 /* We stepped past the last function.
2156 Let's adjust the index to point to the last instruction in
2157 the previous function. */
2158 index -= 1;
2159 steps -= 1;
2160 break;
2163 /* We now point to the first instruction in the new function. */
2164 bfun = next;
2165 index = 0;
2168 /* We did make progress. */
2169 gdb_assert (adv > 0);
2172 /* Update the iterator. */
2173 it->call_index = bfun->number - 1;
2174 it->insn_index = index;
2176 return steps;
2179 /* See btrace.h. */
2181 unsigned int
2182 btrace_insn_prev (struct btrace_insn_iterator *it, unsigned int stride)
2184 const struct btrace_function *bfun;
2185 unsigned int index, steps;
2187 bfun = &it->btinfo->functions[it->call_index];
2188 steps = 0;
2189 index = it->insn_index;
2191 while (stride != 0)
2193 unsigned int adv;
2195 /* Move to the previous function if we're at the start of this one. */
2196 if (index == 0)
2198 const struct btrace_function *prev;
2200 prev = ftrace_find_call_by_number (it->btinfo, bfun->number - 1);
2201 if (prev == NULL)
2202 break;
2204 /* We point to one after the last instruction in the new function. */
2205 bfun = prev;
2206 index = bfun->insn.size ();
2208 /* An empty function segment represents a gap in the trace. We count
2209 it as one instruction. */
2210 if (index == 0)
2212 stride -= 1;
2213 steps += 1;
2215 continue;
2219 /* Advance the iterator as far as possible within this segment. */
2220 adv = std::min (index, stride);
2222 stride -= adv;
2223 index -= adv;
2224 steps += adv;
2226 /* We did make progress. */
2227 gdb_assert (adv > 0);
2230 /* Update the iterator. */
2231 it->call_index = bfun->number - 1;
2232 it->insn_index = index;
2234 return steps;
2237 /* See btrace.h. */
2240 btrace_insn_cmp (const struct btrace_insn_iterator *lhs,
2241 const struct btrace_insn_iterator *rhs)
2243 gdb_assert (lhs->btinfo == rhs->btinfo);
2245 if (lhs->call_index != rhs->call_index)
2246 return lhs->call_index - rhs->call_index;
2248 return lhs->insn_index - rhs->insn_index;
2251 /* See btrace.h. */
2254 btrace_find_insn_by_number (struct btrace_insn_iterator *it,
2255 const struct btrace_thread_info *btinfo,
2256 unsigned int number)
2258 const struct btrace_function *bfun;
2259 unsigned int upper, lower;
2261 if (btinfo->functions.empty ())
2262 return 0;
2264 lower = 0;
2265 bfun = &btinfo->functions[lower];
2266 if (number < bfun->insn_offset)
2267 return 0;
2269 upper = btinfo->functions.size () - 1;
2270 bfun = &btinfo->functions[upper];
2271 if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2272 return 0;
2274 /* We assume that there are no holes in the numbering. */
2275 for (;;)
2277 const unsigned int average = lower + (upper - lower) / 2;
2279 bfun = &btinfo->functions[average];
2281 if (number < bfun->insn_offset)
2283 upper = average - 1;
2284 continue;
2287 if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2289 lower = average + 1;
2290 continue;
2293 break;
2296 it->btinfo = btinfo;
2297 it->call_index = bfun->number - 1;
2298 it->insn_index = number - bfun->insn_offset;
2299 return 1;
2302 /* Returns true if the recording ends with a function segment that
2303 contains only a single (i.e. the current) instruction. */
2305 static bool
2306 btrace_ends_with_single_insn (const struct btrace_thread_info *btinfo)
2308 const btrace_function *bfun;
2310 if (btinfo->functions.empty ())
2311 return false;
2313 bfun = &btinfo->functions.back ();
2314 if (bfun->errcode != 0)
2315 return false;
2317 return ftrace_call_num_insn (bfun) == 1;
2320 /* See btrace.h. */
2322 const struct btrace_function *
2323 btrace_call_get (const struct btrace_call_iterator *it)
2325 if (it->index >= it->btinfo->functions.size ())
2326 return NULL;
2328 return &it->btinfo->functions[it->index];
2331 /* See btrace.h. */
2333 unsigned int
2334 btrace_call_number (const struct btrace_call_iterator *it)
2336 const unsigned int length = it->btinfo->functions.size ();
2338 /* If the last function segment contains only a single instruction (i.e. the
2339 current instruction), skip it. */
2340 if ((it->index == length) && btrace_ends_with_single_insn (it->btinfo))
2341 return length;
2343 return it->index + 1;
2346 /* See btrace.h. */
2348 void
2349 btrace_call_begin (struct btrace_call_iterator *it,
2350 const struct btrace_thread_info *btinfo)
2352 if (btinfo->functions.empty ())
2353 error (_("No trace."));
2355 it->btinfo = btinfo;
2356 it->index = 0;
2359 /* See btrace.h. */
2361 void
2362 btrace_call_end (struct btrace_call_iterator *it,
2363 const struct btrace_thread_info *btinfo)
2365 if (btinfo->functions.empty ())
2366 error (_("No trace."));
2368 it->btinfo = btinfo;
2369 it->index = btinfo->functions.size ();
2372 /* See btrace.h. */
2374 unsigned int
2375 btrace_call_next (struct btrace_call_iterator *it, unsigned int stride)
2377 const unsigned int length = it->btinfo->functions.size ();
2379 if (it->index + stride < length - 1)
2380 /* Default case: Simply advance the iterator. */
2381 it->index += stride;
2382 else if (it->index + stride == length - 1)
2384 /* We land exactly at the last function segment. If it contains only one
2385 instruction (i.e. the current instruction) it is not actually part of
2386 the trace. */
2387 if (btrace_ends_with_single_insn (it->btinfo))
2388 it->index = length;
2389 else
2390 it->index = length - 1;
2392 else
2394 /* We land past the last function segment and have to adjust the stride.
2395 If the last function segment contains only one instruction (i.e. the
2396 current instruction) it is not actually part of the trace. */
2397 if (btrace_ends_with_single_insn (it->btinfo))
2398 stride = length - it->index - 1;
2399 else
2400 stride = length - it->index;
2402 it->index = length;
2405 return stride;
2408 /* See btrace.h. */
2410 unsigned int
2411 btrace_call_prev (struct btrace_call_iterator *it, unsigned int stride)
2413 const unsigned int length = it->btinfo->functions.size ();
2414 int steps = 0;
2416 gdb_assert (it->index <= length);
2418 if (stride == 0 || it->index == 0)
2419 return 0;
2421 /* If we are at the end, the first step is a special case. If the last
2422 function segment contains only one instruction (i.e. the current
2423 instruction) it is not actually part of the trace. To be able to step
2424 over this instruction, we need at least one more function segment. */
2425 if ((it->index == length) && (length > 1))
2427 if (btrace_ends_with_single_insn (it->btinfo))
2428 it->index = length - 2;
2429 else
2430 it->index = length - 1;
2432 steps = 1;
2433 stride -= 1;
2436 stride = std::min (stride, it->index);
2438 it->index -= stride;
2439 return steps + stride;
2442 /* See btrace.h. */
2445 btrace_call_cmp (const struct btrace_call_iterator *lhs,
2446 const struct btrace_call_iterator *rhs)
2448 gdb_assert (lhs->btinfo == rhs->btinfo);
2449 return (int) (lhs->index - rhs->index);
2452 /* See btrace.h. */
2455 btrace_find_call_by_number (struct btrace_call_iterator *it,
2456 const struct btrace_thread_info *btinfo,
2457 unsigned int number)
2459 const unsigned int length = btinfo->functions.size ();
2461 if ((number == 0) || (number > length))
2462 return 0;
2464 it->btinfo = btinfo;
2465 it->index = number - 1;
2466 return 1;
2469 /* See btrace.h. */
2471 void
2472 btrace_set_insn_history (struct btrace_thread_info *btinfo,
2473 const struct btrace_insn_iterator *begin,
2474 const struct btrace_insn_iterator *end)
2476 if (btinfo->insn_history == NULL)
2477 btinfo->insn_history = XCNEW (struct btrace_insn_history);
2479 btinfo->insn_history->begin = *begin;
2480 btinfo->insn_history->end = *end;
2483 /* See btrace.h. */
2485 void
2486 btrace_set_call_history (struct btrace_thread_info *btinfo,
2487 const struct btrace_call_iterator *begin,
2488 const struct btrace_call_iterator *end)
2490 gdb_assert (begin->btinfo == end->btinfo);
2492 if (btinfo->call_history == NULL)
2493 btinfo->call_history = XCNEW (struct btrace_call_history);
2495 btinfo->call_history->begin = *begin;
2496 btinfo->call_history->end = *end;
2499 /* See btrace.h. */
2502 btrace_is_replaying (struct thread_info *tp)
2504 return tp->btrace.replay != NULL;
2507 /* See btrace.h. */
2510 btrace_is_empty (struct thread_info *tp)
2512 struct btrace_insn_iterator begin, end;
2513 struct btrace_thread_info *btinfo;
2515 btinfo = &tp->btrace;
2517 if (btinfo->functions.empty ())
2518 return 1;
2520 btrace_insn_begin (&begin, btinfo);
2521 btrace_insn_end (&end, btinfo);
2523 return btrace_insn_cmp (&begin, &end) == 0;
2526 #if defined (HAVE_LIBIPT)
2528 /* Print a single packet. */
2530 static void
2531 pt_print_packet (const struct pt_packet *packet)
2533 switch (packet->type)
2535 default:
2536 gdb_printf (("[??: %x]"), packet->type);
2537 break;
2539 case ppt_psb:
2540 gdb_printf (("psb"));
2541 break;
2543 case ppt_psbend:
2544 gdb_printf (("psbend"));
2545 break;
2547 case ppt_pad:
2548 gdb_printf (("pad"));
2549 break;
2551 case ppt_tip:
2552 gdb_printf (("tip %u: 0x%" PRIx64 ""),
2553 packet->payload.ip.ipc,
2554 packet->payload.ip.ip);
2555 break;
2557 case ppt_tip_pge:
2558 gdb_printf (("tip.pge %u: 0x%" PRIx64 ""),
2559 packet->payload.ip.ipc,
2560 packet->payload.ip.ip);
2561 break;
2563 case ppt_tip_pgd:
2564 gdb_printf (("tip.pgd %u: 0x%" PRIx64 ""),
2565 packet->payload.ip.ipc,
2566 packet->payload.ip.ip);
2567 break;
2569 case ppt_fup:
2570 gdb_printf (("fup %u: 0x%" PRIx64 ""),
2571 packet->payload.ip.ipc,
2572 packet->payload.ip.ip);
2573 break;
2575 case ppt_tnt_8:
2576 gdb_printf (("tnt-8 %u: 0x%" PRIx64 ""),
2577 packet->payload.tnt.bit_size,
2578 packet->payload.tnt.payload);
2579 break;
2581 case ppt_tnt_64:
2582 gdb_printf (("tnt-64 %u: 0x%" PRIx64 ""),
2583 packet->payload.tnt.bit_size,
2584 packet->payload.tnt.payload);
2585 break;
2587 case ppt_pip:
2588 gdb_printf (("pip %" PRIx64 "%s"), packet->payload.pip.cr3,
2589 packet->payload.pip.nr ? (" nr") : (""));
2590 break;
2592 case ppt_tsc:
2593 gdb_printf (("tsc %" PRIx64 ""), packet->payload.tsc.tsc);
2594 break;
2596 case ppt_cbr:
2597 gdb_printf (("cbr %u"), packet->payload.cbr.ratio);
2598 break;
2600 case ppt_mode:
2601 switch (packet->payload.mode.leaf)
2603 default:
2604 gdb_printf (("mode %u"), packet->payload.mode.leaf);
2605 break;
2607 case pt_mol_exec:
2608 gdb_printf (("mode.exec%s%s"),
2609 packet->payload.mode.bits.exec.csl
2610 ? (" cs.l") : (""),
2611 packet->payload.mode.bits.exec.csd
2612 ? (" cs.d") : (""));
2613 break;
2615 case pt_mol_tsx:
2616 gdb_printf (("mode.tsx%s%s"),
2617 packet->payload.mode.bits.tsx.intx
2618 ? (" intx") : (""),
2619 packet->payload.mode.bits.tsx.abrt
2620 ? (" abrt") : (""));
2621 break;
2623 break;
2625 case ppt_ovf:
2626 gdb_printf (("ovf"));
2627 break;
2629 case ppt_stop:
2630 gdb_printf (("stop"));
2631 break;
2633 case ppt_vmcs:
2634 gdb_printf (("vmcs %" PRIx64 ""), packet->payload.vmcs.base);
2635 break;
2637 case ppt_tma:
2638 gdb_printf (("tma %x %x"), packet->payload.tma.ctc,
2639 packet->payload.tma.fc);
2640 break;
2642 case ppt_mtc:
2643 gdb_printf (("mtc %x"), packet->payload.mtc.ctc);
2644 break;
2646 case ppt_cyc:
2647 gdb_printf (("cyc %" PRIx64 ""), packet->payload.cyc.value);
2648 break;
2650 case ppt_mnt:
2651 gdb_printf (("mnt %" PRIx64 ""), packet->payload.mnt.payload);
2652 break;
2656 /* Decode packets into MAINT using DECODER. */
2658 static void
2659 btrace_maint_decode_pt (struct btrace_maint_info *maint,
2660 struct pt_packet_decoder *decoder)
2662 int errcode;
2664 if (maint->variant.pt.packets == NULL)
2665 maint->variant.pt.packets = new std::vector<btrace_pt_packet>;
2667 for (;;)
2669 struct btrace_pt_packet packet;
2671 errcode = pt_pkt_sync_forward (decoder);
2672 if (errcode < 0)
2673 break;
2675 for (;;)
2677 pt_pkt_get_offset (decoder, &packet.offset);
2679 errcode = pt_pkt_next (decoder, &packet.packet,
2680 sizeof(packet.packet));
2681 if (errcode < 0)
2682 break;
2684 if (maint_btrace_pt_skip_pad == 0 || packet.packet.type != ppt_pad)
2686 packet.errcode = pt_errcode (errcode);
2687 maint->variant.pt.packets->push_back (packet);
2691 if (errcode == -pte_eos)
2692 break;
2694 packet.errcode = pt_errcode (errcode);
2695 maint->variant.pt.packets->push_back (packet);
2697 warning (_("Error at trace offset 0x%" PRIx64 ": %s."),
2698 packet.offset, pt_errstr (packet.errcode));
2701 if (errcode != -pte_eos)
2702 warning (_("Failed to synchronize onto the Intel Processor Trace "
2703 "stream: %s."), pt_errstr (pt_errcode (errcode)));
2706 /* Update the packet history in BTINFO. */
2708 static void
2709 btrace_maint_update_pt_packets (struct btrace_thread_info *btinfo)
2711 struct pt_packet_decoder *decoder;
2712 const struct btrace_cpu *cpu;
2713 struct btrace_data_pt *pt;
2714 struct pt_config config;
2715 int errcode;
2717 pt = &btinfo->data.variant.pt;
2719 /* Nothing to do if there is no trace. */
2720 if (pt->size == 0)
2721 return;
2723 memset (&config, 0, sizeof(config));
2725 config.size = sizeof (config);
2726 config.begin = pt->data;
2727 config.end = pt->data + pt->size;
2729 cpu = record_btrace_get_cpu ();
2730 if (cpu == nullptr)
2731 cpu = &pt->config.cpu;
2733 /* We treat an unknown vendor as 'no errata'. */
2734 if (cpu->vendor != CV_UNKNOWN)
2736 config.cpu.vendor = pt_translate_cpu_vendor (cpu->vendor);
2737 config.cpu.family = cpu->family;
2738 config.cpu.model = cpu->model;
2739 config.cpu.stepping = cpu->stepping;
2741 errcode = pt_cpu_errata (&config.errata, &config.cpu);
2742 if (errcode < 0)
2743 error (_("Failed to configure the Intel Processor Trace "
2744 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
2747 decoder = pt_pkt_alloc_decoder (&config);
2748 if (decoder == NULL)
2749 error (_("Failed to allocate the Intel Processor Trace decoder."));
2753 btrace_maint_decode_pt (&btinfo->maint, decoder);
2755 catch (const gdb_exception &except)
2757 pt_pkt_free_decoder (decoder);
2759 if (except.reason < 0)
2760 throw;
2763 pt_pkt_free_decoder (decoder);
2766 #endif /* !defined (HAVE_LIBIPT) */
2768 /* Update the packet maintenance information for BTINFO and store the
2769 low and high bounds into BEGIN and END, respectively.
2770 Store the current iterator state into FROM and TO. */
2772 static void
2773 btrace_maint_update_packets (struct btrace_thread_info *btinfo,
2774 unsigned int *begin, unsigned int *end,
2775 unsigned int *from, unsigned int *to)
2777 switch (btinfo->data.format)
2779 default:
2780 *begin = 0;
2781 *end = 0;
2782 *from = 0;
2783 *to = 0;
2784 break;
2786 case BTRACE_FORMAT_BTS:
2787 /* Nothing to do - we operate directly on BTINFO->DATA. */
2788 *begin = 0;
2789 *end = btinfo->data.variant.bts.blocks->size ();
2790 *from = btinfo->maint.variant.bts.packet_history.begin;
2791 *to = btinfo->maint.variant.bts.packet_history.end;
2792 break;
2794 #if defined (HAVE_LIBIPT)
2795 case BTRACE_FORMAT_PT:
2796 if (btinfo->maint.variant.pt.packets == nullptr)
2797 btinfo->maint.variant.pt.packets = new std::vector<btrace_pt_packet>;
2799 if (btinfo->maint.variant.pt.packets->empty ())
2800 btrace_maint_update_pt_packets (btinfo);
2802 *begin = 0;
2803 *end = btinfo->maint.variant.pt.packets->size ();
2804 *from = btinfo->maint.variant.pt.packet_history.begin;
2805 *to = btinfo->maint.variant.pt.packet_history.end;
2806 break;
2807 #endif /* defined (HAVE_LIBIPT) */
2811 /* Print packets in BTINFO from BEGIN (inclusive) until END (exclusive) and
2812 update the current iterator position. */
2814 static void
2815 btrace_maint_print_packets (struct btrace_thread_info *btinfo,
2816 unsigned int begin, unsigned int end)
2818 switch (btinfo->data.format)
2820 default:
2821 break;
2823 case BTRACE_FORMAT_BTS:
2825 const std::vector<btrace_block> &blocks
2826 = *btinfo->data.variant.bts.blocks;
2827 unsigned int blk;
2829 for (blk = begin; blk < end; ++blk)
2831 const btrace_block &block = blocks.at (blk);
2833 gdb_printf ("%u\tbegin: %s, end: %s\n", blk,
2834 core_addr_to_string_nz (block.begin),
2835 core_addr_to_string_nz (block.end));
2838 btinfo->maint.variant.bts.packet_history.begin = begin;
2839 btinfo->maint.variant.bts.packet_history.end = end;
2841 break;
2843 #if defined (HAVE_LIBIPT)
2844 case BTRACE_FORMAT_PT:
2846 const std::vector<btrace_pt_packet> &packets
2847 = *btinfo->maint.variant.pt.packets;
2848 unsigned int pkt;
2850 for (pkt = begin; pkt < end; ++pkt)
2852 const struct btrace_pt_packet &packet = packets.at (pkt);
2854 gdb_printf ("%u\t", pkt);
2855 gdb_printf ("0x%" PRIx64 "\t", packet.offset);
2857 if (packet.errcode == pte_ok)
2858 pt_print_packet (&packet.packet);
2859 else
2860 gdb_printf ("[error: %s]", pt_errstr (packet.errcode));
2862 gdb_printf ("\n");
2865 btinfo->maint.variant.pt.packet_history.begin = begin;
2866 btinfo->maint.variant.pt.packet_history.end = end;
2868 break;
2869 #endif /* defined (HAVE_LIBIPT) */
2873 /* Read a number from an argument string. */
2875 static unsigned int
2876 get_uint (const char **arg)
2878 const char *begin, *pos;
2879 char *end;
2880 unsigned long number;
2882 begin = *arg;
2883 pos = skip_spaces (begin);
2885 if (!isdigit (*pos))
2886 error (_("Expected positive number, got: %s."), pos);
2888 number = strtoul (pos, &end, 10);
2889 if (number > UINT_MAX)
2890 error (_("Number too big."));
2892 *arg += (end - begin);
2894 return (unsigned int) number;
2897 /* Read a context size from an argument string. */
2899 static int
2900 get_context_size (const char **arg)
2902 const char *pos = skip_spaces (*arg);
2904 if (!isdigit (*pos))
2905 error (_("Expected positive number, got: %s."), pos);
2907 char *end;
2908 long result = strtol (pos, &end, 10);
2909 *arg = end;
2910 return result;
2913 /* Complain about junk at the end of an argument string. */
2915 static void
2916 no_chunk (const char *arg)
2918 if (*arg != 0)
2919 error (_("Junk after argument: %s."), arg);
2922 /* The "maintenance btrace packet-history" command. */
2924 static void
2925 maint_btrace_packet_history_cmd (const char *arg, int from_tty)
2927 struct btrace_thread_info *btinfo;
2928 unsigned int size, begin, end, from, to;
2930 thread_info *tp = current_inferior ()->find_thread (inferior_ptid);
2931 if (tp == NULL)
2932 error (_("No thread."));
2934 size = 10;
2935 btinfo = &tp->btrace;
2937 btrace_maint_update_packets (btinfo, &begin, &end, &from, &to);
2938 if (begin == end)
2940 gdb_printf (_("No trace.\n"));
2941 return;
2944 if (arg == NULL || *arg == 0 || strcmp (arg, "+") == 0)
2946 from = to;
2948 if (end - from < size)
2949 size = end - from;
2950 to = from + size;
2952 else if (strcmp (arg, "-") == 0)
2954 to = from;
2956 if (to - begin < size)
2957 size = to - begin;
2958 from = to - size;
2960 else
2962 from = get_uint (&arg);
2963 if (end <= from)
2964 error (_("'%u' is out of range."), from);
2966 arg = skip_spaces (arg);
2967 if (*arg == ',')
2969 arg = skip_spaces (++arg);
2971 if (*arg == '+')
2973 arg += 1;
2974 size = get_context_size (&arg);
2976 no_chunk (arg);
2978 if (end - from < size)
2979 size = end - from;
2980 to = from + size;
2982 else if (*arg == '-')
2984 arg += 1;
2985 size = get_context_size (&arg);
2987 no_chunk (arg);
2989 /* Include the packet given as first argument. */
2990 from += 1;
2991 to = from;
2993 if (to - begin < size)
2994 size = to - begin;
2995 from = to - size;
2997 else
2999 to = get_uint (&arg);
3001 /* Include the packet at the second argument and silently
3002 truncate the range. */
3003 if (to < end)
3004 to += 1;
3005 else
3006 to = end;
3008 no_chunk (arg);
3011 else
3013 no_chunk (arg);
3015 if (end - from < size)
3016 size = end - from;
3017 to = from + size;
3020 dont_repeat ();
3023 btrace_maint_print_packets (btinfo, from, to);
3026 /* The "maintenance btrace clear-packet-history" command. */
3028 static void
3029 maint_btrace_clear_packet_history_cmd (const char *args, int from_tty)
3031 if (args != NULL && *args != 0)
3032 error (_("Invalid argument."));
3034 if (inferior_ptid == null_ptid)
3035 error (_("No thread."));
3037 thread_info *tp = inferior_thread ();
3038 btrace_thread_info *btinfo = &tp->btrace;
3040 /* Must clear the maint data before - it depends on BTINFO->DATA. */
3041 btrace_maint_clear (btinfo);
3042 btinfo->data.clear ();
3045 /* The "maintenance btrace clear" command. */
3047 static void
3048 maint_btrace_clear_cmd (const char *args, int from_tty)
3050 if (args != NULL && *args != 0)
3051 error (_("Invalid argument."));
3053 if (inferior_ptid == null_ptid)
3054 error (_("No thread."));
3056 thread_info *tp = inferior_thread ();
3057 btrace_clear (tp);
3060 /* The "maintenance info btrace" command. */
3062 static void
3063 maint_info_btrace_cmd (const char *args, int from_tty)
3065 struct btrace_thread_info *btinfo;
3066 const struct btrace_config *conf;
3068 if (args != NULL && *args != 0)
3069 error (_("Invalid argument."));
3071 if (inferior_ptid == null_ptid)
3072 error (_("No thread."));
3074 thread_info *tp = inferior_thread ();
3076 btinfo = &tp->btrace;
3078 conf = btrace_conf (btinfo);
3079 if (conf == NULL)
3080 error (_("No btrace configuration."));
3082 gdb_printf (_("Format: %s.\n"),
3083 btrace_format_string (conf->format));
3085 switch (conf->format)
3087 default:
3088 break;
3090 case BTRACE_FORMAT_BTS:
3091 gdb_printf (_("Number of packets: %zu.\n"),
3092 btinfo->data.variant.bts.blocks->size ());
3093 break;
3095 #if defined (HAVE_LIBIPT)
3096 case BTRACE_FORMAT_PT:
3098 struct pt_version version;
3100 version = pt_library_version ();
3101 gdb_printf (_("Version: %u.%u.%u%s.\n"), version.major,
3102 version.minor, version.build,
3103 version.ext != NULL ? version.ext : "");
3105 btrace_maint_update_pt_packets (btinfo);
3106 gdb_printf (_("Number of packets: %zu.\n"),
3107 ((btinfo->maint.variant.pt.packets == nullptr)
3108 ? 0 : btinfo->maint.variant.pt.packets->size ()));
3110 break;
3111 #endif /* defined (HAVE_LIBIPT) */
3115 /* The "maint show btrace pt skip-pad" show value function. */
3117 static void
3118 show_maint_btrace_pt_skip_pad (struct ui_file *file, int from_tty,
3119 struct cmd_list_element *c,
3120 const char *value)
3122 gdb_printf (file, _("Skip PAD packets is %s.\n"), value);
3126 /* Initialize btrace maintenance commands. */
3128 void _initialize_btrace ();
3129 void
3130 _initialize_btrace ()
3132 add_cmd ("btrace", class_maintenance, maint_info_btrace_cmd,
3133 _("Info about branch tracing data."), &maintenanceinfolist);
3135 add_basic_prefix_cmd ("btrace", class_maintenance,
3136 _("Branch tracing maintenance commands."),
3137 &maint_btrace_cmdlist, 0, &maintenancelist);
3139 add_setshow_prefix_cmd ("btrace", class_maintenance,
3140 _("Set branch tracing specific variables."),
3141 _("Show branch tracing specific variables."),
3142 &maint_btrace_set_cmdlist,
3143 &maint_btrace_show_cmdlist,
3144 &maintenance_set_cmdlist,
3145 &maintenance_show_cmdlist);
3147 add_setshow_prefix_cmd ("pt", class_maintenance,
3148 _("Set Intel Processor Trace specific variables."),
3149 _("Show Intel Processor Trace specific variables."),
3150 &maint_btrace_pt_set_cmdlist,
3151 &maint_btrace_pt_show_cmdlist,
3152 &maint_btrace_set_cmdlist,
3153 &maint_btrace_show_cmdlist);
3155 add_setshow_boolean_cmd ("skip-pad", class_maintenance,
3156 &maint_btrace_pt_skip_pad, _("\
3157 Set whether PAD packets should be skipped in the btrace packet history."), _("\
3158 Show whether PAD packets should be skipped in the btrace packet history."),_("\
3159 When enabled, PAD packets are ignored in the btrace packet history."),
3160 NULL, show_maint_btrace_pt_skip_pad,
3161 &maint_btrace_pt_set_cmdlist,
3162 &maint_btrace_pt_show_cmdlist);
3164 add_cmd ("packet-history", class_maintenance, maint_btrace_packet_history_cmd,
3165 _("Print the raw branch tracing data.\n\
3166 With no argument, print ten more packets after the previous ten-line print.\n\
3167 With '-' as argument print ten packets before a previous ten-line print.\n\
3168 One argument specifies the starting packet of a ten-line print.\n\
3169 Two arguments with comma between specify starting and ending packets to \
3170 print.\n\
3171 Preceded with '+'/'-' the second argument specifies the distance from the \
3172 first."),
3173 &maint_btrace_cmdlist);
3175 add_cmd ("clear-packet-history", class_maintenance,
3176 maint_btrace_clear_packet_history_cmd,
3177 _("Clears the branch tracing packet history.\n\
3178 Discards the raw branch tracing data but not the execution history data."),
3179 &maint_btrace_cmdlist);
3181 add_cmd ("clear", class_maintenance, maint_btrace_clear_cmd,
3182 _("Clears the branch tracing data.\n\
3183 Discards the raw branch tracing data and the execution history data.\n\
3184 The next 'record' command will fetch the branch tracing data anew."),
3185 &maint_btrace_cmdlist);