1 /* Branch trace support for GDB, the GNU debugger.
3 Copyright (C) 2013-2018 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/>. */
24 #include "gdbthread.h"
31 #include "filenames.h"
32 #include "xml-support.h"
36 #include "cli/cli-utils.h"
38 /* For maintenance commands. */
39 #include "record-btrace.h"
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 int maint_btrace_pt_skip_pad = 1;
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...) \
63 if (record_debug != 0) \
64 fprintf_unfiltered (gdb_stdlog, \
65 "[btrace] " msg "\n", ##args); \
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. */
75 ftrace_print_function_name (const struct btrace_function *bfun)
77 struct minimal_symbol *msym;
84 return SYMBOL_PRINT_NAME (sym);
87 return MSYMBOL_PRINT_NAME (msym);
92 /* Return the file name of a recorded function segment for printing.
93 This function never returns NULL. */
96 ftrace_print_filename (const struct btrace_function *bfun)
104 filename = symtab_to_filename_for_display (symbol_symtab (sym));
106 filename = "<unknown>";
111 /* Return a string representation of the address of an instruction.
112 This function never returns NULL. */
115 ftrace_print_insn_addr (const struct btrace_insn *insn)
120 return core_addr_to_string_nz (insn->pc);
123 /* Print an ftrace debug status message. */
126 ftrace_debug (const struct btrace_function *bfun, const char *prefix)
128 const char *fun, *file;
129 unsigned int ibegin, iend;
132 fun = ftrace_print_function_name (bfun);
133 file = ftrace_print_filename (bfun);
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. */
146 ftrace_call_num_insn (const struct btrace_function* bfun)
151 /* A gap is always counted as one instruction. */
152 if (bfun->errcode != 0)
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,
165 if (number == 0 || number > btinfo->functions.size ())
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,
177 if (number == 0 || number > btinfo->functions.size ())
180 return &btinfo->functions[number - 1];
183 /* Return non-zero if BFUN does not match MFUN and FUN,
184 return zero otherwise. */
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;
197 /* If the minimal symbol changed, we certainly switched functions. */
198 if (mfun != NULL && msym != NULL
199 && strcmp (MSYMBOL_LINKAGE_NAME (mfun), MSYMBOL_LINKAGE_NAME (msym)) != 0)
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 (SYMBOL_LINKAGE_NAME (fun), SYMBOL_LINKAGE_NAME (sym)) != 0)
211 /* Check the location of those functions, as well. */
212 bfname = symtab_to_fullname (symbol_symtab (sym));
213 fname = symtab_to_fullname (symbol_symtab (fun));
214 if (filename_cmp (fname, bfname) != 0)
218 /* If we lost symbol information, we switched functions. */
219 if (!(msym == NULL && sym == NULL) && mfun == NULL && fun == NULL)
222 /* If we gained symbol information, we switched functions. */
223 if (msym == NULL && sym == NULL && !(mfun == NULL && fun == NULL))
229 /* Allocate and initialize a new branch trace function segment at the end of
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,
241 unsigned int number, insn_offset;
243 if (btinfo->functions.empty ())
245 /* Start counting NUMBER and INSN_OFFSET at one. */
252 const struct btrace_function *prev = &btinfo->functions.back ();
254 number = prev->number + 1;
255 insn_offset = prev->insn_offset + ftrace_call_num_insn (prev);
258 btinfo->functions.emplace_back (mfun, fun, number, insn_offset, level);
259 return &btinfo->functions.back ();
262 /* Update the UP field of a function segment. */
265 ftrace_update_caller (struct btrace_function *bfun,
266 struct btrace_function *caller,
267 enum btrace_function_flag flags)
270 ftrace_debug (bfun, "updating caller");
272 bfun->up = caller->number;
275 ftrace_debug (bfun, "set caller");
276 ftrace_debug (caller, "..to");
279 /* Fix up the caller for all segments of a function. */
282 ftrace_fixup_caller (struct btrace_thread_info *btinfo,
283 struct btrace_function *bfun,
284 struct btrace_function *caller,
285 enum btrace_function_flag flags)
287 unsigned int prev, 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,
316 const unsigned int length = btinfo->functions.size ();
317 struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
322 ftrace_debug (bfun, "new call");
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,
336 const unsigned int length = btinfo->functions.size ();
337 struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
341 bfun->flags |= BFUN_UP_LINKS_TO_TAILCALL;
343 ftrace_debug (bfun, "new tail call");
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);
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
366 static struct btrace_function *
367 ftrace_find_caller (struct btrace_thread_info *btinfo,
368 struct btrace_function *bfun,
369 struct minimal_symbol *mfun,
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))
378 /* This is the function segment we're looking for. */
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))
397 if (bfun->errcode != 0)
400 btrace_insn &last = bfun->insn.back ();
402 if (last.iclass == BTRACE_INSN_CALL)
409 /* Add a continuation segment for a function into which we return at the end of
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,
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);
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");
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);
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");
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");
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,
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);
508 bfun->flags = prev->flags;
510 ftrace_debug (bfun, "new switch");
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);
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");
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;
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);
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 ();
584 switch (last->iclass)
586 case BTRACE_INSN_RETURN:
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)
611 return ftrace_new_call (btinfo, mfun, fun);
613 case BTRACE_INSN_JUMP:
617 start = get_pc_function_start (pc);
619 /* A jump to the start of a function is (typically) a tail call. */
621 return ftrace_new_tailcall (btinfo, mfun, fun);
623 /* If we can't determine the function for PC, we treat a jump at
624 the end of the block as tail call if we're switching functions
625 and as an intra-function branch if we don't. */
626 if (start == 0 && ftrace_function_switched (bfun, mfun, fun))
627 return ftrace_new_tailcall (btinfo, mfun, fun);
634 /* Check if we're switching functions for some other reason. */
635 if (ftrace_function_switched (bfun, mfun, fun))
637 DEBUG_FTRACE ("switching from %s in %s at %s",
638 ftrace_print_insn_addr (last),
639 ftrace_print_function_name (bfun),
640 ftrace_print_filename (bfun));
642 return ftrace_new_switch (btinfo, mfun, fun);
648 /* Add the instruction at PC to BFUN's instructions. */
651 ftrace_update_insns (struct btrace_function *bfun, const btrace_insn &insn)
653 bfun->insn.push_back (insn);
655 if (record_debug > 1)
656 ftrace_debug (bfun, "update insn");
659 /* Classify the instruction at PC. */
661 static enum btrace_insn_class
662 ftrace_classify_insn (struct gdbarch *gdbarch, CORE_ADDR pc)
664 enum btrace_insn_class iclass;
666 iclass = BTRACE_INSN_OTHER;
669 if (gdbarch_insn_is_call (gdbarch, pc))
670 iclass = BTRACE_INSN_CALL;
671 else if (gdbarch_insn_is_ret (gdbarch, pc))
672 iclass = BTRACE_INSN_RETURN;
673 else if (gdbarch_insn_is_jump (gdbarch, pc))
674 iclass = BTRACE_INSN_JUMP;
676 CATCH (error, RETURN_MASK_ERROR)
684 /* Try to match the back trace at LHS to the back trace at RHS. Returns the
685 number of matching function segments or zero if the back traces do not
686 match. BTINFO is the branch trace information for the current thread. */
689 ftrace_match_backtrace (struct btrace_thread_info *btinfo,
690 struct btrace_function *lhs,
691 struct btrace_function *rhs)
695 for (matches = 0; lhs != NULL && rhs != NULL; ++matches)
697 if (ftrace_function_switched (lhs, rhs->msym, rhs->sym))
700 lhs = ftrace_get_caller (btinfo, lhs);
701 rhs = ftrace_get_caller (btinfo, rhs);
707 /* Add ADJUSTMENT to the level of BFUN and succeeding function segments.
708 BTINFO is the branch trace information for the current thread. */
711 ftrace_fixup_level (struct btrace_thread_info *btinfo,
712 struct btrace_function *bfun, int adjustment)
717 DEBUG_FTRACE ("fixup level (%+d)", adjustment);
718 ftrace_debug (bfun, "..bfun");
722 bfun->level += adjustment;
723 bfun = ftrace_find_call_by_number (btinfo, bfun->number + 1);
727 /* Recompute the global level offset. Traverse the function trace and compute
728 the global level offset as the negative of the minimal function level. */
731 ftrace_compute_global_level_offset (struct btrace_thread_info *btinfo)
738 if (btinfo->functions.empty ())
741 unsigned int length = btinfo->functions.size() - 1;
742 for (unsigned int i = 0; i < length; ++i)
743 level = std::min (level, btinfo->functions[i].level);
745 /* The last function segment contains the current instruction, which is not
746 really part of the trace. If it contains just this one instruction, we
747 ignore the segment. */
748 struct btrace_function *last = &btinfo->functions.back();
749 if (last->insn.size () != 1)
750 level = std::min (level, last->level);
752 DEBUG_FTRACE ("setting global level offset: %d", -level);
753 btinfo->level = -level;
756 /* Connect the function segments PREV and NEXT in a bottom-to-top walk as in
757 ftrace_connect_backtrace. BTINFO is the branch trace information for the
761 ftrace_connect_bfun (struct btrace_thread_info *btinfo,
762 struct btrace_function *prev,
763 struct btrace_function *next)
765 DEBUG_FTRACE ("connecting...");
766 ftrace_debug (prev, "..prev");
767 ftrace_debug (next, "..next");
769 /* The function segments are not yet connected. */
770 gdb_assert (prev->next == 0);
771 gdb_assert (next->prev == 0);
773 prev->next = next->number;
774 next->prev = prev->number;
776 /* We may have moved NEXT to a different function level. */
777 ftrace_fixup_level (btinfo, next, prev->level - next->level);
779 /* If we run out of back trace for one, let's use the other's. */
782 const btrace_function_flags flags = next->flags;
784 next = ftrace_find_call_by_number (btinfo, next->up);
787 DEBUG_FTRACE ("using next's callers");
788 ftrace_fixup_caller (btinfo, prev, next, flags);
791 else if (next->up == 0)
793 const btrace_function_flags flags = prev->flags;
795 prev = ftrace_find_call_by_number (btinfo, prev->up);
798 DEBUG_FTRACE ("using prev's callers");
799 ftrace_fixup_caller (btinfo, next, prev, flags);
804 /* PREV may have a tailcall caller, NEXT can't. If it does, fixup the up
805 link to add the tail callers to NEXT's back trace.
807 This removes NEXT->UP from NEXT's back trace. It will be added back
808 when connecting NEXT and PREV's callers - provided they exist.
810 If PREV's back trace consists of a series of tail calls without an
811 actual call, there will be no further connection and NEXT's caller will
812 be removed for good. To catch this case, we handle it here and connect
813 the top of PREV's back trace to NEXT's caller. */
814 if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) != 0)
816 struct btrace_function *caller;
817 btrace_function_flags next_flags, prev_flags;
819 /* We checked NEXT->UP above so CALLER can't be NULL. */
820 caller = ftrace_find_call_by_number (btinfo, next->up);
821 next_flags = next->flags;
822 prev_flags = prev->flags;
824 DEBUG_FTRACE ("adding prev's tail calls to next");
826 prev = ftrace_find_call_by_number (btinfo, prev->up);
827 ftrace_fixup_caller (btinfo, next, prev, prev_flags);
829 for (; prev != NULL; prev = ftrace_find_call_by_number (btinfo,
832 /* At the end of PREV's back trace, continue with CALLER. */
835 DEBUG_FTRACE ("fixing up link for tailcall chain");
836 ftrace_debug (prev, "..top");
837 ftrace_debug (caller, "..up");
839 ftrace_fixup_caller (btinfo, prev, caller, next_flags);
841 /* If we skipped any tail calls, this may move CALLER to a
842 different function level.
844 Note that changing CALLER's level is only OK because we
845 know that this is the last iteration of the bottom-to-top
846 walk in ftrace_connect_backtrace.
848 Otherwise we will fix up CALLER's level when we connect it
849 to PREV's caller in the next iteration. */
850 ftrace_fixup_level (btinfo, caller,
851 prev->level - caller->level - 1);
855 /* There's nothing to do if we find a real call. */
856 if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) == 0)
858 DEBUG_FTRACE ("will fix up link in next iteration");
866 /* Connect function segments on the same level in the back trace at LHS and RHS.
867 The back traces at LHS and RHS are expected to match according to
868 ftrace_match_backtrace. BTINFO is the branch trace information for the
872 ftrace_connect_backtrace (struct btrace_thread_info *btinfo,
873 struct btrace_function *lhs,
874 struct btrace_function *rhs)
876 while (lhs != NULL && rhs != NULL)
878 struct btrace_function *prev, *next;
880 gdb_assert (!ftrace_function_switched (lhs, rhs->msym, rhs->sym));
882 /* Connecting LHS and RHS may change the up link. */
886 lhs = ftrace_get_caller (btinfo, lhs);
887 rhs = ftrace_get_caller (btinfo, rhs);
889 ftrace_connect_bfun (btinfo, prev, next);
893 /* Bridge the gap between two function segments left and right of a gap if their
894 respective back traces match in at least MIN_MATCHES functions. BTINFO is
895 the branch trace information for the current thread.
897 Returns non-zero if the gap could be bridged, zero otherwise. */
900 ftrace_bridge_gap (struct btrace_thread_info *btinfo,
901 struct btrace_function *lhs, struct btrace_function *rhs,
904 struct btrace_function *best_l, *best_r, *cand_l, *cand_r;
907 DEBUG_FTRACE ("checking gap at insn %u (req matches: %d)",
908 rhs->insn_offset - 1, min_matches);
914 /* We search the back traces of LHS and RHS for valid connections and connect
915 the two functon segments that give the longest combined back trace. */
917 for (cand_l = lhs; cand_l != NULL;
918 cand_l = ftrace_get_caller (btinfo, cand_l))
919 for (cand_r = rhs; cand_r != NULL;
920 cand_r = ftrace_get_caller (btinfo, cand_r))
924 matches = ftrace_match_backtrace (btinfo, cand_l, cand_r);
925 if (best_matches < matches)
927 best_matches = matches;
933 /* We need at least MIN_MATCHES matches. */
934 gdb_assert (min_matches > 0);
935 if (best_matches < min_matches)
938 DEBUG_FTRACE ("..matches: %d", best_matches);
940 /* We will fix up the level of BEST_R and succeeding function segments such
941 that BEST_R's level matches BEST_L's when we connect BEST_L to BEST_R.
943 This will ignore the level of RHS and following if BEST_R != RHS. I.e. if
944 BEST_R is a successor of RHS in the back trace of RHS (phases 1 and 3).
946 To catch this, we already fix up the level here where we can start at RHS
947 instead of at BEST_R. We will ignore the level fixup when connecting
948 BEST_L to BEST_R as they will already be on the same level. */
949 ftrace_fixup_level (btinfo, rhs, best_l->level - best_r->level);
951 ftrace_connect_backtrace (btinfo, best_l, best_r);
956 /* Try to bridge gaps due to overflow or decode errors by connecting the
957 function segments that are separated by the gap. */
960 btrace_bridge_gaps (struct thread_info *tp, std::vector<unsigned int> &gaps)
962 struct btrace_thread_info *btinfo = &tp->btrace;
963 std::vector<unsigned int> remaining;
966 DEBUG ("bridge gaps");
968 /* We require a minimum amount of matches for bridging a gap. The number of
969 required matches will be lowered with each iteration.
971 The more matches the higher our confidence that the bridging is correct.
972 For big gaps or small traces, however, it may not be feasible to require a
973 high number of matches. */
974 for (min_matches = 5; min_matches > 0; --min_matches)
976 /* Let's try to bridge as many gaps as we can. In some cases, we need to
977 skip a gap and revisit it again after we closed later gaps. */
978 while (!gaps.empty ())
980 for (const unsigned int number : gaps)
982 struct btrace_function *gap, *lhs, *rhs;
985 gap = ftrace_find_call_by_number (btinfo, number);
987 /* We may have a sequence of gaps if we run from one error into
988 the next as we try to re-sync onto the trace stream. Ignore
989 all but the leftmost gap in such a sequence.
991 Also ignore gaps at the beginning of the trace. */
992 lhs = ftrace_find_call_by_number (btinfo, gap->number - 1);
993 if (lhs == NULL || lhs->errcode != 0)
996 /* Skip gaps to the right. */
997 rhs = ftrace_find_call_by_number (btinfo, gap->number + 1);
998 while (rhs != NULL && rhs->errcode != 0)
999 rhs = ftrace_find_call_by_number (btinfo, rhs->number + 1);
1001 /* Ignore gaps at the end of the trace. */
1005 bridged = ftrace_bridge_gap (btinfo, lhs, rhs, min_matches);
1007 /* Keep track of gaps we were not able to bridge and try again.
1008 If we just pushed them to the end of GAPS we would risk an
1009 infinite loop in case we simply cannot bridge a gap. */
1011 remaining.push_back (number);
1014 /* Let's see if we made any progress. */
1015 if (remaining.size () == gaps.size ())
1019 gaps.swap (remaining);
1022 /* We get here if either GAPS is empty or if GAPS equals REMAINING. */
1029 /* We may omit this in some cases. Not sure it is worth the extra
1030 complication, though. */
1031 ftrace_compute_global_level_offset (btinfo);
1034 /* Compute the function branch trace from BTS trace. */
1037 btrace_compute_ftrace_bts (struct thread_info *tp,
1038 const struct btrace_data_bts *btrace,
1039 std::vector<unsigned int> &gaps)
1041 struct btrace_thread_info *btinfo;
1042 struct gdbarch *gdbarch;
1046 gdbarch = target_gdbarch ();
1047 btinfo = &tp->btrace;
1048 blk = VEC_length (btrace_block_s, btrace->blocks);
1050 if (btinfo->functions.empty ())
1053 level = -btinfo->level;
1057 btrace_block_s *block;
1062 block = VEC_index (btrace_block_s, btrace->blocks, blk);
1067 struct btrace_function *bfun;
1068 struct btrace_insn insn;
1071 /* We should hit the end of the block. Warn if we went too far. */
1072 if (block->end < pc)
1074 /* Indicate the gap in the trace. */
1075 bfun = ftrace_new_gap (btinfo, BDE_BTS_OVERFLOW, gaps);
1077 warning (_("Recorded trace may be corrupted at instruction "
1078 "%u (pc = %s)."), bfun->insn_offset - 1,
1079 core_addr_to_string_nz (pc));
1084 bfun = ftrace_update_function (btinfo, pc);
1086 /* Maintain the function level offset.
1087 For all but the last block, we do it here. */
1089 level = std::min (level, bfun->level);
1094 size = gdb_insn_length (gdbarch, pc);
1096 CATCH (error, RETURN_MASK_ERROR)
1103 insn.iclass = ftrace_classify_insn (gdbarch, pc);
1106 ftrace_update_insns (bfun, insn);
1108 /* We're done once we pushed the instruction at the end. */
1109 if (block->end == pc)
1112 /* We can't continue if we fail to compute the size. */
1115 /* Indicate the gap in the trace. We just added INSN so we're
1116 not at the beginning. */
1117 bfun = ftrace_new_gap (btinfo, BDE_BTS_INSN_SIZE, gaps);
1119 warning (_("Recorded trace may be incomplete at instruction %u "
1120 "(pc = %s)."), bfun->insn_offset - 1,
1121 core_addr_to_string_nz (pc));
1128 /* Maintain the function level offset.
1129 For the last block, we do it here to not consider the last
1131 Since the last instruction corresponds to the current instruction
1132 and is not really part of the execution history, it shouldn't
1133 affect the level. */
1135 level = std::min (level, bfun->level);
1139 /* LEVEL is the minimal function level of all btrace function segments.
1140 Define the global level offset to -LEVEL so all function levels are
1141 normalized to start at zero. */
1142 btinfo->level = -level;
1145 #if defined (HAVE_LIBIPT)
1147 static enum btrace_insn_class
1148 pt_reclassify_insn (enum pt_insn_class iclass)
1153 return BTRACE_INSN_CALL;
1156 return BTRACE_INSN_RETURN;
1159 return BTRACE_INSN_JUMP;
1162 return BTRACE_INSN_OTHER;
1166 /* Return the btrace instruction flags for INSN. */
1168 static btrace_insn_flags
1169 pt_btrace_insn_flags (const struct pt_insn &insn)
1171 btrace_insn_flags flags = 0;
1173 if (insn.speculative)
1174 flags |= BTRACE_INSN_FLAG_SPECULATIVE;
1179 /* Return the btrace instruction for INSN. */
1182 pt_btrace_insn (const struct pt_insn &insn)
1184 return {(CORE_ADDR) insn.ip, (gdb_byte) insn.size,
1185 pt_reclassify_insn (insn.iclass),
1186 pt_btrace_insn_flags (insn)};
1189 /* Handle instruction decode events (libipt-v2). */
1192 handle_pt_insn_events (struct btrace_thread_info *btinfo,
1193 struct pt_insn_decoder *decoder,
1194 std::vector<unsigned int> &gaps, int status)
1196 #if defined (HAVE_PT_INSN_EVENT)
1197 while (status & pts_event_pending)
1199 struct btrace_function *bfun;
1200 struct pt_event event;
1203 status = pt_insn_event (decoder, &event, sizeof (event));
1213 if (event.variant.enabled.resumed == 0 && !btinfo->functions.empty ())
1215 bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1217 pt_insn_get_offset (decoder, &offset);
1219 warning (_("Non-contiguous trace at instruction %u (offset = 0x%"
1220 PRIx64 ")."), bfun->insn_offset - 1, offset);
1226 bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1228 pt_insn_get_offset (decoder, &offset);
1230 warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ")."),
1231 bfun->insn_offset - 1, offset);
1236 #endif /* defined (HAVE_PT_INSN_EVENT) */
1241 /* Handle events indicated by flags in INSN (libipt-v1). */
1244 handle_pt_insn_event_flags (struct btrace_thread_info *btinfo,
1245 struct pt_insn_decoder *decoder,
1246 const struct pt_insn &insn,
1247 std::vector<unsigned int> &gaps)
1249 #if defined (HAVE_STRUCT_PT_INSN_ENABLED)
1250 /* Tracing is disabled and re-enabled each time we enter the kernel. Most
1251 times, we continue from the same instruction we stopped before. This is
1252 indicated via the RESUMED instruction flag. The ENABLED instruction flag
1253 means that we continued from some other instruction. Indicate this as a
1254 trace gap except when tracing just started. */
1255 if (insn.enabled && !btinfo->functions.empty ())
1257 struct btrace_function *bfun;
1260 bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1262 pt_insn_get_offset (decoder, &offset);
1264 warning (_("Non-contiguous trace at instruction %u (offset = 0x%" PRIx64
1265 ", pc = 0x%" PRIx64 ")."), bfun->insn_offset - 1, offset,
1268 #endif /* defined (HAVE_STRUCT_PT_INSN_ENABLED) */
1270 #if defined (HAVE_STRUCT_PT_INSN_RESYNCED)
1271 /* Indicate trace overflows. */
1274 struct btrace_function *bfun;
1277 bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1279 pt_insn_get_offset (decoder, &offset);
1281 warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ", pc = 0x%"
1282 PRIx64 ")."), bfun->insn_offset - 1, offset, insn.ip);
1284 #endif /* defined (HAVE_STRUCT_PT_INSN_RESYNCED) */
1287 /* Add function branch trace to BTINFO using DECODER. */
1290 ftrace_add_pt (struct btrace_thread_info *btinfo,
1291 struct pt_insn_decoder *decoder,
1293 std::vector<unsigned int> &gaps)
1295 struct btrace_function *bfun;
1301 struct pt_insn insn;
1303 status = pt_insn_sync_forward (decoder);
1306 if (status != -pte_eos)
1307 warning (_("Failed to synchronize onto the Intel Processor "
1308 "Trace stream: %s."), pt_errstr (pt_errcode (status)));
1314 /* Handle events from the previous iteration or synchronization. */
1315 status = handle_pt_insn_events (btinfo, decoder, gaps, status);
1319 status = pt_insn_next (decoder, &insn, sizeof(insn));
1323 /* Handle events indicated by flags in INSN. */
1324 handle_pt_insn_event_flags (btinfo, decoder, insn, gaps);
1326 bfun = ftrace_update_function (btinfo, insn.ip);
1328 /* Maintain the function level offset. */
1329 *plevel = std::min (*plevel, bfun->level);
1331 ftrace_update_insns (bfun, pt_btrace_insn (insn));
1334 if (status == -pte_eos)
1337 /* Indicate the gap in the trace. */
1338 bfun = ftrace_new_gap (btinfo, status, gaps);
1340 pt_insn_get_offset (decoder, &offset);
1342 warning (_("Decode error (%d) at instruction %u (offset = 0x%" PRIx64
1343 ", pc = 0x%" PRIx64 "): %s."), status, bfun->insn_offset - 1,
1344 offset, insn.ip, pt_errstr (pt_errcode (status)));
1348 /* A callback function to allow the trace decoder to read the inferior's
1352 btrace_pt_readmem_callback (gdb_byte *buffer, size_t size,
1353 const struct pt_asid *asid, uint64_t pc,
1356 int result, errcode;
1358 result = (int) size;
1361 errcode = target_read_code ((CORE_ADDR) pc, buffer, size);
1363 result = -pte_nomap;
1365 CATCH (error, RETURN_MASK_ERROR)
1367 result = -pte_nomap;
1374 /* Translate the vendor from one enum to another. */
1376 static enum pt_cpu_vendor
1377 pt_translate_cpu_vendor (enum btrace_cpu_vendor vendor)
1389 /* Finalize the function branch trace after decode. */
1391 static void btrace_finalize_ftrace_pt (struct pt_insn_decoder *decoder,
1392 struct thread_info *tp, int level)
1394 pt_insn_free_decoder (decoder);
1396 /* LEVEL is the minimal function level of all btrace function segments.
1397 Define the global level offset to -LEVEL so all function levels are
1398 normalized to start at zero. */
1399 tp->btrace.level = -level;
1401 /* Add a single last instruction entry for the current PC.
1402 This allows us to compute the backtrace at the current PC using both
1403 standard unwind and btrace unwind.
1404 This extra entry is ignored by all record commands. */
1408 /* Compute the function branch trace from Intel Processor Trace
1412 btrace_compute_ftrace_pt (struct thread_info *tp,
1413 const struct btrace_data_pt *btrace,
1414 std::vector<unsigned int> &gaps)
1416 struct btrace_thread_info *btinfo;
1417 struct pt_insn_decoder *decoder;
1418 struct pt_config config;
1421 if (btrace->size == 0)
1424 btinfo = &tp->btrace;
1425 if (btinfo->functions.empty ())
1428 level = -btinfo->level;
1430 pt_config_init(&config);
1431 config.begin = btrace->data;
1432 config.end = btrace->data + btrace->size;
1434 /* We treat an unknown vendor as 'no errata'. */
1435 if (btrace->config.cpu.vendor != CV_UNKNOWN)
1438 = pt_translate_cpu_vendor (btrace->config.cpu.vendor);
1439 config.cpu.family = btrace->config.cpu.family;
1440 config.cpu.model = btrace->config.cpu.model;
1441 config.cpu.stepping = btrace->config.cpu.stepping;
1443 errcode = pt_cpu_errata (&config.errata, &config.cpu);
1445 error (_("Failed to configure the Intel Processor Trace "
1446 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
1449 decoder = pt_insn_alloc_decoder (&config);
1450 if (decoder == NULL)
1451 error (_("Failed to allocate the Intel Processor Trace decoder."));
1455 struct pt_image *image;
1457 image = pt_insn_get_image(decoder);
1459 error (_("Failed to configure the Intel Processor Trace decoder."));
1461 errcode = pt_image_set_callback(image, btrace_pt_readmem_callback, NULL);
1463 error (_("Failed to configure the Intel Processor Trace decoder: "
1464 "%s."), pt_errstr (pt_errcode (errcode)));
1466 ftrace_add_pt (btinfo, decoder, &level, gaps);
1468 CATCH (error, RETURN_MASK_ALL)
1470 /* Indicate a gap in the trace if we quit trace processing. */
1471 if (error.reason == RETURN_QUIT && !btinfo->functions.empty ())
1472 ftrace_new_gap (btinfo, BDE_PT_USER_QUIT, gaps);
1474 btrace_finalize_ftrace_pt (decoder, tp, level);
1476 throw_exception (error);
1480 btrace_finalize_ftrace_pt (decoder, tp, level);
1483 #else /* defined (HAVE_LIBIPT) */
1486 btrace_compute_ftrace_pt (struct thread_info *tp,
1487 const struct btrace_data_pt *btrace,
1488 std::vector<unsigned int> &gaps)
1490 internal_error (__FILE__, __LINE__, _("Unexpected branch trace format."));
1493 #endif /* defined (HAVE_LIBIPT) */
1495 /* Compute the function branch trace from a block branch trace BTRACE for
1496 a thread given by BTINFO. If CPU is not NULL, overwrite the cpu in the
1497 branch trace configuration. This is currently only used for the PT
1501 btrace_compute_ftrace_1 (struct thread_info *tp,
1502 struct btrace_data *btrace,
1503 const struct btrace_cpu *cpu,
1504 std::vector<unsigned int> &gaps)
1506 DEBUG ("compute ftrace");
1508 switch (btrace->format)
1510 case BTRACE_FORMAT_NONE:
1513 case BTRACE_FORMAT_BTS:
1514 btrace_compute_ftrace_bts (tp, &btrace->variant.bts, gaps);
1517 case BTRACE_FORMAT_PT:
1518 /* Overwrite the cpu we use for enabling errata workarounds. */
1520 btrace->variant.pt.config.cpu = *cpu;
1522 btrace_compute_ftrace_pt (tp, &btrace->variant.pt, gaps);
1526 internal_error (__FILE__, __LINE__, _("Unkown branch trace format."));
1530 btrace_finalize_ftrace (struct thread_info *tp, std::vector<unsigned int> &gaps)
1534 tp->btrace.ngaps += gaps.size ();
1535 btrace_bridge_gaps (tp, gaps);
1540 btrace_compute_ftrace (struct thread_info *tp, struct btrace_data *btrace,
1541 const struct btrace_cpu *cpu)
1543 std::vector<unsigned int> gaps;
1547 btrace_compute_ftrace_1 (tp, btrace, cpu, gaps);
1549 CATCH (error, RETURN_MASK_ALL)
1551 btrace_finalize_ftrace (tp, gaps);
1553 throw_exception (error);
1557 btrace_finalize_ftrace (tp, gaps);
1560 /* Add an entry for the current PC. */
1563 btrace_add_pc (struct thread_info *tp)
1565 struct btrace_data btrace;
1566 struct btrace_block *block;
1567 struct regcache *regcache;
1570 regcache = get_thread_regcache (tp->ptid);
1571 pc = regcache_read_pc (regcache);
1573 btrace.format = BTRACE_FORMAT_BTS;
1574 btrace.variant.bts.blocks = NULL;
1576 block = VEC_safe_push (btrace_block_s, btrace.variant.bts.blocks, NULL);
1580 btrace_compute_ftrace (tp, &btrace, NULL);
1586 btrace_enable (struct thread_info *tp, const struct btrace_config *conf)
1588 if (tp->btrace.target != NULL)
1591 #if !defined (HAVE_LIBIPT)
1592 if (conf->format == BTRACE_FORMAT_PT)
1593 error (_("Intel Processor Trace support was disabled at compile time."));
1594 #endif /* !defined (HAVE_LIBIPT) */
1596 DEBUG ("enable thread %s (%s)", print_thread_id (tp),
1597 target_pid_to_str (tp->ptid));
1599 tp->btrace.target = target_enable_btrace (tp->ptid, conf);
1601 /* We're done if we failed to enable tracing. */
1602 if (tp->btrace.target == NULL)
1605 /* We need to undo the enable in case of errors. */
1608 /* Add an entry for the current PC so we start tracing from where we
1611 If we can't access TP's registers, TP is most likely running. In this
1612 case, we can't really say where tracing was enabled so it should be
1613 safe to simply skip this step.
1615 This is not relevant for BTRACE_FORMAT_PT since the trace will already
1616 start at the PC at which tracing was enabled. */
1617 if (conf->format != BTRACE_FORMAT_PT
1618 && can_access_registers_ptid (tp->ptid))
1621 CATCH (exception, RETURN_MASK_ALL)
1623 btrace_disable (tp);
1625 throw_exception (exception);
1632 const struct btrace_config *
1633 btrace_conf (const struct btrace_thread_info *btinfo)
1635 if (btinfo->target == NULL)
1638 return target_btrace_conf (btinfo->target);
1644 btrace_disable (struct thread_info *tp)
1646 struct btrace_thread_info *btp = &tp->btrace;
1648 if (btp->target == NULL)
1651 DEBUG ("disable thread %s (%s)", print_thread_id (tp),
1652 target_pid_to_str (tp->ptid));
1654 target_disable_btrace (btp->target);
1663 btrace_teardown (struct thread_info *tp)
1665 struct btrace_thread_info *btp = &tp->btrace;
1667 if (btp->target == NULL)
1670 DEBUG ("teardown thread %s (%s)", print_thread_id (tp),
1671 target_pid_to_str (tp->ptid));
1673 target_teardown_btrace (btp->target);
1679 /* Stitch branch trace in BTS format. */
1682 btrace_stitch_bts (struct btrace_data_bts *btrace, struct thread_info *tp)
1684 struct btrace_thread_info *btinfo;
1685 struct btrace_function *last_bfun;
1686 btrace_block_s *first_new_block;
1688 btinfo = &tp->btrace;
1689 gdb_assert (!btinfo->functions.empty ());
1690 gdb_assert (!VEC_empty (btrace_block_s, btrace->blocks));
1692 last_bfun = &btinfo->functions.back ();
1694 /* If the existing trace ends with a gap, we just glue the traces
1695 together. We need to drop the last (i.e. chronologically first) block
1696 of the new trace, though, since we can't fill in the start address.*/
1697 if (last_bfun->insn.empty ())
1699 VEC_pop (btrace_block_s, btrace->blocks);
1703 /* Beware that block trace starts with the most recent block, so the
1704 chronologically first block in the new trace is the last block in
1705 the new trace's block vector. */
1706 first_new_block = VEC_last (btrace_block_s, btrace->blocks);
1707 const btrace_insn &last_insn = last_bfun->insn.back ();
1709 /* If the current PC at the end of the block is the same as in our current
1710 trace, there are two explanations:
1711 1. we executed the instruction and some branch brought us back.
1712 2. we have not made any progress.
1713 In the first case, the delta trace vector should contain at least two
1715 In the second case, the delta trace vector should contain exactly one
1716 entry for the partial block containing the current PC. Remove it. */
1717 if (first_new_block->end == last_insn.pc
1718 && VEC_length (btrace_block_s, btrace->blocks) == 1)
1720 VEC_pop (btrace_block_s, btrace->blocks);
1724 DEBUG ("stitching %s to %s", ftrace_print_insn_addr (&last_insn),
1725 core_addr_to_string_nz (first_new_block->end));
1727 /* Do a simple sanity check to make sure we don't accidentally end up
1728 with a bad block. This should not occur in practice. */
1729 if (first_new_block->end < last_insn.pc)
1731 warning (_("Error while trying to read delta trace. Falling back to "
1736 /* We adjust the last block to start at the end of our current trace. */
1737 gdb_assert (first_new_block->begin == 0);
1738 first_new_block->begin = last_insn.pc;
1740 /* We simply pop the last insn so we can insert it again as part of
1741 the normal branch trace computation.
1742 Since instruction iterators are based on indices in the instructions
1743 vector, we don't leave any pointers dangling. */
1744 DEBUG ("pruning insn at %s for stitching",
1745 ftrace_print_insn_addr (&last_insn));
1747 last_bfun->insn.pop_back ();
1749 /* The instructions vector may become empty temporarily if this has
1750 been the only instruction in this function segment.
1751 This violates the invariant but will be remedied shortly by
1752 btrace_compute_ftrace when we add the new trace. */
1754 /* The only case where this would hurt is if the entire trace consisted
1755 of just that one instruction. If we remove it, we might turn the now
1756 empty btrace function segment into a gap. But we don't want gaps at
1757 the beginning. To avoid this, we remove the entire old trace. */
1758 if (last_bfun->number == 1 && last_bfun->insn.empty ())
1764 /* Adjust the block trace in order to stitch old and new trace together.
1765 BTRACE is the new delta trace between the last and the current stop.
1766 TP is the traced thread.
1767 May modifx BTRACE as well as the existing trace in TP.
1768 Return 0 on success, -1 otherwise. */
1771 btrace_stitch_trace (struct btrace_data *btrace, struct thread_info *tp)
1773 /* If we don't have trace, there's nothing to do. */
1774 if (btrace->empty ())
1777 switch (btrace->format)
1779 case BTRACE_FORMAT_NONE:
1782 case BTRACE_FORMAT_BTS:
1783 return btrace_stitch_bts (&btrace->variant.bts, tp);
1785 case BTRACE_FORMAT_PT:
1786 /* Delta reads are not supported. */
1790 internal_error (__FILE__, __LINE__, _("Unkown branch trace format."));
1793 /* Clear the branch trace histories in BTINFO. */
1796 btrace_clear_history (struct btrace_thread_info *btinfo)
1798 xfree (btinfo->insn_history);
1799 xfree (btinfo->call_history);
1800 xfree (btinfo->replay);
1802 btinfo->insn_history = NULL;
1803 btinfo->call_history = NULL;
1804 btinfo->replay = NULL;
1807 /* Clear the branch trace maintenance histories in BTINFO. */
1810 btrace_maint_clear (struct btrace_thread_info *btinfo)
1812 switch (btinfo->data.format)
1817 case BTRACE_FORMAT_BTS:
1818 btinfo->maint.variant.bts.packet_history.begin = 0;
1819 btinfo->maint.variant.bts.packet_history.end = 0;
1822 #if defined (HAVE_LIBIPT)
1823 case BTRACE_FORMAT_PT:
1824 xfree (btinfo->maint.variant.pt.packets);
1826 btinfo->maint.variant.pt.packets = NULL;
1827 btinfo->maint.variant.pt.packet_history.begin = 0;
1828 btinfo->maint.variant.pt.packet_history.end = 0;
1830 #endif /* defined (HAVE_LIBIPT) */
1837 btrace_decode_error (enum btrace_format format, int errcode)
1841 case BTRACE_FORMAT_BTS:
1844 case BDE_BTS_OVERFLOW:
1845 return _("instruction overflow");
1847 case BDE_BTS_INSN_SIZE:
1848 return _("unknown instruction");
1855 #if defined (HAVE_LIBIPT)
1856 case BTRACE_FORMAT_PT:
1859 case BDE_PT_USER_QUIT:
1860 return _("trace decode cancelled");
1862 case BDE_PT_DISABLED:
1863 return _("disabled");
1865 case BDE_PT_OVERFLOW:
1866 return _("overflow");
1870 return pt_errstr (pt_errcode (errcode));
1874 #endif /* defined (HAVE_LIBIPT) */
1880 return _("unknown");
1886 btrace_fetch (struct thread_info *tp, const struct btrace_cpu *cpu)
1888 struct btrace_thread_info *btinfo;
1889 struct btrace_target_info *tinfo;
1890 struct btrace_data btrace;
1893 DEBUG ("fetch thread %s (%s)", print_thread_id (tp),
1894 target_pid_to_str (tp->ptid));
1896 btinfo = &tp->btrace;
1897 tinfo = btinfo->target;
1901 /* There's no way we could get new trace while replaying.
1902 On the other hand, delta trace would return a partial record with the
1903 current PC, which is the replay PC, not the last PC, as expected. */
1904 if (btinfo->replay != NULL)
1907 /* With CLI usage, TP->PTID always equals INFERIOR_PTID here. Now that we
1908 can store a gdb.Record object in Python referring to a different thread
1909 than the current one, temporarily set INFERIOR_PTID. */
1910 scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1911 inferior_ptid = tp->ptid;
1913 /* We should not be called on running or exited threads. */
1914 gdb_assert (can_access_registers_ptid (tp->ptid));
1916 /* Let's first try to extend the trace we already have. */
1917 if (!btinfo->functions.empty ())
1919 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_DELTA);
1922 /* Success. Let's try to stitch the traces together. */
1923 errcode = btrace_stitch_trace (&btrace, tp);
1927 /* We failed to read delta trace. Let's try to read new trace. */
1928 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_NEW);
1930 /* If we got any new trace, discard what we have. */
1931 if (errcode == 0 && !btrace.empty ())
1935 /* If we were not able to read the trace, we start over. */
1939 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1943 errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1945 /* If we were not able to read the branch trace, signal an error. */
1947 error (_("Failed to read branch trace."));
1949 /* Compute the trace, provided we have any. */
1950 if (!btrace.empty ())
1952 /* Store the raw trace data. The stored data will be cleared in
1953 btrace_clear, so we always append the new trace. */
1954 btrace_data_append (&btinfo->data, &btrace);
1955 btrace_maint_clear (btinfo);
1957 btrace_clear_history (btinfo);
1958 btrace_compute_ftrace (tp, &btrace, cpu);
1965 btrace_clear (struct thread_info *tp)
1967 struct btrace_thread_info *btinfo;
1969 DEBUG ("clear thread %s (%s)", print_thread_id (tp),
1970 target_pid_to_str (tp->ptid));
1972 /* Make sure btrace frames that may hold a pointer into the branch
1973 trace data are destroyed. */
1974 reinit_frame_cache ();
1976 btinfo = &tp->btrace;
1978 btinfo->functions.clear ();
1981 /* Must clear the maint data before - it depends on BTINFO->DATA. */
1982 btrace_maint_clear (btinfo);
1983 btinfo->data.clear ();
1984 btrace_clear_history (btinfo);
1990 btrace_free_objfile (struct objfile *objfile)
1992 struct thread_info *tp;
1994 DEBUG ("free objfile");
1996 ALL_NON_EXITED_THREADS (tp)
2000 #if defined (HAVE_LIBEXPAT)
2002 /* Check the btrace document version. */
2005 check_xml_btrace_version (struct gdb_xml_parser *parser,
2006 const struct gdb_xml_element *element,
2008 std::vector<gdb_xml_value> &attributes)
2011 = (const char *) xml_find_attribute (attributes, "version")->value.get ();
2013 if (strcmp (version, "1.0") != 0)
2014 gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
2017 /* Parse a btrace "block" xml record. */
2020 parse_xml_btrace_block (struct gdb_xml_parser *parser,
2021 const struct gdb_xml_element *element,
2023 std::vector<gdb_xml_value> &attributes)
2025 struct btrace_data *btrace;
2026 struct btrace_block *block;
2027 ULONGEST *begin, *end;
2029 btrace = (struct btrace_data *) user_data;
2031 switch (btrace->format)
2033 case BTRACE_FORMAT_BTS:
2036 case BTRACE_FORMAT_NONE:
2037 btrace->format = BTRACE_FORMAT_BTS;
2038 btrace->variant.bts.blocks = NULL;
2042 gdb_xml_error (parser, _("Btrace format error."));
2045 begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
2046 end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
2048 block = VEC_safe_push (btrace_block_s, btrace->variant.bts.blocks, NULL);
2049 block->begin = *begin;
2053 /* Parse a "raw" xml record. */
2056 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
2057 gdb_byte **pdata, size_t *psize)
2059 struct cleanup *cleanup;
2060 gdb_byte *data, *bin;
2063 len = strlen (body_text);
2065 gdb_xml_error (parser, _("Bad raw data size."));
2069 bin = data = (gdb_byte *) xmalloc (size);
2070 cleanup = make_cleanup (xfree, data);
2072 /* We use hex encoding - see common/rsp-low.h. */
2080 if (hi == 0 || lo == 0)
2081 gdb_xml_error (parser, _("Bad hex encoding."));
2083 *bin++ = fromhex (hi) * 16 + fromhex (lo);
2087 discard_cleanups (cleanup);
2093 /* Parse a btrace pt-config "cpu" xml record. */
2096 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
2097 const struct gdb_xml_element *element,
2099 std::vector<gdb_xml_value> &attributes)
2101 struct btrace_data *btrace;
2103 ULONGEST *family, *model, *stepping;
2106 (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
2108 = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
2110 = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
2112 = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
2114 btrace = (struct btrace_data *) user_data;
2116 if (strcmp (vendor, "GenuineIntel") == 0)
2117 btrace->variant.pt.config.cpu.vendor = CV_INTEL;
2119 btrace->variant.pt.config.cpu.family = *family;
2120 btrace->variant.pt.config.cpu.model = *model;
2121 btrace->variant.pt.config.cpu.stepping = *stepping;
2124 /* Parse a btrace pt "raw" xml record. */
2127 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
2128 const struct gdb_xml_element *element,
2129 void *user_data, const char *body_text)
2131 struct btrace_data *btrace;
2133 btrace = (struct btrace_data *) user_data;
2134 parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
2135 &btrace->variant.pt.size);
2138 /* Parse a btrace "pt" xml record. */
2141 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
2142 const struct gdb_xml_element *element,
2144 std::vector<gdb_xml_value> &attributes)
2146 struct btrace_data *btrace;
2148 btrace = (struct btrace_data *) user_data;
2149 btrace->format = BTRACE_FORMAT_PT;
2150 btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
2151 btrace->variant.pt.data = NULL;
2152 btrace->variant.pt.size = 0;
2155 static const struct gdb_xml_attribute block_attributes[] = {
2156 { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2157 { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2158 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2161 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
2162 { "vendor", GDB_XML_AF_NONE, NULL, NULL },
2163 { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2164 { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2165 { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2166 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2169 static const struct gdb_xml_element btrace_pt_config_children[] = {
2170 { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
2171 parse_xml_btrace_pt_config_cpu, NULL },
2172 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2175 static const struct gdb_xml_element btrace_pt_children[] = {
2176 { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
2178 { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
2179 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2182 static const struct gdb_xml_attribute btrace_attributes[] = {
2183 { "version", GDB_XML_AF_NONE, NULL, NULL },
2184 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2187 static const struct gdb_xml_element btrace_children[] = {
2188 { "block", block_attributes, NULL,
2189 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
2190 { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
2192 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2195 static const struct gdb_xml_element btrace_elements[] = {
2196 { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
2197 check_xml_btrace_version, NULL },
2198 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2201 #endif /* defined (HAVE_LIBEXPAT) */
2206 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
2210 #if defined (HAVE_LIBEXPAT)
2213 result.format = BTRACE_FORMAT_NONE;
2215 errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
2218 error (_("Error parsing branch trace."));
2220 /* Keep parse results. */
2221 *btrace = std::move (result);
2223 #else /* !defined (HAVE_LIBEXPAT) */
2225 error (_("Cannot process branch trace. XML support was disabled at "
2228 #endif /* !defined (HAVE_LIBEXPAT) */
2231 #if defined (HAVE_LIBEXPAT)
2233 /* Parse a btrace-conf "bts" xml record. */
2236 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
2237 const struct gdb_xml_element *element,
2239 std::vector<gdb_xml_value> &attributes)
2241 struct btrace_config *conf;
2242 struct gdb_xml_value *size;
2244 conf = (struct btrace_config *) user_data;
2245 conf->format = BTRACE_FORMAT_BTS;
2248 size = xml_find_attribute (attributes, "size");
2250 conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
2253 /* Parse a btrace-conf "pt" xml record. */
2256 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
2257 const struct gdb_xml_element *element,
2259 std::vector<gdb_xml_value> &attributes)
2261 struct btrace_config *conf;
2262 struct gdb_xml_value *size;
2264 conf = (struct btrace_config *) user_data;
2265 conf->format = BTRACE_FORMAT_PT;
2268 size = xml_find_attribute (attributes, "size");
2270 conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
2273 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
2274 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2275 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2278 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
2279 { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2280 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2283 static const struct gdb_xml_element btrace_conf_children[] = {
2284 { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
2285 parse_xml_btrace_conf_bts, NULL },
2286 { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
2287 parse_xml_btrace_conf_pt, NULL },
2288 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2291 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
2292 { "version", GDB_XML_AF_NONE, NULL, NULL },
2293 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2296 static const struct gdb_xml_element btrace_conf_elements[] = {
2297 { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
2298 GDB_XML_EF_NONE, NULL, NULL },
2299 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2302 #endif /* defined (HAVE_LIBEXPAT) */
2307 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
2311 #if defined (HAVE_LIBEXPAT)
2313 errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
2314 btrace_conf_elements, xml, conf);
2316 error (_("Error parsing branch trace configuration."));
2318 #else /* !defined (HAVE_LIBEXPAT) */
2320 error (_("Cannot process the branch trace configuration. XML support "
2321 "was disabled at compile time."));
2323 #endif /* !defined (HAVE_LIBEXPAT) */
2328 const struct btrace_insn *
2329 btrace_insn_get (const struct btrace_insn_iterator *it)
2331 const struct btrace_function *bfun;
2332 unsigned int index, end;
2334 index = it->insn_index;
2335 bfun = &it->btinfo->functions[it->call_index];
2337 /* Check if the iterator points to a gap in the trace. */
2338 if (bfun->errcode != 0)
2341 /* The index is within the bounds of this function's instruction vector. */
2342 end = bfun->insn.size ();
2343 gdb_assert (0 < end);
2344 gdb_assert (index < end);
2346 return &bfun->insn[index];
2352 btrace_insn_get_error (const struct btrace_insn_iterator *it)
2354 return it->btinfo->functions[it->call_index].errcode;
2360 btrace_insn_number (const struct btrace_insn_iterator *it)
2362 return it->btinfo->functions[it->call_index].insn_offset + it->insn_index;
2368 btrace_insn_begin (struct btrace_insn_iterator *it,
2369 const struct btrace_thread_info *btinfo)
2371 if (btinfo->functions.empty ())
2372 error (_("No trace."));
2374 it->btinfo = btinfo;
2382 btrace_insn_end (struct btrace_insn_iterator *it,
2383 const struct btrace_thread_info *btinfo)
2385 const struct btrace_function *bfun;
2386 unsigned int length;
2388 if (btinfo->functions.empty ())
2389 error (_("No trace."));
2391 bfun = &btinfo->functions.back ();
2392 length = bfun->insn.size ();
2394 /* The last function may either be a gap or it contains the current
2395 instruction, which is one past the end of the execution trace; ignore
2400 it->btinfo = btinfo;
2401 it->call_index = bfun->number - 1;
2402 it->insn_index = length;
2408 btrace_insn_next (struct btrace_insn_iterator *it, unsigned int stride)
2410 const struct btrace_function *bfun;
2411 unsigned int index, steps;
2413 bfun = &it->btinfo->functions[it->call_index];
2415 index = it->insn_index;
2419 unsigned int end, space, adv;
2421 end = bfun->insn.size ();
2423 /* An empty function segment represents a gap in the trace. We count
2424 it as one instruction. */
2427 const struct btrace_function *next;
2429 next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2442 gdb_assert (0 < end);
2443 gdb_assert (index < end);
2445 /* Compute the number of instructions remaining in this segment. */
2446 space = end - index;
2448 /* Advance the iterator as far as possible within this segment. */
2449 adv = std::min (space, stride);
2454 /* Move to the next function if we're at the end of this one. */
2457 const struct btrace_function *next;
2459 next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2462 /* We stepped past the last function.
2464 Let's adjust the index to point to the last instruction in
2465 the previous function. */
2471 /* We now point to the first instruction in the new function. */
2476 /* We did make progress. */
2477 gdb_assert (adv > 0);
2480 /* Update the iterator. */
2481 it->call_index = bfun->number - 1;
2482 it->insn_index = index;
2490 btrace_insn_prev (struct btrace_insn_iterator *it, unsigned int stride)
2492 const struct btrace_function *bfun;
2493 unsigned int index, steps;
2495 bfun = &it->btinfo->functions[it->call_index];
2497 index = it->insn_index;
2503 /* Move to the previous function if we're at the start of this one. */
2506 const struct btrace_function *prev;
2508 prev = ftrace_find_call_by_number (it->btinfo, bfun->number - 1);
2512 /* We point to one after the last instruction in the new function. */
2514 index = bfun->insn.size ();
2516 /* An empty function segment represents a gap in the trace. We count
2517 it as one instruction. */
2527 /* Advance the iterator as far as possible within this segment. */
2528 adv = std::min (index, stride);
2534 /* We did make progress. */
2535 gdb_assert (adv > 0);
2538 /* Update the iterator. */
2539 it->call_index = bfun->number - 1;
2540 it->insn_index = index;
2548 btrace_insn_cmp (const struct btrace_insn_iterator *lhs,
2549 const struct btrace_insn_iterator *rhs)
2551 gdb_assert (lhs->btinfo == rhs->btinfo);
2553 if (lhs->call_index != rhs->call_index)
2554 return lhs->call_index - rhs->call_index;
2556 return lhs->insn_index - rhs->insn_index;
2562 btrace_find_insn_by_number (struct btrace_insn_iterator *it,
2563 const struct btrace_thread_info *btinfo,
2564 unsigned int number)
2566 const struct btrace_function *bfun;
2567 unsigned int upper, lower;
2569 if (btinfo->functions.empty ())
2573 bfun = &btinfo->functions[lower];
2574 if (number < bfun->insn_offset)
2577 upper = btinfo->functions.size () - 1;
2578 bfun = &btinfo->functions[upper];
2579 if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2582 /* We assume that there are no holes in the numbering. */
2585 const unsigned int average = lower + (upper - lower) / 2;
2587 bfun = &btinfo->functions[average];
2589 if (number < bfun->insn_offset)
2591 upper = average - 1;
2595 if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2597 lower = average + 1;
2604 it->btinfo = btinfo;
2605 it->call_index = bfun->number - 1;
2606 it->insn_index = number - bfun->insn_offset;
2610 /* Returns true if the recording ends with a function segment that
2611 contains only a single (i.e. the current) instruction. */
2614 btrace_ends_with_single_insn (const struct btrace_thread_info *btinfo)
2616 const btrace_function *bfun;
2618 if (btinfo->functions.empty ())
2621 bfun = &btinfo->functions.back ();
2622 if (bfun->errcode != 0)
2625 return ftrace_call_num_insn (bfun) == 1;
2630 const struct btrace_function *
2631 btrace_call_get (const struct btrace_call_iterator *it)
2633 if (it->index >= it->btinfo->functions.size ())
2636 return &it->btinfo->functions[it->index];
2642 btrace_call_number (const struct btrace_call_iterator *it)
2644 const unsigned int length = it->btinfo->functions.size ();
2646 /* If the last function segment contains only a single instruction (i.e. the
2647 current instruction), skip it. */
2648 if ((it->index == length) && btrace_ends_with_single_insn (it->btinfo))
2651 return it->index + 1;
2657 btrace_call_begin (struct btrace_call_iterator *it,
2658 const struct btrace_thread_info *btinfo)
2660 if (btinfo->functions.empty ())
2661 error (_("No trace."));
2663 it->btinfo = btinfo;
2670 btrace_call_end (struct btrace_call_iterator *it,
2671 const struct btrace_thread_info *btinfo)
2673 if (btinfo->functions.empty ())
2674 error (_("No trace."));
2676 it->btinfo = btinfo;
2677 it->index = btinfo->functions.size ();
2683 btrace_call_next (struct btrace_call_iterator *it, unsigned int stride)
2685 const unsigned int length = it->btinfo->functions.size ();
2687 if (it->index + stride < length - 1)
2688 /* Default case: Simply advance the iterator. */
2689 it->index += stride;
2690 else if (it->index + stride == length - 1)
2692 /* We land exactly at the last function segment. If it contains only one
2693 instruction (i.e. the current instruction) it is not actually part of
2695 if (btrace_ends_with_single_insn (it->btinfo))
2698 it->index = length - 1;
2702 /* We land past the last function segment and have to adjust the stride.
2703 If the last function segment contains only one instruction (i.e. the
2704 current instruction) it is not actually part of the trace. */
2705 if (btrace_ends_with_single_insn (it->btinfo))
2706 stride = length - it->index - 1;
2708 stride = length - it->index;
2719 btrace_call_prev (struct btrace_call_iterator *it, unsigned int stride)
2721 const unsigned int length = it->btinfo->functions.size ();
2724 gdb_assert (it->index <= length);
2726 if (stride == 0 || it->index == 0)
2729 /* If we are at the end, the first step is a special case. If the last
2730 function segment contains only one instruction (i.e. the current
2731 instruction) it is not actually part of the trace. To be able to step
2732 over this instruction, we need at least one more function segment. */
2733 if ((it->index == length) && (length > 1))
2735 if (btrace_ends_with_single_insn (it->btinfo))
2736 it->index = length - 2;
2738 it->index = length - 1;
2744 stride = std::min (stride, it->index);
2746 it->index -= stride;
2747 return steps + stride;
2753 btrace_call_cmp (const struct btrace_call_iterator *lhs,
2754 const struct btrace_call_iterator *rhs)
2756 gdb_assert (lhs->btinfo == rhs->btinfo);
2757 return (int) (lhs->index - rhs->index);
2763 btrace_find_call_by_number (struct btrace_call_iterator *it,
2764 const struct btrace_thread_info *btinfo,
2765 unsigned int number)
2767 const unsigned int length = btinfo->functions.size ();
2769 if ((number == 0) || (number > length))
2772 it->btinfo = btinfo;
2773 it->index = number - 1;
2780 btrace_set_insn_history (struct btrace_thread_info *btinfo,
2781 const struct btrace_insn_iterator *begin,
2782 const struct btrace_insn_iterator *end)
2784 if (btinfo->insn_history == NULL)
2785 btinfo->insn_history = XCNEW (struct btrace_insn_history);
2787 btinfo->insn_history->begin = *begin;
2788 btinfo->insn_history->end = *end;
2794 btrace_set_call_history (struct btrace_thread_info *btinfo,
2795 const struct btrace_call_iterator *begin,
2796 const struct btrace_call_iterator *end)
2798 gdb_assert (begin->btinfo == end->btinfo);
2800 if (btinfo->call_history == NULL)
2801 btinfo->call_history = XCNEW (struct btrace_call_history);
2803 btinfo->call_history->begin = *begin;
2804 btinfo->call_history->end = *end;
2810 btrace_is_replaying (struct thread_info *tp)
2812 return tp->btrace.replay != NULL;
2818 btrace_is_empty (struct thread_info *tp)
2820 struct btrace_insn_iterator begin, end;
2821 struct btrace_thread_info *btinfo;
2823 btinfo = &tp->btrace;
2825 if (btinfo->functions.empty ())
2828 btrace_insn_begin (&begin, btinfo);
2829 btrace_insn_end (&end, btinfo);
2831 return btrace_insn_cmp (&begin, &end) == 0;
2834 #if defined (HAVE_LIBIPT)
2836 /* Print a single packet. */
2839 pt_print_packet (const struct pt_packet *packet)
2841 switch (packet->type)
2844 printf_unfiltered (("[??: %x]"), packet->type);
2848 printf_unfiltered (("psb"));
2852 printf_unfiltered (("psbend"));
2856 printf_unfiltered (("pad"));
2860 printf_unfiltered (("tip %u: 0x%" PRIx64 ""),
2861 packet->payload.ip.ipc,
2862 packet->payload.ip.ip);
2866 printf_unfiltered (("tip.pge %u: 0x%" PRIx64 ""),
2867 packet->payload.ip.ipc,
2868 packet->payload.ip.ip);
2872 printf_unfiltered (("tip.pgd %u: 0x%" PRIx64 ""),
2873 packet->payload.ip.ipc,
2874 packet->payload.ip.ip);
2878 printf_unfiltered (("fup %u: 0x%" PRIx64 ""),
2879 packet->payload.ip.ipc,
2880 packet->payload.ip.ip);
2884 printf_unfiltered (("tnt-8 %u: 0x%" PRIx64 ""),
2885 packet->payload.tnt.bit_size,
2886 packet->payload.tnt.payload);
2890 printf_unfiltered (("tnt-64 %u: 0x%" PRIx64 ""),
2891 packet->payload.tnt.bit_size,
2892 packet->payload.tnt.payload);
2896 printf_unfiltered (("pip %" PRIx64 "%s"), packet->payload.pip.cr3,
2897 packet->payload.pip.nr ? (" nr") : (""));
2901 printf_unfiltered (("tsc %" PRIx64 ""), packet->payload.tsc.tsc);
2905 printf_unfiltered (("cbr %u"), packet->payload.cbr.ratio);
2909 switch (packet->payload.mode.leaf)
2912 printf_unfiltered (("mode %u"), packet->payload.mode.leaf);
2916 printf_unfiltered (("mode.exec%s%s"),
2917 packet->payload.mode.bits.exec.csl
2919 packet->payload.mode.bits.exec.csd
2920 ? (" cs.d") : (""));
2924 printf_unfiltered (("mode.tsx%s%s"),
2925 packet->payload.mode.bits.tsx.intx
2927 packet->payload.mode.bits.tsx.abrt
2928 ? (" abrt") : (""));
2934 printf_unfiltered (("ovf"));
2938 printf_unfiltered (("stop"));
2942 printf_unfiltered (("vmcs %" PRIx64 ""), packet->payload.vmcs.base);
2946 printf_unfiltered (("tma %x %x"), packet->payload.tma.ctc,
2947 packet->payload.tma.fc);
2951 printf_unfiltered (("mtc %x"), packet->payload.mtc.ctc);
2955 printf_unfiltered (("cyc %" PRIx64 ""), packet->payload.cyc.value);
2959 printf_unfiltered (("mnt %" PRIx64 ""), packet->payload.mnt.payload);
2964 /* Decode packets into MAINT using DECODER. */
2967 btrace_maint_decode_pt (struct btrace_maint_info *maint,
2968 struct pt_packet_decoder *decoder)
2974 struct btrace_pt_packet packet;
2976 errcode = pt_pkt_sync_forward (decoder);
2982 pt_pkt_get_offset (decoder, &packet.offset);
2984 errcode = pt_pkt_next (decoder, &packet.packet,
2985 sizeof(packet.packet));
2989 if (maint_btrace_pt_skip_pad == 0 || packet.packet.type != ppt_pad)
2991 packet.errcode = pt_errcode (errcode);
2992 VEC_safe_push (btrace_pt_packet_s, maint->variant.pt.packets,
2997 if (errcode == -pte_eos)
3000 packet.errcode = pt_errcode (errcode);
3001 VEC_safe_push (btrace_pt_packet_s, maint->variant.pt.packets,
3004 warning (_("Error at trace offset 0x%" PRIx64 ": %s."),
3005 packet.offset, pt_errstr (packet.errcode));
3008 if (errcode != -pte_eos)
3009 warning (_("Failed to synchronize onto the Intel Processor Trace "
3010 "stream: %s."), pt_errstr (pt_errcode (errcode)));
3013 /* Update the packet history in BTINFO. */
3016 btrace_maint_update_pt_packets (struct btrace_thread_info *btinfo)
3018 struct pt_packet_decoder *decoder;
3019 const struct btrace_cpu *cpu;
3020 struct btrace_data_pt *pt;
3021 struct pt_config config;
3024 pt = &btinfo->data.variant.pt;
3026 /* Nothing to do if there is no trace. */
3030 memset (&config, 0, sizeof(config));
3032 config.size = sizeof (config);
3033 config.begin = pt->data;
3034 config.end = pt->data + pt->size;
3036 cpu = record_btrace_get_cpu ();
3038 cpu = &pt->config.cpu;
3040 /* We treat an unknown vendor as 'no errata'. */
3041 if (cpu->vendor != CV_UNKNOWN)
3043 config.cpu.vendor = pt_translate_cpu_vendor (cpu->vendor);
3044 config.cpu.family = cpu->family;
3045 config.cpu.model = cpu->model;
3046 config.cpu.stepping = cpu->stepping;
3048 errcode = pt_cpu_errata (&config.errata, &config.cpu);
3050 error (_("Failed to configure the Intel Processor Trace "
3051 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
3054 decoder = pt_pkt_alloc_decoder (&config);
3055 if (decoder == NULL)
3056 error (_("Failed to allocate the Intel Processor Trace decoder."));
3060 btrace_maint_decode_pt (&btinfo->maint, decoder);
3062 CATCH (except, RETURN_MASK_ALL)
3064 pt_pkt_free_decoder (decoder);
3066 if (except.reason < 0)
3067 throw_exception (except);
3071 pt_pkt_free_decoder (decoder);
3074 #endif /* !defined (HAVE_LIBIPT) */
3076 /* Update the packet maintenance information for BTINFO and store the
3077 low and high bounds into BEGIN and END, respectively.
3078 Store the current iterator state into FROM and TO. */
3081 btrace_maint_update_packets (struct btrace_thread_info *btinfo,
3082 unsigned int *begin, unsigned int *end,
3083 unsigned int *from, unsigned int *to)
3085 switch (btinfo->data.format)
3094 case BTRACE_FORMAT_BTS:
3095 /* Nothing to do - we operate directly on BTINFO->DATA. */
3097 *end = VEC_length (btrace_block_s, btinfo->data.variant.bts.blocks);
3098 *from = btinfo->maint.variant.bts.packet_history.begin;
3099 *to = btinfo->maint.variant.bts.packet_history.end;
3102 #if defined (HAVE_LIBIPT)
3103 case BTRACE_FORMAT_PT:
3104 if (VEC_empty (btrace_pt_packet_s, btinfo->maint.variant.pt.packets))
3105 btrace_maint_update_pt_packets (btinfo);
3108 *end = VEC_length (btrace_pt_packet_s, btinfo->maint.variant.pt.packets);
3109 *from = btinfo->maint.variant.pt.packet_history.begin;
3110 *to = btinfo->maint.variant.pt.packet_history.end;
3112 #endif /* defined (HAVE_LIBIPT) */
3116 /* Print packets in BTINFO from BEGIN (inclusive) until END (exclusive) and
3117 update the current iterator position. */
3120 btrace_maint_print_packets (struct btrace_thread_info *btinfo,
3121 unsigned int begin, unsigned int end)
3123 switch (btinfo->data.format)
3128 case BTRACE_FORMAT_BTS:
3130 VEC (btrace_block_s) *blocks;
3133 blocks = btinfo->data.variant.bts.blocks;
3134 for (blk = begin; blk < end; ++blk)
3136 const btrace_block_s *block;
3138 block = VEC_index (btrace_block_s, blocks, blk);
3140 printf_unfiltered ("%u\tbegin: %s, end: %s\n", blk,
3141 core_addr_to_string_nz (block->begin),
3142 core_addr_to_string_nz (block->end));
3145 btinfo->maint.variant.bts.packet_history.begin = begin;
3146 btinfo->maint.variant.bts.packet_history.end = end;
3150 #if defined (HAVE_LIBIPT)
3151 case BTRACE_FORMAT_PT:
3153 VEC (btrace_pt_packet_s) *packets;
3156 packets = btinfo->maint.variant.pt.packets;
3157 for (pkt = begin; pkt < end; ++pkt)
3159 const struct btrace_pt_packet *packet;
3161 packet = VEC_index (btrace_pt_packet_s, packets, pkt);
3163 printf_unfiltered ("%u\t", pkt);
3164 printf_unfiltered ("0x%" PRIx64 "\t", packet->offset);
3166 if (packet->errcode == pte_ok)
3167 pt_print_packet (&packet->packet);
3169 printf_unfiltered ("[error: %s]", pt_errstr (packet->errcode));
3171 printf_unfiltered ("\n");
3174 btinfo->maint.variant.pt.packet_history.begin = begin;
3175 btinfo->maint.variant.pt.packet_history.end = end;
3178 #endif /* defined (HAVE_LIBIPT) */
3182 /* Read a number from an argument string. */
3185 get_uint (const char **arg)
3187 const char *begin, *pos;
3189 unsigned long number;
3192 pos = skip_spaces (begin);
3194 if (!isdigit (*pos))
3195 error (_("Expected positive number, got: %s."), pos);
3197 number = strtoul (pos, &end, 10);
3198 if (number > UINT_MAX)
3199 error (_("Number too big."));
3201 *arg += (end - begin);
3203 return (unsigned int) number;
3206 /* Read a context size from an argument string. */
3209 get_context_size (const char **arg)
3211 const char *pos = skip_spaces (*arg);
3213 if (!isdigit (*pos))
3214 error (_("Expected positive number, got: %s."), pos);
3217 long result = strtol (pos, &end, 10);
3222 /* Complain about junk at the end of an argument string. */
3225 no_chunk (const char *arg)
3228 error (_("Junk after argument: %s."), arg);
3231 /* The "maintenance btrace packet-history" command. */
3234 maint_btrace_packet_history_cmd (const char *arg, int from_tty)
3236 struct btrace_thread_info *btinfo;
3237 struct thread_info *tp;
3238 unsigned int size, begin, end, from, to;
3240 tp = find_thread_ptid (inferior_ptid);
3242 error (_("No thread."));
3245 btinfo = &tp->btrace;
3247 btrace_maint_update_packets (btinfo, &begin, &end, &from, &to);
3250 printf_unfiltered (_("No trace.\n"));
3254 if (arg == NULL || *arg == 0 || strcmp (arg, "+") == 0)
3258 if (end - from < size)
3262 else if (strcmp (arg, "-") == 0)
3266 if (to - begin < size)
3272 from = get_uint (&arg);
3274 error (_("'%u' is out of range."), from);
3276 arg = skip_spaces (arg);
3279 arg = skip_spaces (++arg);
3284 size = get_context_size (&arg);
3288 if (end - from < size)
3292 else if (*arg == '-')
3295 size = get_context_size (&arg);
3299 /* Include the packet given as first argument. */
3303 if (to - begin < size)
3309 to = get_uint (&arg);
3311 /* Include the packet at the second argument and silently
3312 truncate the range. */
3325 if (end - from < size)
3333 btrace_maint_print_packets (btinfo, from, to);
3336 /* The "maintenance btrace clear-packet-history" command. */
3339 maint_btrace_clear_packet_history_cmd (const char *args, int from_tty)
3341 struct btrace_thread_info *btinfo;
3342 struct thread_info *tp;
3344 if (args != NULL && *args != 0)
3345 error (_("Invalid argument."));
3347 tp = find_thread_ptid (inferior_ptid);
3349 error (_("No thread."));
3351 btinfo = &tp->btrace;
3353 /* Must clear the maint data before - it depends on BTINFO->DATA. */
3354 btrace_maint_clear (btinfo);
3355 btinfo->data.clear ();
3358 /* The "maintenance btrace clear" command. */
3361 maint_btrace_clear_cmd (const char *args, int from_tty)
3363 struct thread_info *tp;
3365 if (args != NULL && *args != 0)
3366 error (_("Invalid argument."));
3368 tp = find_thread_ptid (inferior_ptid);
3370 error (_("No thread."));
3375 /* The "maintenance btrace" command. */
3378 maint_btrace_cmd (const char *args, int from_tty)
3380 help_list (maint_btrace_cmdlist, "maintenance btrace ", all_commands,
3384 /* The "maintenance set btrace" command. */
3387 maint_btrace_set_cmd (const char *args, int from_tty)
3389 help_list (maint_btrace_set_cmdlist, "maintenance set btrace ", all_commands,
3393 /* The "maintenance show btrace" command. */
3396 maint_btrace_show_cmd (const char *args, int from_tty)
3398 help_list (maint_btrace_show_cmdlist, "maintenance show btrace ",
3399 all_commands, gdb_stdout);
3402 /* The "maintenance set btrace pt" command. */
3405 maint_btrace_pt_set_cmd (const char *args, int from_tty)
3407 help_list (maint_btrace_pt_set_cmdlist, "maintenance set btrace pt ",
3408 all_commands, gdb_stdout);
3411 /* The "maintenance show btrace pt" command. */
3414 maint_btrace_pt_show_cmd (const char *args, int from_tty)
3416 help_list (maint_btrace_pt_show_cmdlist, "maintenance show btrace pt ",
3417 all_commands, gdb_stdout);
3420 /* The "maintenance info btrace" command. */
3423 maint_info_btrace_cmd (const char *args, int from_tty)
3425 struct btrace_thread_info *btinfo;
3426 struct thread_info *tp;
3427 const struct btrace_config *conf;
3429 if (args != NULL && *args != 0)
3430 error (_("Invalid argument."));
3432 tp = find_thread_ptid (inferior_ptid);
3434 error (_("No thread."));
3436 btinfo = &tp->btrace;
3438 conf = btrace_conf (btinfo);
3440 error (_("No btrace configuration."));
3442 printf_unfiltered (_("Format: %s.\n"),
3443 btrace_format_string (conf->format));
3445 switch (conf->format)
3450 case BTRACE_FORMAT_BTS:
3451 printf_unfiltered (_("Number of packets: %u.\n"),
3452 VEC_length (btrace_block_s,
3453 btinfo->data.variant.bts.blocks));
3456 #if defined (HAVE_LIBIPT)
3457 case BTRACE_FORMAT_PT:
3459 struct pt_version version;
3461 version = pt_library_version ();
3462 printf_unfiltered (_("Version: %u.%u.%u%s.\n"), version.major,
3463 version.minor, version.build,
3464 version.ext != NULL ? version.ext : "");
3466 btrace_maint_update_pt_packets (btinfo);
3467 printf_unfiltered (_("Number of packets: %u.\n"),
3468 VEC_length (btrace_pt_packet_s,
3469 btinfo->maint.variant.pt.packets));
3472 #endif /* defined (HAVE_LIBIPT) */
3476 /* The "maint show btrace pt skip-pad" show value function. */
3479 show_maint_btrace_pt_skip_pad (struct ui_file *file, int from_tty,
3480 struct cmd_list_element *c,
3483 fprintf_filtered (file, _("Skip PAD packets is %s.\n"), value);
3487 /* Initialize btrace maintenance commands. */
3490 _initialize_btrace (void)
3492 add_cmd ("btrace", class_maintenance, maint_info_btrace_cmd,
3493 _("Info about branch tracing data."), &maintenanceinfolist);
3495 add_prefix_cmd ("btrace", class_maintenance, maint_btrace_cmd,
3496 _("Branch tracing maintenance commands."),
3497 &maint_btrace_cmdlist, "maintenance btrace ",
3498 0, &maintenancelist);
3500 add_prefix_cmd ("btrace", class_maintenance, maint_btrace_set_cmd, _("\
3501 Set branch tracing specific variables."),
3502 &maint_btrace_set_cmdlist, "maintenance set btrace ",
3503 0, &maintenance_set_cmdlist);
3505 add_prefix_cmd ("pt", class_maintenance, maint_btrace_pt_set_cmd, _("\
3506 Set Intel Processor Trace specific variables."),
3507 &maint_btrace_pt_set_cmdlist, "maintenance set btrace pt ",
3508 0, &maint_btrace_set_cmdlist);
3510 add_prefix_cmd ("btrace", class_maintenance, maint_btrace_show_cmd, _("\
3511 Show branch tracing specific variables."),
3512 &maint_btrace_show_cmdlist, "maintenance show btrace ",
3513 0, &maintenance_show_cmdlist);
3515 add_prefix_cmd ("pt", class_maintenance, maint_btrace_pt_show_cmd, _("\
3516 Show Intel Processor Trace specific variables."),
3517 &maint_btrace_pt_show_cmdlist, "maintenance show btrace pt ",
3518 0, &maint_btrace_show_cmdlist);
3520 add_setshow_boolean_cmd ("skip-pad", class_maintenance,
3521 &maint_btrace_pt_skip_pad, _("\
3522 Set whether PAD packets should be skipped in the btrace packet history."), _("\
3523 Show whether PAD packets should be skipped in the btrace packet history."),_("\
3524 When enabled, PAD packets are ignored in the btrace packet history."),
3525 NULL, show_maint_btrace_pt_skip_pad,
3526 &maint_btrace_pt_set_cmdlist,
3527 &maint_btrace_pt_show_cmdlist);
3529 add_cmd ("packet-history", class_maintenance, maint_btrace_packet_history_cmd,
3530 _("Print the raw branch tracing data.\n\
3531 With no argument, print ten more packets after the previous ten-line print.\n\
3532 With '-' as argument print ten packets before a previous ten-line print.\n\
3533 One argument specifies the starting packet of a ten-line print.\n\
3534 Two arguments with comma between specify starting and ending packets to \
3536 Preceded with '+'/'-' the second argument specifies the distance from the \
3538 &maint_btrace_cmdlist);
3540 add_cmd ("clear-packet-history", class_maintenance,
3541 maint_btrace_clear_packet_history_cmd,
3542 _("Clears the branch tracing packet history.\n\
3543 Discards the raw branch tracing data but not the execution history data.\n\
3545 &maint_btrace_cmdlist);
3547 add_cmd ("clear", class_maintenance, maint_btrace_clear_cmd,
3548 _("Clears the branch tracing data.\n\
3549 Discards the raw branch tracing data and the execution history data.\n\
3550 The next 'record' command will fetch the branch tracing data anew.\n\
3552 &maint_btrace_cmdlist);