xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/btrace.c (revision a45db23f655e22f0c2354600d3b3c2cb98abf2dc)
1 /* Branch trace support for GDB, the GNU debugger.
2 
3    Copyright (C) 2013-2020 Free Software Foundation, Inc.
4 
5    Contributed by Intel Corp. <markus.t.metzger@intel.com>
6 
7    This file is part of GDB.
8 
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.
13 
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.
18 
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/>.  */
21 
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 "xml-support.h"
33 #include "regcache.h"
34 #include "gdbsupport/rsp-low.h"
35 #include "gdbcmd.h"
36 #include "cli/cli-utils.h"
37 #include "gdbarch.h"
38 
39 /* For maintenance commands.  */
40 #include "record-btrace.h"
41 
42 #include <inttypes.h>
43 #include <ctype.h>
44 #include <algorithm>
45 
46 /* Command lists for btrace maintenance commands.  */
47 static struct cmd_list_element *maint_btrace_cmdlist;
48 static struct cmd_list_element *maint_btrace_set_cmdlist;
49 static struct cmd_list_element *maint_btrace_show_cmdlist;
50 static struct cmd_list_element *maint_btrace_pt_set_cmdlist;
51 static struct cmd_list_element *maint_btrace_pt_show_cmdlist;
52 
53 /* Control whether to skip PAD packets when computing the packet history.  */
54 static bool maint_btrace_pt_skip_pad = true;
55 
56 static void btrace_add_pc (struct thread_info *tp);
57 
58 /* Print a record debug message.  Use do ... while (0) to avoid ambiguities
59    when used in if statements.  */
60 
61 #define DEBUG(msg, args...)						\
62   do									\
63     {									\
64       if (record_debug != 0)						\
65         fprintf_unfiltered (gdb_stdlog,					\
66 			    "[btrace] " msg "\n", ##args);		\
67     }									\
68   while (0)
69 
70 #define DEBUG_FTRACE(msg, args...) DEBUG ("[ftrace] " msg, ##args)
71 
72 /* Return the function name of a recorded function segment for printing.
73    This function never returns NULL.  */
74 
75 static const char *
76 ftrace_print_function_name (const struct btrace_function *bfun)
77 {
78   struct minimal_symbol *msym;
79   struct symbol *sym;
80 
81   msym = bfun->msym;
82   sym = bfun->sym;
83 
84   if (sym != NULL)
85     return sym->print_name ();
86 
87   if (msym != NULL)
88     return msym->print_name ();
89 
90   return "<unknown>";
91 }
92 
93 /* Return the file name of a recorded function segment for printing.
94    This function never returns NULL.  */
95 
96 static const char *
97 ftrace_print_filename (const struct btrace_function *bfun)
98 {
99   struct symbol *sym;
100   const char *filename;
101 
102   sym = bfun->sym;
103 
104   if (sym != NULL)
105     filename = symtab_to_filename_for_display (symbol_symtab (sym));
106   else
107     filename = "<unknown>";
108 
109   return filename;
110 }
111 
112 /* Return a string representation of the address of an instruction.
113    This function never returns NULL.  */
114 
115 static const char *
116 ftrace_print_insn_addr (const struct btrace_insn *insn)
117 {
118   if (insn == NULL)
119     return "<nil>";
120 
121   return core_addr_to_string_nz (insn->pc);
122 }
123 
124 /* Print an ftrace debug status message.  */
125 
126 static void
127 ftrace_debug (const struct btrace_function *bfun, const char *prefix)
128 {
129   const char *fun, *file;
130   unsigned int ibegin, iend;
131   int level;
132 
133   fun = ftrace_print_function_name (bfun);
134   file = ftrace_print_filename (bfun);
135   level = bfun->level;
136 
137   ibegin = bfun->insn_offset;
138   iend = ibegin + bfun->insn.size ();
139 
140   DEBUG_FTRACE ("%s: fun = %s, file = %s, level = %d, insn = [%u; %u)",
141 		prefix, fun, file, level, ibegin, iend);
142 }
143 
144 /* Return the number of instructions in a given function call segment.  */
145 
146 static unsigned int
147 ftrace_call_num_insn (const struct btrace_function* bfun)
148 {
149   if (bfun == NULL)
150     return 0;
151 
152   /* A gap is always counted as one instruction.  */
153   if (bfun->errcode != 0)
154     return 1;
155 
156   return bfun->insn.size ();
157 }
158 
159 /* Return the function segment with the given NUMBER or NULL if no such segment
160    exists.  BTINFO is the branch trace information for the current thread.  */
161 
162 static struct btrace_function *
163 ftrace_find_call_by_number (struct btrace_thread_info *btinfo,
164 			    unsigned int number)
165 {
166   if (number == 0 || number > btinfo->functions.size ())
167     return NULL;
168 
169   return &btinfo->functions[number - 1];
170 }
171 
172 /* A const version of the function above.  */
173 
174 static const struct btrace_function *
175 ftrace_find_call_by_number (const struct btrace_thread_info *btinfo,
176 			    unsigned int number)
177 {
178   if (number == 0 || number > btinfo->functions.size ())
179     return NULL;
180 
181   return &btinfo->functions[number - 1];
182 }
183 
184 /* Return non-zero if BFUN does not match MFUN and FUN,
185    return zero otherwise.  */
186 
187 static int
188 ftrace_function_switched (const struct btrace_function *bfun,
189 			  const struct minimal_symbol *mfun,
190 			  const struct symbol *fun)
191 {
192   struct minimal_symbol *msym;
193   struct symbol *sym;
194 
195   msym = bfun->msym;
196   sym = bfun->sym;
197 
198   /* If the minimal symbol changed, we certainly switched functions.  */
199   if (mfun != NULL && msym != NULL
200       && strcmp (mfun->linkage_name (), msym->linkage_name ()) != 0)
201     return 1;
202 
203   /* If the symbol changed, we certainly switched functions.  */
204   if (fun != NULL && sym != NULL)
205     {
206       const char *bfname, *fname;
207 
208       /* Check the function name.  */
209       if (strcmp (fun->linkage_name (), sym->linkage_name ()) != 0)
210 	return 1;
211 
212       /* Check the location of those functions, as well.  */
213       bfname = symtab_to_fullname (symbol_symtab (sym));
214       fname = symtab_to_fullname (symbol_symtab (fun));
215       if (filename_cmp (fname, bfname) != 0)
216 	return 1;
217     }
218 
219   /* If we lost symbol information, we switched functions.  */
220   if (!(msym == NULL && sym == NULL) && mfun == NULL && fun == NULL)
221     return 1;
222 
223   /* If we gained symbol information, we switched functions.  */
224   if (msym == NULL && sym == NULL && !(mfun == NULL && fun == NULL))
225     return 1;
226 
227   return 0;
228 }
229 
230 /* Allocate and initialize a new branch trace function segment at the end of
231    the trace.
232    BTINFO is the branch trace information for the current thread.
233    MFUN and FUN are the symbol information we have for this function.
234    This invalidates all struct btrace_function pointer currently held.  */
235 
236 static struct btrace_function *
237 ftrace_new_function (struct btrace_thread_info *btinfo,
238 		     struct minimal_symbol *mfun,
239 		     struct symbol *fun)
240 {
241   int level;
242   unsigned int number, insn_offset;
243 
244   if (btinfo->functions.empty ())
245     {
246       /* Start counting NUMBER and INSN_OFFSET at one.  */
247       level = 0;
248       number = 1;
249       insn_offset = 1;
250     }
251   else
252     {
253       const struct btrace_function *prev = &btinfo->functions.back ();
254       level = prev->level;
255       number = prev->number + 1;
256       insn_offset = prev->insn_offset + ftrace_call_num_insn (prev);
257     }
258 
259   btinfo->functions.emplace_back (mfun, fun, number, insn_offset, level);
260   return &btinfo->functions.back ();
261 }
262 
263 /* Update the UP field of a function segment.  */
264 
265 static void
266 ftrace_update_caller (struct btrace_function *bfun,
267 		      struct btrace_function *caller,
268 		      enum btrace_function_flag flags)
269 {
270   if (bfun->up != 0)
271     ftrace_debug (bfun, "updating caller");
272 
273   bfun->up = caller->number;
274   bfun->flags = flags;
275 
276   ftrace_debug (bfun, "set caller");
277   ftrace_debug (caller, "..to");
278 }
279 
280 /* Fix up the caller for all segments of a function.  */
281 
282 static void
283 ftrace_fixup_caller (struct btrace_thread_info *btinfo,
284 		     struct btrace_function *bfun,
285 		     struct btrace_function *caller,
286 		     enum btrace_function_flag flags)
287 {
288   unsigned int prev, next;
289 
290   prev = bfun->prev;
291   next = bfun->next;
292   ftrace_update_caller (bfun, caller, flags);
293 
294   /* Update all function segments belonging to the same function.  */
295   for (; prev != 0; prev = bfun->prev)
296     {
297       bfun = ftrace_find_call_by_number (btinfo, prev);
298       ftrace_update_caller (bfun, caller, flags);
299     }
300 
301   for (; next != 0; next = bfun->next)
302     {
303       bfun = ftrace_find_call_by_number (btinfo, next);
304       ftrace_update_caller (bfun, caller, flags);
305     }
306 }
307 
308 /* Add a new function segment for a call at the end of the trace.
309    BTINFO is the branch trace information for the current thread.
310    MFUN and FUN are the symbol information we have for this function.  */
311 
312 static struct btrace_function *
313 ftrace_new_call (struct btrace_thread_info *btinfo,
314 		 struct minimal_symbol *mfun,
315 		 struct symbol *fun)
316 {
317   const unsigned int length = btinfo->functions.size ();
318   struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
319 
320   bfun->up = length;
321   bfun->level += 1;
322 
323   ftrace_debug (bfun, "new call");
324 
325   return bfun;
326 }
327 
328 /* Add a new function segment for a tail call at the end of the trace.
329    BTINFO is the branch trace information for the current thread.
330    MFUN and FUN are the symbol information we have for this function.  */
331 
332 static struct btrace_function *
333 ftrace_new_tailcall (struct btrace_thread_info *btinfo,
334 		     struct minimal_symbol *mfun,
335 		     struct symbol *fun)
336 {
337   const unsigned int length = btinfo->functions.size ();
338   struct btrace_function *bfun = ftrace_new_function (btinfo, mfun, fun);
339 
340   bfun->up = length;
341   bfun->level += 1;
342   bfun->flags |= BFUN_UP_LINKS_TO_TAILCALL;
343 
344   ftrace_debug (bfun, "new tail call");
345 
346   return bfun;
347 }
348 
349 /* Return the caller of BFUN or NULL if there is none.  This function skips
350    tail calls in the call chain.  BTINFO is the branch trace information for
351    the current thread.  */
352 static struct btrace_function *
353 ftrace_get_caller (struct btrace_thread_info *btinfo,
354 		   struct btrace_function *bfun)
355 {
356   for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
357     if ((bfun->flags & BFUN_UP_LINKS_TO_TAILCALL) == 0)
358       return ftrace_find_call_by_number (btinfo, bfun->up);
359 
360   return NULL;
361 }
362 
363 /* Find the innermost caller in the back trace of BFUN with MFUN/FUN
364    symbol information.  BTINFO is the branch trace information for the current
365    thread.  */
366 
367 static struct btrace_function *
368 ftrace_find_caller (struct btrace_thread_info *btinfo,
369 		    struct btrace_function *bfun,
370 		    struct minimal_symbol *mfun,
371 		    struct symbol *fun)
372 {
373   for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
374     {
375       /* Skip functions with incompatible symbol information.  */
376       if (ftrace_function_switched (bfun, mfun, fun))
377 	continue;
378 
379       /* This is the function segment we're looking for.  */
380       break;
381     }
382 
383   return bfun;
384 }
385 
386 /* Find the innermost caller in the back trace of BFUN, skipping all
387    function segments that do not end with a call instruction (e.g.
388    tail calls ending with a jump).  BTINFO is the branch trace information for
389    the current thread.  */
390 
391 static struct btrace_function *
392 ftrace_find_call (struct btrace_thread_info *btinfo,
393 		  struct btrace_function *bfun)
394 {
395   for (; bfun != NULL; bfun = ftrace_find_call_by_number (btinfo, bfun->up))
396     {
397       /* Skip gaps.  */
398       if (bfun->errcode != 0)
399 	continue;
400 
401       btrace_insn &last = bfun->insn.back ();
402 
403       if (last.iclass == BTRACE_INSN_CALL)
404 	break;
405     }
406 
407   return bfun;
408 }
409 
410 /* Add a continuation segment for a function into which we return at the end of
411    the trace.
412    BTINFO is the branch trace information for the current thread.
413    MFUN and FUN are the symbol information we have for this function.  */
414 
415 static struct btrace_function *
416 ftrace_new_return (struct btrace_thread_info *btinfo,
417 		   struct minimal_symbol *mfun,
418 		   struct symbol *fun)
419 {
420   struct btrace_function *prev, *bfun, *caller;
421 
422   bfun = ftrace_new_function (btinfo, mfun, fun);
423   prev = ftrace_find_call_by_number (btinfo, bfun->number - 1);
424 
425   /* It is important to start at PREV's caller.  Otherwise, we might find
426      PREV itself, if PREV is a recursive function.  */
427   caller = ftrace_find_call_by_number (btinfo, prev->up);
428   caller = ftrace_find_caller (btinfo, caller, mfun, fun);
429   if (caller != NULL)
430     {
431       /* The caller of PREV is the preceding btrace function segment in this
432 	 function instance.  */
433       gdb_assert (caller->next == 0);
434 
435       caller->next = bfun->number;
436       bfun->prev = caller->number;
437 
438       /* Maintain the function level.  */
439       bfun->level = caller->level;
440 
441       /* Maintain the call stack.  */
442       bfun->up = caller->up;
443       bfun->flags = caller->flags;
444 
445       ftrace_debug (bfun, "new return");
446     }
447   else
448     {
449       /* We did not find a caller.  This could mean that something went
450 	 wrong or that the call is simply not included in the trace.  */
451 
452       /* Let's search for some actual call.  */
453       caller = ftrace_find_call_by_number (btinfo, prev->up);
454       caller = ftrace_find_call (btinfo, caller);
455       if (caller == NULL)
456 	{
457 	  /* There is no call in PREV's back trace.  We assume that the
458 	     branch trace did not include it.  */
459 
460 	  /* Let's find the topmost function and add a new caller for it.
461 	     This should handle a series of initial tail calls.  */
462 	  while (prev->up != 0)
463 	    prev = ftrace_find_call_by_number (btinfo, prev->up);
464 
465 	  bfun->level = prev->level - 1;
466 
467 	  /* Fix up the call stack for PREV.  */
468 	  ftrace_fixup_caller (btinfo, prev, bfun, BFUN_UP_LINKS_TO_RET);
469 
470 	  ftrace_debug (bfun, "new return - no caller");
471 	}
472       else
473 	{
474 	  /* There is a call in PREV's back trace to which we should have
475 	     returned but didn't.  Let's start a new, separate back trace
476 	     from PREV's level.  */
477 	  bfun->level = prev->level - 1;
478 
479 	  /* We fix up the back trace for PREV but leave other function segments
480 	     on the same level as they are.
481 	     This should handle things like schedule () correctly where we're
482 	     switching contexts.  */
483 	  prev->up = bfun->number;
484 	  prev->flags = BFUN_UP_LINKS_TO_RET;
485 
486 	  ftrace_debug (bfun, "new return - unknown caller");
487 	}
488     }
489 
490   return bfun;
491 }
492 
493 /* Add a new function segment for a function switch at the end of the trace.
494    BTINFO is the branch trace information for the current thread.
495    MFUN and FUN are the symbol information we have for this function.  */
496 
497 static struct btrace_function *
498 ftrace_new_switch (struct btrace_thread_info *btinfo,
499 		   struct minimal_symbol *mfun,
500 		   struct symbol *fun)
501 {
502   struct btrace_function *prev, *bfun;
503 
504   /* This is an unexplained function switch.  We can't really be sure about the
505      call stack, yet the best I can think of right now is to preserve it.  */
506   bfun = ftrace_new_function (btinfo, mfun, fun);
507   prev = ftrace_find_call_by_number (btinfo, bfun->number - 1);
508   bfun->up = prev->up;
509   bfun->flags = prev->flags;
510 
511   ftrace_debug (bfun, "new switch");
512 
513   return bfun;
514 }
515 
516 /* Add a new function segment for a gap in the trace due to a decode error at
517    the end of the trace.
518    BTINFO is the branch trace information for the current thread.
519    ERRCODE is the format-specific error code.  */
520 
521 static struct btrace_function *
522 ftrace_new_gap (struct btrace_thread_info *btinfo, int errcode,
523 		std::vector<unsigned int> &gaps)
524 {
525   struct btrace_function *bfun;
526 
527   if (btinfo->functions.empty ())
528     bfun = ftrace_new_function (btinfo, NULL, NULL);
529   else
530     {
531       /* We hijack the previous function segment if it was empty.  */
532       bfun = &btinfo->functions.back ();
533       if (bfun->errcode != 0 || !bfun->insn.empty ())
534 	bfun = ftrace_new_function (btinfo, NULL, NULL);
535     }
536 
537   bfun->errcode = errcode;
538   gaps.push_back (bfun->number);
539 
540   ftrace_debug (bfun, "new gap");
541 
542   return bfun;
543 }
544 
545 /* Update the current function segment at the end of the trace in BTINFO with
546    respect to the instruction at PC.  This may create new function segments.
547    Return the chronologically latest function segment, never NULL.  */
548 
549 static struct btrace_function *
550 ftrace_update_function (struct btrace_thread_info *btinfo, CORE_ADDR pc)
551 {
552   struct bound_minimal_symbol bmfun;
553   struct minimal_symbol *mfun;
554   struct symbol *fun;
555   struct btrace_function *bfun;
556 
557   /* Try to determine the function we're in.  We use both types of symbols
558      to avoid surprises when we sometimes get a full symbol and sometimes
559      only a minimal symbol.  */
560   fun = find_pc_function (pc);
561   bmfun = lookup_minimal_symbol_by_pc (pc);
562   mfun = bmfun.minsym;
563 
564   if (fun == NULL && mfun == NULL)
565     DEBUG_FTRACE ("no symbol at %s", core_addr_to_string_nz (pc));
566 
567   /* If we didn't have a function, we create one.  */
568   if (btinfo->functions.empty ())
569     return ftrace_new_function (btinfo, mfun, fun);
570 
571   /* If we had a gap before, we create a function.  */
572   bfun = &btinfo->functions.back ();
573   if (bfun->errcode != 0)
574     return ftrace_new_function (btinfo, mfun, fun);
575 
576   /* Check the last instruction, if we have one.
577      We do this check first, since it allows us to fill in the call stack
578      links in addition to the normal flow links.  */
579   btrace_insn *last = NULL;
580   if (!bfun->insn.empty ())
581     last = &bfun->insn.back ();
582 
583   if (last != NULL)
584     {
585       switch (last->iclass)
586 	{
587 	case BTRACE_INSN_RETURN:
588 	  {
589 	    const char *fname;
590 
591 	    /* On some systems, _dl_runtime_resolve returns to the resolved
592 	       function instead of jumping to it.  From our perspective,
593 	       however, this is a tailcall.
594 	       If we treated it as return, we wouldn't be able to find the
595 	       resolved function in our stack back trace.  Hence, we would
596 	       lose the current stack back trace and start anew with an empty
597 	       back trace.  When the resolved function returns, we would then
598 	       create a stack back trace with the same function names but
599 	       different frame id's.  This will confuse stepping.  */
600 	    fname = ftrace_print_function_name (bfun);
601 	    if (strcmp (fname, "_dl_runtime_resolve") == 0)
602 	      return ftrace_new_tailcall (btinfo, mfun, fun);
603 
604 	    return ftrace_new_return (btinfo, mfun, fun);
605 	  }
606 
607 	case BTRACE_INSN_CALL:
608 	  /* Ignore calls to the next instruction.  They are used for PIC.  */
609 	  if (last->pc + last->size == pc)
610 	    break;
611 
612 	  return ftrace_new_call (btinfo, mfun, fun);
613 
614 	case BTRACE_INSN_JUMP:
615 	  {
616 	    CORE_ADDR start;
617 
618 	    start = get_pc_function_start (pc);
619 
620 	    /* A jump to the start of a function is (typically) a tail call.  */
621 	    if (start == pc)
622 	      return ftrace_new_tailcall (btinfo, mfun, fun);
623 
624 	    /* Some versions of _Unwind_RaiseException use an indirect
625 	       jump to 'return' to the exception handler of the caller
626 	       handling the exception instead of a return.  Let's restrict
627 	       this heuristic to that and related functions.  */
628 	    const char *fname = ftrace_print_function_name (bfun);
629 	    if (strncmp (fname, "_Unwind_", strlen ("_Unwind_")) == 0)
630 	      {
631 		struct btrace_function *caller
632 		  = ftrace_find_call_by_number (btinfo, bfun->up);
633 		caller = ftrace_find_caller (btinfo, caller, mfun, fun);
634 		if (caller != NULL)
635 		  return ftrace_new_return (btinfo, mfun, fun);
636 	      }
637 
638 	    /* If we can't determine the function for PC, we treat a jump at
639 	       the end of the block as tail call if we're switching functions
640 	       and as an intra-function branch if we don't.  */
641 	    if (start == 0 && ftrace_function_switched (bfun, mfun, fun))
642 	      return ftrace_new_tailcall (btinfo, mfun, fun);
643 
644 	    break;
645 	  }
646 	}
647     }
648 
649   /* Check if we're switching functions for some other reason.  */
650   if (ftrace_function_switched (bfun, mfun, fun))
651     {
652       DEBUG_FTRACE ("switching from %s in %s at %s",
653 		    ftrace_print_insn_addr (last),
654 		    ftrace_print_function_name (bfun),
655 		    ftrace_print_filename (bfun));
656 
657       return ftrace_new_switch (btinfo, mfun, fun);
658     }
659 
660   return bfun;
661 }
662 
663 /* Add the instruction at PC to BFUN's instructions.  */
664 
665 static void
666 ftrace_update_insns (struct btrace_function *bfun, const btrace_insn &insn)
667 {
668   bfun->insn.push_back (insn);
669 
670   if (record_debug > 1)
671     ftrace_debug (bfun, "update insn");
672 }
673 
674 /* Classify the instruction at PC.  */
675 
676 static enum btrace_insn_class
677 ftrace_classify_insn (struct gdbarch *gdbarch, CORE_ADDR pc)
678 {
679   enum btrace_insn_class iclass;
680 
681   iclass = BTRACE_INSN_OTHER;
682   try
683     {
684       if (gdbarch_insn_is_call (gdbarch, pc))
685 	iclass = BTRACE_INSN_CALL;
686       else if (gdbarch_insn_is_ret (gdbarch, pc))
687 	iclass = BTRACE_INSN_RETURN;
688       else if (gdbarch_insn_is_jump (gdbarch, pc))
689 	iclass = BTRACE_INSN_JUMP;
690     }
691   catch (const gdb_exception_error &error)
692     {
693     }
694 
695   return iclass;
696 }
697 
698 /* Try to match the back trace at LHS to the back trace at RHS.  Returns the
699    number of matching function segments or zero if the back traces do not
700    match.  BTINFO is the branch trace information for the current thread.  */
701 
702 static int
703 ftrace_match_backtrace (struct btrace_thread_info *btinfo,
704 			struct btrace_function *lhs,
705 			struct btrace_function *rhs)
706 {
707   int matches;
708 
709   for (matches = 0; lhs != NULL && rhs != NULL; ++matches)
710     {
711       if (ftrace_function_switched (lhs, rhs->msym, rhs->sym))
712 	return 0;
713 
714       lhs = ftrace_get_caller (btinfo, lhs);
715       rhs = ftrace_get_caller (btinfo, rhs);
716     }
717 
718   return matches;
719 }
720 
721 /* Add ADJUSTMENT to the level of BFUN and succeeding function segments.
722    BTINFO is the branch trace information for the current thread.  */
723 
724 static void
725 ftrace_fixup_level (struct btrace_thread_info *btinfo,
726 		    struct btrace_function *bfun, int adjustment)
727 {
728   if (adjustment == 0)
729     return;
730 
731   DEBUG_FTRACE ("fixup level (%+d)", adjustment);
732   ftrace_debug (bfun, "..bfun");
733 
734   while (bfun != NULL)
735     {
736       bfun->level += adjustment;
737       bfun = ftrace_find_call_by_number (btinfo, bfun->number + 1);
738     }
739 }
740 
741 /* Recompute the global level offset.  Traverse the function trace and compute
742    the global level offset as the negative of the minimal function level.  */
743 
744 static void
745 ftrace_compute_global_level_offset (struct btrace_thread_info *btinfo)
746 {
747   int level = INT_MAX;
748 
749   if (btinfo == NULL)
750     return;
751 
752   if (btinfo->functions.empty ())
753     return;
754 
755   unsigned int length = btinfo->functions.size() - 1;
756   for (unsigned int i = 0; i < length; ++i)
757     level = std::min (level, btinfo->functions[i].level);
758 
759   /* The last function segment contains the current instruction, which is not
760      really part of the trace.  If it contains just this one instruction, we
761      ignore the segment.  */
762   struct btrace_function *last = &btinfo->functions.back();
763   if (last->insn.size () != 1)
764     level = std::min (level, last->level);
765 
766   DEBUG_FTRACE ("setting global level offset: %d", -level);
767   btinfo->level = -level;
768 }
769 
770 /* Connect the function segments PREV and NEXT in a bottom-to-top walk as in
771    ftrace_connect_backtrace.  BTINFO is the branch trace information for the
772    current thread.  */
773 
774 static void
775 ftrace_connect_bfun (struct btrace_thread_info *btinfo,
776 		     struct btrace_function *prev,
777 		     struct btrace_function *next)
778 {
779   DEBUG_FTRACE ("connecting...");
780   ftrace_debug (prev, "..prev");
781   ftrace_debug (next, "..next");
782 
783   /* The function segments are not yet connected.  */
784   gdb_assert (prev->next == 0);
785   gdb_assert (next->prev == 0);
786 
787   prev->next = next->number;
788   next->prev = prev->number;
789 
790   /* We may have moved NEXT to a different function level.  */
791   ftrace_fixup_level (btinfo, next, prev->level - next->level);
792 
793   /* If we run out of back trace for one, let's use the other's.  */
794   if (prev->up == 0)
795     {
796       const btrace_function_flags flags = next->flags;
797 
798       next = ftrace_find_call_by_number (btinfo, next->up);
799       if (next != NULL)
800 	{
801 	  DEBUG_FTRACE ("using next's callers");
802 	  ftrace_fixup_caller (btinfo, prev, next, flags);
803 	}
804     }
805   else if (next->up == 0)
806     {
807       const btrace_function_flags flags = prev->flags;
808 
809       prev = ftrace_find_call_by_number (btinfo, prev->up);
810       if (prev != NULL)
811 	{
812 	  DEBUG_FTRACE ("using prev's callers");
813 	  ftrace_fixup_caller (btinfo, next, prev, flags);
814 	}
815     }
816   else
817     {
818       /* PREV may have a tailcall caller, NEXT can't.  If it does, fixup the up
819 	 link to add the tail callers to NEXT's back trace.
820 
821 	 This removes NEXT->UP from NEXT's back trace.  It will be added back
822 	 when connecting NEXT and PREV's callers - provided they exist.
823 
824 	 If PREV's back trace consists of a series of tail calls without an
825 	 actual call, there will be no further connection and NEXT's caller will
826 	 be removed for good.  To catch this case, we handle it here and connect
827 	 the top of PREV's back trace to NEXT's caller.  */
828       if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) != 0)
829 	{
830 	  struct btrace_function *caller;
831 	  btrace_function_flags next_flags, prev_flags;
832 
833 	  /* We checked NEXT->UP above so CALLER can't be NULL.  */
834 	  caller = ftrace_find_call_by_number (btinfo, next->up);
835 	  next_flags = next->flags;
836 	  prev_flags = prev->flags;
837 
838 	  DEBUG_FTRACE ("adding prev's tail calls to next");
839 
840 	  prev = ftrace_find_call_by_number (btinfo, prev->up);
841 	  ftrace_fixup_caller (btinfo, next, prev, prev_flags);
842 
843 	  for (; prev != NULL; prev = ftrace_find_call_by_number (btinfo,
844 								  prev->up))
845 	    {
846 	      /* At the end of PREV's back trace, continue with CALLER.  */
847 	      if (prev->up == 0)
848 		{
849 		  DEBUG_FTRACE ("fixing up link for tailcall chain");
850 		  ftrace_debug (prev, "..top");
851 		  ftrace_debug (caller, "..up");
852 
853 		  ftrace_fixup_caller (btinfo, prev, caller, next_flags);
854 
855 		  /* If we skipped any tail calls, this may move CALLER to a
856 		     different function level.
857 
858 		     Note that changing CALLER's level is only OK because we
859 		     know that this is the last iteration of the bottom-to-top
860 		     walk in ftrace_connect_backtrace.
861 
862 		     Otherwise we will fix up CALLER's level when we connect it
863 		     to PREV's caller in the next iteration.  */
864 		  ftrace_fixup_level (btinfo, caller,
865 				      prev->level - caller->level - 1);
866 		  break;
867 		}
868 
869 	      /* There's nothing to do if we find a real call.  */
870 	      if ((prev->flags & BFUN_UP_LINKS_TO_TAILCALL) == 0)
871 		{
872 		  DEBUG_FTRACE ("will fix up link in next iteration");
873 		  break;
874 		}
875 	    }
876 	}
877     }
878 }
879 
880 /* Connect function segments on the same level in the back trace at LHS and RHS.
881    The back traces at LHS and RHS are expected to match according to
882    ftrace_match_backtrace.  BTINFO is the branch trace information for the
883    current thread.  */
884 
885 static void
886 ftrace_connect_backtrace (struct btrace_thread_info *btinfo,
887 			  struct btrace_function *lhs,
888 			  struct btrace_function *rhs)
889 {
890   while (lhs != NULL && rhs != NULL)
891     {
892       struct btrace_function *prev, *next;
893 
894       gdb_assert (!ftrace_function_switched (lhs, rhs->msym, rhs->sym));
895 
896       /* Connecting LHS and RHS may change the up link.  */
897       prev = lhs;
898       next = rhs;
899 
900       lhs = ftrace_get_caller (btinfo, lhs);
901       rhs = ftrace_get_caller (btinfo, rhs);
902 
903       ftrace_connect_bfun (btinfo, prev, next);
904     }
905 }
906 
907 /* Bridge the gap between two function segments left and right of a gap if their
908    respective back traces match in at least MIN_MATCHES functions.  BTINFO is
909    the branch trace information for the current thread.
910 
911    Returns non-zero if the gap could be bridged, zero otherwise.  */
912 
913 static int
914 ftrace_bridge_gap (struct btrace_thread_info *btinfo,
915 		   struct btrace_function *lhs, struct btrace_function *rhs,
916 		   int min_matches)
917 {
918   struct btrace_function *best_l, *best_r, *cand_l, *cand_r;
919   int best_matches;
920 
921   DEBUG_FTRACE ("checking gap at insn %u (req matches: %d)",
922 		rhs->insn_offset - 1, min_matches);
923 
924   best_matches = 0;
925   best_l = NULL;
926   best_r = NULL;
927 
928   /* We search the back traces of LHS and RHS for valid connections and connect
929      the two function segments that give the longest combined back trace.  */
930 
931   for (cand_l = lhs; cand_l != NULL;
932        cand_l = ftrace_get_caller (btinfo, cand_l))
933     for (cand_r = rhs; cand_r != NULL;
934 	 cand_r = ftrace_get_caller (btinfo, cand_r))
935       {
936 	int matches;
937 
938 	matches = ftrace_match_backtrace (btinfo, cand_l, cand_r);
939 	if (best_matches < matches)
940 	  {
941 	    best_matches = matches;
942 	    best_l = cand_l;
943 	    best_r = cand_r;
944 	  }
945       }
946 
947   /* We need at least MIN_MATCHES matches.  */
948   gdb_assert (min_matches > 0);
949   if (best_matches < min_matches)
950     return 0;
951 
952   DEBUG_FTRACE ("..matches: %d", best_matches);
953 
954   /* We will fix up the level of BEST_R and succeeding function segments such
955      that BEST_R's level matches BEST_L's when we connect BEST_L to BEST_R.
956 
957      This will ignore the level of RHS and following if BEST_R != RHS.  I.e. if
958      BEST_R is a successor of RHS in the back trace of RHS (phases 1 and 3).
959 
960      To catch this, we already fix up the level here where we can start at RHS
961      instead of at BEST_R.  We will ignore the level fixup when connecting
962      BEST_L to BEST_R as they will already be on the same level.  */
963   ftrace_fixup_level (btinfo, rhs, best_l->level - best_r->level);
964 
965   ftrace_connect_backtrace (btinfo, best_l, best_r);
966 
967   return best_matches;
968 }
969 
970 /* Try to bridge gaps due to overflow or decode errors by connecting the
971    function segments that are separated by the gap.  */
972 
973 static void
974 btrace_bridge_gaps (struct thread_info *tp, std::vector<unsigned int> &gaps)
975 {
976   struct btrace_thread_info *btinfo = &tp->btrace;
977   std::vector<unsigned int> remaining;
978   int min_matches;
979 
980   DEBUG ("bridge gaps");
981 
982   /* We require a minimum amount of matches for bridging a gap.  The number of
983      required matches will be lowered with each iteration.
984 
985      The more matches the higher our confidence that the bridging is correct.
986      For big gaps or small traces, however, it may not be feasible to require a
987      high number of matches.  */
988   for (min_matches = 5; min_matches > 0; --min_matches)
989     {
990       /* Let's try to bridge as many gaps as we can.  In some cases, we need to
991 	 skip a gap and revisit it again after we closed later gaps.  */
992       while (!gaps.empty ())
993 	{
994 	  for (const unsigned int number : gaps)
995 	    {
996 	      struct btrace_function *gap, *lhs, *rhs;
997 	      int bridged;
998 
999 	      gap = ftrace_find_call_by_number (btinfo, number);
1000 
1001 	      /* We may have a sequence of gaps if we run from one error into
1002 		 the next as we try to re-sync onto the trace stream.  Ignore
1003 		 all but the leftmost gap in such a sequence.
1004 
1005 		 Also ignore gaps at the beginning of the trace.  */
1006 	      lhs = ftrace_find_call_by_number (btinfo, gap->number - 1);
1007 	      if (lhs == NULL || lhs->errcode != 0)
1008 		continue;
1009 
1010 	      /* Skip gaps to the right.  */
1011 	      rhs = ftrace_find_call_by_number (btinfo, gap->number + 1);
1012 	      while (rhs != NULL && rhs->errcode != 0)
1013 		rhs = ftrace_find_call_by_number (btinfo, rhs->number + 1);
1014 
1015 	      /* Ignore gaps at the end of the trace.  */
1016 	      if (rhs == NULL)
1017 		continue;
1018 
1019 	      bridged = ftrace_bridge_gap (btinfo, lhs, rhs, min_matches);
1020 
1021 	      /* Keep track of gaps we were not able to bridge and try again.
1022 		 If we just pushed them to the end of GAPS we would risk an
1023 		 infinite loop in case we simply cannot bridge a gap.  */
1024 	      if (bridged == 0)
1025 		remaining.push_back (number);
1026 	    }
1027 
1028 	  /* Let's see if we made any progress.  */
1029 	  if (remaining.size () == gaps.size ())
1030 	    break;
1031 
1032 	  gaps.clear ();
1033 	  gaps.swap (remaining);
1034 	}
1035 
1036       /* We get here if either GAPS is empty or if GAPS equals REMAINING.  */
1037       if (gaps.empty ())
1038 	break;
1039 
1040       remaining.clear ();
1041     }
1042 
1043   /* We may omit this in some cases.  Not sure it is worth the extra
1044      complication, though.  */
1045   ftrace_compute_global_level_offset (btinfo);
1046 }
1047 
1048 /* Compute the function branch trace from BTS trace.  */
1049 
1050 static void
1051 btrace_compute_ftrace_bts (struct thread_info *tp,
1052 			   const struct btrace_data_bts *btrace,
1053 			   std::vector<unsigned int> &gaps)
1054 {
1055   struct btrace_thread_info *btinfo;
1056   struct gdbarch *gdbarch;
1057   unsigned int blk;
1058   int level;
1059 
1060   gdbarch = target_gdbarch ();
1061   btinfo = &tp->btrace;
1062   blk = btrace->blocks->size ();
1063 
1064   if (btinfo->functions.empty ())
1065     level = INT_MAX;
1066   else
1067     level = -btinfo->level;
1068 
1069   while (blk != 0)
1070     {
1071       CORE_ADDR pc;
1072 
1073       blk -= 1;
1074 
1075       const btrace_block &block = btrace->blocks->at (blk);
1076       pc = block.begin;
1077 
1078       for (;;)
1079 	{
1080 	  struct btrace_function *bfun;
1081 	  struct btrace_insn insn;
1082 	  int size;
1083 
1084 	  /* We should hit the end of the block.  Warn if we went too far.  */
1085 	  if (block.end < pc)
1086 	    {
1087 	      /* Indicate the gap in the trace.  */
1088 	      bfun = ftrace_new_gap (btinfo, BDE_BTS_OVERFLOW, gaps);
1089 
1090 	      warning (_("Recorded trace may be corrupted at instruction "
1091 			 "%u (pc = %s)."), bfun->insn_offset - 1,
1092 		       core_addr_to_string_nz (pc));
1093 
1094 	      break;
1095 	    }
1096 
1097 	  bfun = ftrace_update_function (btinfo, pc);
1098 
1099 	  /* Maintain the function level offset.
1100 	     For all but the last block, we do it here.  */
1101 	  if (blk != 0)
1102 	    level = std::min (level, bfun->level);
1103 
1104 	  size = 0;
1105 	  try
1106 	    {
1107 	      size = gdb_insn_length (gdbarch, pc);
1108 	    }
1109 	  catch (const gdb_exception_error &error)
1110 	    {
1111 	    }
1112 
1113 	  insn.pc = pc;
1114 	  insn.size = size;
1115 	  insn.iclass = ftrace_classify_insn (gdbarch, pc);
1116 	  insn.flags = 0;
1117 
1118 	  ftrace_update_insns (bfun, insn);
1119 
1120 	  /* We're done once we pushed the instruction at the end.  */
1121 	  if (block.end == pc)
1122 	    break;
1123 
1124 	  /* We can't continue if we fail to compute the size.  */
1125 	  if (size <= 0)
1126 	    {
1127 	      /* Indicate the gap in the trace.  We just added INSN so we're
1128 		 not at the beginning.  */
1129 	      bfun = ftrace_new_gap (btinfo, BDE_BTS_INSN_SIZE, gaps);
1130 
1131 	      warning (_("Recorded trace may be incomplete at instruction %u "
1132 			 "(pc = %s)."), bfun->insn_offset - 1,
1133 		       core_addr_to_string_nz (pc));
1134 
1135 	      break;
1136 	    }
1137 
1138 	  pc += size;
1139 
1140 	  /* Maintain the function level offset.
1141 	     For the last block, we do it here to not consider the last
1142 	     instruction.
1143 	     Since the last instruction corresponds to the current instruction
1144 	     and is not really part of the execution history, it shouldn't
1145 	     affect the level.  */
1146 	  if (blk == 0)
1147 	    level = std::min (level, bfun->level);
1148 	}
1149     }
1150 
1151   /* LEVEL is the minimal function level of all btrace function segments.
1152      Define the global level offset to -LEVEL so all function levels are
1153      normalized to start at zero.  */
1154   btinfo->level = -level;
1155 }
1156 
1157 #if defined (HAVE_LIBIPT)
1158 
1159 static enum btrace_insn_class
1160 pt_reclassify_insn (enum pt_insn_class iclass)
1161 {
1162   switch (iclass)
1163     {
1164     case ptic_call:
1165       return BTRACE_INSN_CALL;
1166 
1167     case ptic_return:
1168       return BTRACE_INSN_RETURN;
1169 
1170     case ptic_jump:
1171       return BTRACE_INSN_JUMP;
1172 
1173     default:
1174       return BTRACE_INSN_OTHER;
1175     }
1176 }
1177 
1178 /* Return the btrace instruction flags for INSN.  */
1179 
1180 static btrace_insn_flags
1181 pt_btrace_insn_flags (const struct pt_insn &insn)
1182 {
1183   btrace_insn_flags flags = 0;
1184 
1185   if (insn.speculative)
1186     flags |= BTRACE_INSN_FLAG_SPECULATIVE;
1187 
1188   return flags;
1189 }
1190 
1191 /* Return the btrace instruction for INSN.  */
1192 
1193 static btrace_insn
1194 pt_btrace_insn (const struct pt_insn &insn)
1195 {
1196   return {(CORE_ADDR) insn.ip, (gdb_byte) insn.size,
1197 	  pt_reclassify_insn (insn.iclass),
1198 	  pt_btrace_insn_flags (insn)};
1199 }
1200 
1201 /* Handle instruction decode events (libipt-v2).  */
1202 
1203 static int
1204 handle_pt_insn_events (struct btrace_thread_info *btinfo,
1205 		       struct pt_insn_decoder *decoder,
1206 		       std::vector<unsigned int> &gaps, int status)
1207 {
1208 #if defined (HAVE_PT_INSN_EVENT)
1209   while (status & pts_event_pending)
1210     {
1211       struct btrace_function *bfun;
1212       struct pt_event event;
1213       uint64_t offset;
1214 
1215       status = pt_insn_event (decoder, &event, sizeof (event));
1216       if (status < 0)
1217 	break;
1218 
1219       switch (event.type)
1220 	{
1221 	default:
1222 	  break;
1223 
1224 	case ptev_enabled:
1225 	  if (event.variant.enabled.resumed == 0 && !btinfo->functions.empty ())
1226 	    {
1227 	      bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1228 
1229 	      pt_insn_get_offset (decoder, &offset);
1230 
1231 	      warning (_("Non-contiguous trace at instruction %u (offset = 0x%"
1232 			 PRIx64 ")."), bfun->insn_offset - 1, offset);
1233 	    }
1234 
1235 	  break;
1236 
1237 	case ptev_overflow:
1238 	  bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1239 
1240 	  pt_insn_get_offset (decoder, &offset);
1241 
1242 	  warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ")."),
1243 		   bfun->insn_offset - 1, offset);
1244 
1245 	  break;
1246 	}
1247     }
1248 #endif /* defined (HAVE_PT_INSN_EVENT) */
1249 
1250   return status;
1251 }
1252 
1253 /* Handle events indicated by flags in INSN (libipt-v1).  */
1254 
1255 static void
1256 handle_pt_insn_event_flags (struct btrace_thread_info *btinfo,
1257 			    struct pt_insn_decoder *decoder,
1258 			    const struct pt_insn &insn,
1259 			    std::vector<unsigned int> &gaps)
1260 {
1261 #if defined (HAVE_STRUCT_PT_INSN_ENABLED)
1262   /* Tracing is disabled and re-enabled each time we enter the kernel.  Most
1263      times, we continue from the same instruction we stopped before.  This is
1264      indicated via the RESUMED instruction flag.  The ENABLED instruction flag
1265      means that we continued from some other instruction.  Indicate this as a
1266      trace gap except when tracing just started.  */
1267   if (insn.enabled && !btinfo->functions.empty ())
1268     {
1269       struct btrace_function *bfun;
1270       uint64_t offset;
1271 
1272       bfun = ftrace_new_gap (btinfo, BDE_PT_DISABLED, gaps);
1273 
1274       pt_insn_get_offset (decoder, &offset);
1275 
1276       warning (_("Non-contiguous trace at instruction %u (offset = 0x%" PRIx64
1277 		 ", pc = 0x%" PRIx64 ")."), bfun->insn_offset - 1, offset,
1278 	       insn.ip);
1279     }
1280 #endif /* defined (HAVE_STRUCT_PT_INSN_ENABLED) */
1281 
1282 #if defined (HAVE_STRUCT_PT_INSN_RESYNCED)
1283   /* Indicate trace overflows.  */
1284   if (insn.resynced)
1285     {
1286       struct btrace_function *bfun;
1287       uint64_t offset;
1288 
1289       bfun = ftrace_new_gap (btinfo, BDE_PT_OVERFLOW, gaps);
1290 
1291       pt_insn_get_offset (decoder, &offset);
1292 
1293       warning (_("Overflow at instruction %u (offset = 0x%" PRIx64 ", pc = 0x%"
1294 		 PRIx64 ")."), bfun->insn_offset - 1, offset, insn.ip);
1295     }
1296 #endif /* defined (HAVE_STRUCT_PT_INSN_RESYNCED) */
1297 }
1298 
1299 /* Add function branch trace to BTINFO using DECODER.  */
1300 
1301 static void
1302 ftrace_add_pt (struct btrace_thread_info *btinfo,
1303 	       struct pt_insn_decoder *decoder,
1304 	       int *plevel,
1305 	       std::vector<unsigned int> &gaps)
1306 {
1307   struct btrace_function *bfun;
1308   uint64_t offset;
1309   int status;
1310 
1311   for (;;)
1312     {
1313       struct pt_insn insn;
1314 
1315       status = pt_insn_sync_forward (decoder);
1316       if (status < 0)
1317 	{
1318 	  if (status != -pte_eos)
1319 	    warning (_("Failed to synchronize onto the Intel Processor "
1320 		       "Trace stream: %s."), pt_errstr (pt_errcode (status)));
1321 	  break;
1322 	}
1323 
1324       for (;;)
1325 	{
1326 	  /* Handle events from the previous iteration or synchronization.  */
1327 	  status = handle_pt_insn_events (btinfo, decoder, gaps, status);
1328 	  if (status < 0)
1329 	    break;
1330 
1331 	  status = pt_insn_next (decoder, &insn, sizeof(insn));
1332 	  if (status < 0)
1333 	    break;
1334 
1335 	  /* Handle events indicated by flags in INSN.  */
1336 	  handle_pt_insn_event_flags (btinfo, decoder, insn, gaps);
1337 
1338 	  bfun = ftrace_update_function (btinfo, insn.ip);
1339 
1340 	  /* Maintain the function level offset.  */
1341 	  *plevel = std::min (*plevel, bfun->level);
1342 
1343 	  ftrace_update_insns (bfun, pt_btrace_insn (insn));
1344 	}
1345 
1346       if (status == -pte_eos)
1347 	break;
1348 
1349       /* Indicate the gap in the trace.  */
1350       bfun = ftrace_new_gap (btinfo, status, gaps);
1351 
1352       pt_insn_get_offset (decoder, &offset);
1353 
1354       warning (_("Decode error (%d) at instruction %u (offset = 0x%" PRIx64
1355 		 ", pc = 0x%" PRIx64 "): %s."), status, bfun->insn_offset - 1,
1356 	       offset, insn.ip, pt_errstr (pt_errcode (status)));
1357     }
1358 }
1359 
1360 /* A callback function to allow the trace decoder to read the inferior's
1361    memory.  */
1362 
1363 static int
1364 btrace_pt_readmem_callback (gdb_byte *buffer, size_t size,
1365 			    const struct pt_asid *asid, uint64_t pc,
1366 			    void *context)
1367 {
1368   int result, errcode;
1369 
1370   result = (int) size;
1371   try
1372     {
1373       errcode = target_read_code ((CORE_ADDR) pc, buffer, size);
1374       if (errcode != 0)
1375 	result = -pte_nomap;
1376     }
1377   catch (const gdb_exception_error &error)
1378     {
1379       result = -pte_nomap;
1380     }
1381 
1382   return result;
1383 }
1384 
1385 /* Translate the vendor from one enum to another.  */
1386 
1387 static enum pt_cpu_vendor
1388 pt_translate_cpu_vendor (enum btrace_cpu_vendor vendor)
1389 {
1390   switch (vendor)
1391     {
1392     default:
1393       return pcv_unknown;
1394 
1395     case CV_INTEL:
1396       return pcv_intel;
1397     }
1398 }
1399 
1400 /* Finalize the function branch trace after decode.  */
1401 
1402 static void btrace_finalize_ftrace_pt (struct pt_insn_decoder *decoder,
1403 				       struct thread_info *tp, int level)
1404 {
1405   pt_insn_free_decoder (decoder);
1406 
1407   /* LEVEL is the minimal function level of all btrace function segments.
1408      Define the global level offset to -LEVEL so all function levels are
1409      normalized to start at zero.  */
1410   tp->btrace.level = -level;
1411 
1412   /* Add a single last instruction entry for the current PC.
1413      This allows us to compute the backtrace at the current PC using both
1414      standard unwind and btrace unwind.
1415      This extra entry is ignored by all record commands.  */
1416   btrace_add_pc (tp);
1417 }
1418 
1419 /* Compute the function branch trace from Intel Processor Trace
1420    format.  */
1421 
1422 static void
1423 btrace_compute_ftrace_pt (struct thread_info *tp,
1424 			  const struct btrace_data_pt *btrace,
1425 			  std::vector<unsigned int> &gaps)
1426 {
1427   struct btrace_thread_info *btinfo;
1428   struct pt_insn_decoder *decoder;
1429   struct pt_config config;
1430   int level, errcode;
1431 
1432   if (btrace->size == 0)
1433     return;
1434 
1435   btinfo = &tp->btrace;
1436   if (btinfo->functions.empty ())
1437     level = INT_MAX;
1438   else
1439     level = -btinfo->level;
1440 
1441   pt_config_init(&config);
1442   config.begin = btrace->data;
1443   config.end = btrace->data + btrace->size;
1444 
1445   /* We treat an unknown vendor as 'no errata'.  */
1446   if (btrace->config.cpu.vendor != CV_UNKNOWN)
1447     {
1448       config.cpu.vendor
1449 	= pt_translate_cpu_vendor (btrace->config.cpu.vendor);
1450       config.cpu.family = btrace->config.cpu.family;
1451       config.cpu.model = btrace->config.cpu.model;
1452       config.cpu.stepping = btrace->config.cpu.stepping;
1453 
1454       errcode = pt_cpu_errata (&config.errata, &config.cpu);
1455       if (errcode < 0)
1456 	error (_("Failed to configure the Intel Processor Trace "
1457 		 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
1458     }
1459 
1460   decoder = pt_insn_alloc_decoder (&config);
1461   if (decoder == NULL)
1462     error (_("Failed to allocate the Intel Processor Trace decoder."));
1463 
1464   try
1465     {
1466       struct pt_image *image;
1467 
1468       image = pt_insn_get_image(decoder);
1469       if (image == NULL)
1470 	error (_("Failed to configure the Intel Processor Trace decoder."));
1471 
1472       errcode = pt_image_set_callback(image, btrace_pt_readmem_callback, NULL);
1473       if (errcode < 0)
1474 	error (_("Failed to configure the Intel Processor Trace decoder: "
1475 		 "%s."), pt_errstr (pt_errcode (errcode)));
1476 
1477       ftrace_add_pt (btinfo, decoder, &level, gaps);
1478     }
1479   catch (const gdb_exception &error)
1480     {
1481       /* Indicate a gap in the trace if we quit trace processing.  */
1482       if (error.reason == RETURN_QUIT && !btinfo->functions.empty ())
1483 	ftrace_new_gap (btinfo, BDE_PT_USER_QUIT, gaps);
1484 
1485       btrace_finalize_ftrace_pt (decoder, tp, level);
1486 
1487       throw;
1488     }
1489 
1490   btrace_finalize_ftrace_pt (decoder, tp, level);
1491 }
1492 
1493 #else /* defined (HAVE_LIBIPT)  */
1494 
1495 static void
1496 btrace_compute_ftrace_pt (struct thread_info *tp,
1497 			  const struct btrace_data_pt *btrace,
1498 			  std::vector<unsigned int> &gaps)
1499 {
1500   internal_error (__FILE__, __LINE__, _("Unexpected branch trace format."));
1501 }
1502 
1503 #endif /* defined (HAVE_LIBIPT)  */
1504 
1505 /* Compute the function branch trace from a block branch trace BTRACE for
1506    a thread given by BTINFO.  If CPU is not NULL, overwrite the cpu in the
1507    branch trace configuration.  This is currently only used for the PT
1508    format.  */
1509 
1510 static void
1511 btrace_compute_ftrace_1 (struct thread_info *tp,
1512 			 struct btrace_data *btrace,
1513 			 const struct btrace_cpu *cpu,
1514 			 std::vector<unsigned int> &gaps)
1515 {
1516   DEBUG ("compute ftrace");
1517 
1518   switch (btrace->format)
1519     {
1520     case BTRACE_FORMAT_NONE:
1521       return;
1522 
1523     case BTRACE_FORMAT_BTS:
1524       btrace_compute_ftrace_bts (tp, &btrace->variant.bts, gaps);
1525       return;
1526 
1527     case BTRACE_FORMAT_PT:
1528       /* Overwrite the cpu we use for enabling errata workarounds.  */
1529       if (cpu != nullptr)
1530 	btrace->variant.pt.config.cpu = *cpu;
1531 
1532       btrace_compute_ftrace_pt (tp, &btrace->variant.pt, gaps);
1533       return;
1534     }
1535 
1536   internal_error (__FILE__, __LINE__, _("Unknown branch trace format."));
1537 }
1538 
1539 static void
1540 btrace_finalize_ftrace (struct thread_info *tp, std::vector<unsigned int> &gaps)
1541 {
1542   if (!gaps.empty ())
1543     {
1544       tp->btrace.ngaps += gaps.size ();
1545       btrace_bridge_gaps (tp, gaps);
1546     }
1547 }
1548 
1549 static void
1550 btrace_compute_ftrace (struct thread_info *tp, struct btrace_data *btrace,
1551 		       const struct btrace_cpu *cpu)
1552 {
1553   std::vector<unsigned int> gaps;
1554 
1555   try
1556     {
1557       btrace_compute_ftrace_1 (tp, btrace, cpu, gaps);
1558     }
1559   catch (const gdb_exception &error)
1560     {
1561       btrace_finalize_ftrace (tp, gaps);
1562 
1563       throw;
1564     }
1565 
1566   btrace_finalize_ftrace (tp, gaps);
1567 }
1568 
1569 /* Add an entry for the current PC.  */
1570 
1571 static void
1572 btrace_add_pc (struct thread_info *tp)
1573 {
1574   struct btrace_data btrace;
1575   struct regcache *regcache;
1576   CORE_ADDR pc;
1577 
1578   regcache = get_thread_regcache (tp);
1579   pc = regcache_read_pc (regcache);
1580 
1581   btrace.format = BTRACE_FORMAT_BTS;
1582   btrace.variant.bts.blocks = new std::vector<btrace_block>;
1583 
1584   btrace.variant.bts.blocks->emplace_back (pc, pc);
1585 
1586   btrace_compute_ftrace (tp, &btrace, NULL);
1587 }
1588 
1589 /* See btrace.h.  */
1590 
1591 void
1592 btrace_enable (struct thread_info *tp, const struct btrace_config *conf)
1593 {
1594   if (tp->btrace.target != NULL)
1595     error (_("Recording already enabled on thread %s (%s)."),
1596 	   print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1597 
1598 #if !defined (HAVE_LIBIPT)
1599   if (conf->format == BTRACE_FORMAT_PT)
1600     error (_("Intel Processor Trace support was disabled at compile time."));
1601 #endif /* !defined (HAVE_LIBIPT) */
1602 
1603   DEBUG ("enable thread %s (%s)", print_thread_id (tp),
1604 	 target_pid_to_str (tp->ptid).c_str ());
1605 
1606   tp->btrace.target = target_enable_btrace (tp->ptid, conf);
1607 
1608   if (tp->btrace.target == NULL)
1609     error (_("Failed to enable recording on thread %s (%s)."),
1610 	   print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1611 
1612   /* We need to undo the enable in case of errors.  */
1613   try
1614     {
1615       /* Add an entry for the current PC so we start tracing from where we
1616 	 enabled it.
1617 
1618 	 If we can't access TP's registers, TP is most likely running.  In this
1619 	 case, we can't really say where tracing was enabled so it should be
1620 	 safe to simply skip this step.
1621 
1622 	 This is not relevant for BTRACE_FORMAT_PT since the trace will already
1623 	 start at the PC at which tracing was enabled.  */
1624       if (conf->format != BTRACE_FORMAT_PT
1625 	  && can_access_registers_thread (tp))
1626 	btrace_add_pc (tp);
1627     }
1628   catch (const gdb_exception &exception)
1629     {
1630       btrace_disable (tp);
1631 
1632       throw;
1633     }
1634 }
1635 
1636 /* See btrace.h.  */
1637 
1638 const struct btrace_config *
1639 btrace_conf (const struct btrace_thread_info *btinfo)
1640 {
1641   if (btinfo->target == NULL)
1642     return NULL;
1643 
1644   return target_btrace_conf (btinfo->target);
1645 }
1646 
1647 /* See btrace.h.  */
1648 
1649 void
1650 btrace_disable (struct thread_info *tp)
1651 {
1652   struct btrace_thread_info *btp = &tp->btrace;
1653 
1654   if (btp->target == NULL)
1655     error (_("Recording not enabled on thread %s (%s)."),
1656 	   print_thread_id (tp), target_pid_to_str (tp->ptid).c_str ());
1657 
1658   DEBUG ("disable thread %s (%s)", print_thread_id (tp),
1659 	 target_pid_to_str (tp->ptid).c_str ());
1660 
1661   target_disable_btrace (btp->target);
1662   btp->target = NULL;
1663 
1664   btrace_clear (tp);
1665 }
1666 
1667 /* See btrace.h.  */
1668 
1669 void
1670 btrace_teardown (struct thread_info *tp)
1671 {
1672   struct btrace_thread_info *btp = &tp->btrace;
1673 
1674   if (btp->target == NULL)
1675     return;
1676 
1677   DEBUG ("teardown thread %s (%s)", print_thread_id (tp),
1678 	 target_pid_to_str (tp->ptid).c_str ());
1679 
1680   target_teardown_btrace (btp->target);
1681   btp->target = NULL;
1682 
1683   btrace_clear (tp);
1684 }
1685 
1686 /* Stitch branch trace in BTS format.  */
1687 
1688 static int
1689 btrace_stitch_bts (struct btrace_data_bts *btrace, struct thread_info *tp)
1690 {
1691   struct btrace_thread_info *btinfo;
1692   struct btrace_function *last_bfun;
1693   btrace_block *first_new_block;
1694 
1695   btinfo = &tp->btrace;
1696   gdb_assert (!btinfo->functions.empty ());
1697   gdb_assert (!btrace->blocks->empty ());
1698 
1699   last_bfun = &btinfo->functions.back ();
1700 
1701   /* If the existing trace ends with a gap, we just glue the traces
1702      together.  We need to drop the last (i.e. chronologically first) block
1703      of the new trace,  though, since we can't fill in the start address.*/
1704   if (last_bfun->insn.empty ())
1705     {
1706       btrace->blocks->pop_back ();
1707       return 0;
1708     }
1709 
1710   /* Beware that block trace starts with the most recent block, so the
1711      chronologically first block in the new trace is the last block in
1712      the new trace's block vector.  */
1713   first_new_block = &btrace->blocks->back ();
1714   const btrace_insn &last_insn = last_bfun->insn.back ();
1715 
1716   /* If the current PC at the end of the block is the same as in our current
1717      trace, there are two explanations:
1718        1. we executed the instruction and some branch brought us back.
1719        2. we have not made any progress.
1720      In the first case, the delta trace vector should contain at least two
1721      entries.
1722      In the second case, the delta trace vector should contain exactly one
1723      entry for the partial block containing the current PC.  Remove it.  */
1724   if (first_new_block->end == last_insn.pc && btrace->blocks->size () == 1)
1725     {
1726       btrace->blocks->pop_back ();
1727       return 0;
1728     }
1729 
1730   DEBUG ("stitching %s to %s", ftrace_print_insn_addr (&last_insn),
1731 	 core_addr_to_string_nz (first_new_block->end));
1732 
1733   /* Do a simple sanity check to make sure we don't accidentally end up
1734      with a bad block.  This should not occur in practice.  */
1735   if (first_new_block->end < last_insn.pc)
1736     {
1737       warning (_("Error while trying to read delta trace.  Falling back to "
1738 		 "a full read."));
1739       return -1;
1740     }
1741 
1742   /* We adjust the last block to start at the end of our current trace.  */
1743   gdb_assert (first_new_block->begin == 0);
1744   first_new_block->begin = last_insn.pc;
1745 
1746   /* We simply pop the last insn so we can insert it again as part of
1747      the normal branch trace computation.
1748      Since instruction iterators are based on indices in the instructions
1749      vector, we don't leave any pointers dangling.  */
1750   DEBUG ("pruning insn at %s for stitching",
1751 	 ftrace_print_insn_addr (&last_insn));
1752 
1753   last_bfun->insn.pop_back ();
1754 
1755   /* The instructions vector may become empty temporarily if this has
1756      been the only instruction in this function segment.
1757      This violates the invariant but will be remedied shortly by
1758      btrace_compute_ftrace when we add the new trace.  */
1759 
1760   /* The only case where this would hurt is if the entire trace consisted
1761      of just that one instruction.  If we remove it, we might turn the now
1762      empty btrace function segment into a gap.  But we don't want gaps at
1763      the beginning.  To avoid this, we remove the entire old trace.  */
1764   if (last_bfun->number == 1 && last_bfun->insn.empty ())
1765     btrace_clear (tp);
1766 
1767   return 0;
1768 }
1769 
1770 /* Adjust the block trace in order to stitch old and new trace together.
1771    BTRACE is the new delta trace between the last and the current stop.
1772    TP is the traced thread.
1773    May modifx BTRACE as well as the existing trace in TP.
1774    Return 0 on success, -1 otherwise.  */
1775 
1776 static int
1777 btrace_stitch_trace (struct btrace_data *btrace, struct thread_info *tp)
1778 {
1779   /* If we don't have trace, there's nothing to do.  */
1780   if (btrace->empty ())
1781     return 0;
1782 
1783   switch (btrace->format)
1784     {
1785     case BTRACE_FORMAT_NONE:
1786       return 0;
1787 
1788     case BTRACE_FORMAT_BTS:
1789       return btrace_stitch_bts (&btrace->variant.bts, tp);
1790 
1791     case BTRACE_FORMAT_PT:
1792       /* Delta reads are not supported.  */
1793       return -1;
1794     }
1795 
1796   internal_error (__FILE__, __LINE__, _("Unknown branch trace format."));
1797 }
1798 
1799 /* Clear the branch trace histories in BTINFO.  */
1800 
1801 static void
1802 btrace_clear_history (struct btrace_thread_info *btinfo)
1803 {
1804   xfree (btinfo->insn_history);
1805   xfree (btinfo->call_history);
1806   xfree (btinfo->replay);
1807 
1808   btinfo->insn_history = NULL;
1809   btinfo->call_history = NULL;
1810   btinfo->replay = NULL;
1811 }
1812 
1813 /* Clear the branch trace maintenance histories in BTINFO.  */
1814 
1815 static void
1816 btrace_maint_clear (struct btrace_thread_info *btinfo)
1817 {
1818   switch (btinfo->data.format)
1819     {
1820     default:
1821       break;
1822 
1823     case BTRACE_FORMAT_BTS:
1824       btinfo->maint.variant.bts.packet_history.begin = 0;
1825       btinfo->maint.variant.bts.packet_history.end = 0;
1826       break;
1827 
1828 #if defined (HAVE_LIBIPT)
1829     case BTRACE_FORMAT_PT:
1830       delete btinfo->maint.variant.pt.packets;
1831 
1832       btinfo->maint.variant.pt.packets = NULL;
1833       btinfo->maint.variant.pt.packet_history.begin = 0;
1834       btinfo->maint.variant.pt.packet_history.end = 0;
1835       break;
1836 #endif /* defined (HAVE_LIBIPT)  */
1837     }
1838 }
1839 
1840 /* See btrace.h.  */
1841 
1842 const char *
1843 btrace_decode_error (enum btrace_format format, int errcode)
1844 {
1845   switch (format)
1846     {
1847     case BTRACE_FORMAT_BTS:
1848       switch (errcode)
1849 	{
1850 	case BDE_BTS_OVERFLOW:
1851 	  return _("instruction overflow");
1852 
1853 	case BDE_BTS_INSN_SIZE:
1854 	  return _("unknown instruction");
1855 
1856 	default:
1857 	  break;
1858 	}
1859       break;
1860 
1861 #if defined (HAVE_LIBIPT)
1862     case BTRACE_FORMAT_PT:
1863       switch (errcode)
1864 	{
1865 	case BDE_PT_USER_QUIT:
1866 	  return _("trace decode cancelled");
1867 
1868 	case BDE_PT_DISABLED:
1869 	  return _("disabled");
1870 
1871 	case BDE_PT_OVERFLOW:
1872 	  return _("overflow");
1873 
1874 	default:
1875 	  if (errcode < 0)
1876 	    return pt_errstr (pt_errcode (errcode));
1877 	  break;
1878 	}
1879       break;
1880 #endif /* defined (HAVE_LIBIPT)  */
1881 
1882     default:
1883       break;
1884     }
1885 
1886   return _("unknown");
1887 }
1888 
1889 /* See btrace.h.  */
1890 
1891 void
1892 btrace_fetch (struct thread_info *tp, const struct btrace_cpu *cpu)
1893 {
1894   struct btrace_thread_info *btinfo;
1895   struct btrace_target_info *tinfo;
1896   struct btrace_data btrace;
1897   int errcode;
1898 
1899   DEBUG ("fetch thread %s (%s)", print_thread_id (tp),
1900 	 target_pid_to_str (tp->ptid).c_str ());
1901 
1902   btinfo = &tp->btrace;
1903   tinfo = btinfo->target;
1904   if (tinfo == NULL)
1905     return;
1906 
1907   /* There's no way we could get new trace while replaying.
1908      On the other hand, delta trace would return a partial record with the
1909      current PC, which is the replay PC, not the last PC, as expected.  */
1910   if (btinfo->replay != NULL)
1911     return;
1912 
1913   /* With CLI usage, TP is always the current thread when we get here.
1914      However, since we can also store a gdb.Record object in Python
1915      referring to a different thread than the current one, we need to
1916      temporarily set the current thread.  */
1917   scoped_restore_current_thread restore_thread;
1918   switch_to_thread (tp);
1919 
1920   /* We should not be called on running or exited threads.  */
1921   gdb_assert (can_access_registers_thread (tp));
1922 
1923   /* Let's first try to extend the trace we already have.  */
1924   if (!btinfo->functions.empty ())
1925     {
1926       errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_DELTA);
1927       if (errcode == 0)
1928 	{
1929 	  /* Success.  Let's try to stitch the traces together.  */
1930 	  errcode = btrace_stitch_trace (&btrace, tp);
1931 	}
1932       else
1933 	{
1934 	  /* We failed to read delta trace.  Let's try to read new trace.  */
1935 	  errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_NEW);
1936 
1937 	  /* If we got any new trace, discard what we have.  */
1938 	  if (errcode == 0 && !btrace.empty ())
1939 	    btrace_clear (tp);
1940 	}
1941 
1942       /* If we were not able to read the trace, we start over.  */
1943       if (errcode != 0)
1944 	{
1945 	  btrace_clear (tp);
1946 	  errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1947 	}
1948     }
1949   else
1950     errcode = target_read_btrace (&btrace, tinfo, BTRACE_READ_ALL);
1951 
1952   /* If we were not able to read the branch trace, signal an error.  */
1953   if (errcode != 0)
1954     error (_("Failed to read branch trace."));
1955 
1956   /* Compute the trace, provided we have any.  */
1957   if (!btrace.empty ())
1958     {
1959       /* Store the raw trace data.  The stored data will be cleared in
1960 	 btrace_clear, so we always append the new trace.  */
1961       btrace_data_append (&btinfo->data, &btrace);
1962       btrace_maint_clear (btinfo);
1963 
1964       btrace_clear_history (btinfo);
1965       btrace_compute_ftrace (tp, &btrace, cpu);
1966     }
1967 }
1968 
1969 /* See btrace.h.  */
1970 
1971 void
1972 btrace_clear (struct thread_info *tp)
1973 {
1974   struct btrace_thread_info *btinfo;
1975 
1976   DEBUG ("clear thread %s (%s)", print_thread_id (tp),
1977 	 target_pid_to_str (tp->ptid).c_str ());
1978 
1979   /* Make sure btrace frames that may hold a pointer into the branch
1980      trace data are destroyed.  */
1981   reinit_frame_cache ();
1982 
1983   btinfo = &tp->btrace;
1984 
1985   btinfo->functions.clear ();
1986   btinfo->ngaps = 0;
1987 
1988   /* Must clear the maint data before - it depends on BTINFO->DATA.  */
1989   btrace_maint_clear (btinfo);
1990   btinfo->data.clear ();
1991   btrace_clear_history (btinfo);
1992 }
1993 
1994 /* See btrace.h.  */
1995 
1996 void
1997 btrace_free_objfile (struct objfile *objfile)
1998 {
1999   DEBUG ("free objfile");
2000 
2001   for (thread_info *tp : all_non_exited_threads ())
2002     btrace_clear (tp);
2003 }
2004 
2005 #if defined (HAVE_LIBEXPAT)
2006 
2007 /* Check the btrace document version.  */
2008 
2009 static void
2010 check_xml_btrace_version (struct gdb_xml_parser *parser,
2011 			  const struct gdb_xml_element *element,
2012 			  void *user_data,
2013 			  std::vector<gdb_xml_value> &attributes)
2014 {
2015   const char *version
2016     = (const char *) xml_find_attribute (attributes, "version")->value.get ();
2017 
2018   if (strcmp (version, "1.0") != 0)
2019     gdb_xml_error (parser, _("Unsupported btrace version: \"%s\""), version);
2020 }
2021 
2022 /* Parse a btrace "block" xml record.  */
2023 
2024 static void
2025 parse_xml_btrace_block (struct gdb_xml_parser *parser,
2026 			const struct gdb_xml_element *element,
2027 			void *user_data,
2028 			std::vector<gdb_xml_value> &attributes)
2029 {
2030   struct btrace_data *btrace;
2031   ULONGEST *begin, *end;
2032 
2033   btrace = (struct btrace_data *) user_data;
2034 
2035   switch (btrace->format)
2036     {
2037     case BTRACE_FORMAT_BTS:
2038       break;
2039 
2040     case BTRACE_FORMAT_NONE:
2041       btrace->format = BTRACE_FORMAT_BTS;
2042       btrace->variant.bts.blocks = new std::vector<btrace_block>;
2043       break;
2044 
2045     default:
2046       gdb_xml_error (parser, _("Btrace format error."));
2047     }
2048 
2049   begin = (ULONGEST *) xml_find_attribute (attributes, "begin")->value.get ();
2050   end = (ULONGEST *) xml_find_attribute (attributes, "end")->value.get ();
2051   btrace->variant.bts.blocks->emplace_back (*begin, *end);
2052 }
2053 
2054 /* Parse a "raw" xml record.  */
2055 
2056 static void
2057 parse_xml_raw (struct gdb_xml_parser *parser, const char *body_text,
2058 	       gdb_byte **pdata, size_t *psize)
2059 {
2060   gdb_byte *bin;
2061   size_t len, size;
2062 
2063   len = strlen (body_text);
2064   if (len % 2 != 0)
2065     gdb_xml_error (parser, _("Bad raw data size."));
2066 
2067   size = len / 2;
2068 
2069   gdb::unique_xmalloc_ptr<gdb_byte> data ((gdb_byte *) xmalloc (size));
2070   bin = data.get ();
2071 
2072   /* We use hex encoding - see gdbsupport/rsp-low.h.  */
2073   while (len > 0)
2074     {
2075       char hi, lo;
2076 
2077       hi = *body_text++;
2078       lo = *body_text++;
2079 
2080       if (hi == 0 || lo == 0)
2081 	gdb_xml_error (parser, _("Bad hex encoding."));
2082 
2083       *bin++ = fromhex (hi) * 16 + fromhex (lo);
2084       len -= 2;
2085     }
2086 
2087   *pdata = data.release ();
2088   *psize = size;
2089 }
2090 
2091 /* Parse a btrace pt-config "cpu" xml record.  */
2092 
2093 static void
2094 parse_xml_btrace_pt_config_cpu (struct gdb_xml_parser *parser,
2095 				const struct gdb_xml_element *element,
2096 				void *user_data,
2097 				std::vector<gdb_xml_value> &attributes)
2098 {
2099   struct btrace_data *btrace;
2100   const char *vendor;
2101   ULONGEST *family, *model, *stepping;
2102 
2103   vendor =
2104     (const char *) xml_find_attribute (attributes, "vendor")->value.get ();
2105   family
2106     = (ULONGEST *) xml_find_attribute (attributes, "family")->value.get ();
2107   model
2108     = (ULONGEST *) xml_find_attribute (attributes, "model")->value.get ();
2109   stepping
2110     = (ULONGEST *) xml_find_attribute (attributes, "stepping")->value.get ();
2111 
2112   btrace = (struct btrace_data *) user_data;
2113 
2114   if (strcmp (vendor, "GenuineIntel") == 0)
2115     btrace->variant.pt.config.cpu.vendor = CV_INTEL;
2116 
2117   btrace->variant.pt.config.cpu.family = *family;
2118   btrace->variant.pt.config.cpu.model = *model;
2119   btrace->variant.pt.config.cpu.stepping = *stepping;
2120 }
2121 
2122 /* Parse a btrace pt "raw" xml record.  */
2123 
2124 static void
2125 parse_xml_btrace_pt_raw (struct gdb_xml_parser *parser,
2126 			 const struct gdb_xml_element *element,
2127 			 void *user_data, const char *body_text)
2128 {
2129   struct btrace_data *btrace;
2130 
2131   btrace = (struct btrace_data *) user_data;
2132   parse_xml_raw (parser, body_text, &btrace->variant.pt.data,
2133 		 &btrace->variant.pt.size);
2134 }
2135 
2136 /* Parse a btrace "pt" xml record.  */
2137 
2138 static void
2139 parse_xml_btrace_pt (struct gdb_xml_parser *parser,
2140 		     const struct gdb_xml_element *element,
2141 		     void *user_data,
2142 		     std::vector<gdb_xml_value> &attributes)
2143 {
2144   struct btrace_data *btrace;
2145 
2146   btrace = (struct btrace_data *) user_data;
2147   btrace->format = BTRACE_FORMAT_PT;
2148   btrace->variant.pt.config.cpu.vendor = CV_UNKNOWN;
2149   btrace->variant.pt.data = NULL;
2150   btrace->variant.pt.size = 0;
2151 }
2152 
2153 static const struct gdb_xml_attribute block_attributes[] = {
2154   { "begin", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2155   { "end", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2156   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2157 };
2158 
2159 static const struct gdb_xml_attribute btrace_pt_config_cpu_attributes[] = {
2160   { "vendor", GDB_XML_AF_NONE, NULL, NULL },
2161   { "family", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2162   { "model", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2163   { "stepping", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
2164   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2165 };
2166 
2167 static const struct gdb_xml_element btrace_pt_config_children[] = {
2168   { "cpu", btrace_pt_config_cpu_attributes, NULL, GDB_XML_EF_OPTIONAL,
2169     parse_xml_btrace_pt_config_cpu, NULL },
2170   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2171 };
2172 
2173 static const struct gdb_xml_element btrace_pt_children[] = {
2174   { "pt-config", NULL, btrace_pt_config_children, GDB_XML_EF_OPTIONAL, NULL,
2175     NULL },
2176   { "raw", NULL, NULL, GDB_XML_EF_OPTIONAL, NULL, parse_xml_btrace_pt_raw },
2177   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2178 };
2179 
2180 static const struct gdb_xml_attribute btrace_attributes[] = {
2181   { "version", GDB_XML_AF_NONE, NULL, NULL },
2182   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2183 };
2184 
2185 static const struct gdb_xml_element btrace_children[] = {
2186   { "block", block_attributes, NULL,
2187     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL, parse_xml_btrace_block, NULL },
2188   { "pt", NULL, btrace_pt_children, GDB_XML_EF_OPTIONAL, parse_xml_btrace_pt,
2189     NULL },
2190   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2191 };
2192 
2193 static const struct gdb_xml_element btrace_elements[] = {
2194   { "btrace", btrace_attributes, btrace_children, GDB_XML_EF_NONE,
2195     check_xml_btrace_version, NULL },
2196   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2197 };
2198 
2199 #endif /* defined (HAVE_LIBEXPAT) */
2200 
2201 /* See btrace.h.  */
2202 
2203 void
2204 parse_xml_btrace (struct btrace_data *btrace, const char *buffer)
2205 {
2206 #if defined (HAVE_LIBEXPAT)
2207 
2208   int errcode;
2209   btrace_data result;
2210   result.format = BTRACE_FORMAT_NONE;
2211 
2212   errcode = gdb_xml_parse_quick (_("btrace"), "btrace.dtd", btrace_elements,
2213 				 buffer, &result);
2214   if (errcode != 0)
2215     error (_("Error parsing branch trace."));
2216 
2217   /* Keep parse results.  */
2218   *btrace = std::move (result);
2219 
2220 #else  /* !defined (HAVE_LIBEXPAT) */
2221 
2222   error (_("Cannot process branch trace.  XML support was disabled at "
2223 	   "compile time."));
2224 
2225 #endif  /* !defined (HAVE_LIBEXPAT) */
2226 }
2227 
2228 #if defined (HAVE_LIBEXPAT)
2229 
2230 /* Parse a btrace-conf "bts" xml record.  */
2231 
2232 static void
2233 parse_xml_btrace_conf_bts (struct gdb_xml_parser *parser,
2234 			  const struct gdb_xml_element *element,
2235 			  void *user_data,
2236 			  std::vector<gdb_xml_value> &attributes)
2237 {
2238   struct btrace_config *conf;
2239   struct gdb_xml_value *size;
2240 
2241   conf = (struct btrace_config *) user_data;
2242   conf->format = BTRACE_FORMAT_BTS;
2243   conf->bts.size = 0;
2244 
2245   size = xml_find_attribute (attributes, "size");
2246   if (size != NULL)
2247     conf->bts.size = (unsigned int) *(ULONGEST *) size->value.get ();
2248 }
2249 
2250 /* Parse a btrace-conf "pt" xml record.  */
2251 
2252 static void
2253 parse_xml_btrace_conf_pt (struct gdb_xml_parser *parser,
2254 			  const struct gdb_xml_element *element,
2255 			  void *user_data,
2256 			  std::vector<gdb_xml_value> &attributes)
2257 {
2258   struct btrace_config *conf;
2259   struct gdb_xml_value *size;
2260 
2261   conf = (struct btrace_config *) user_data;
2262   conf->format = BTRACE_FORMAT_PT;
2263   conf->pt.size = 0;
2264 
2265   size = xml_find_attribute (attributes, "size");
2266   if (size != NULL)
2267     conf->pt.size = (unsigned int) *(ULONGEST *) size->value.get ();
2268 }
2269 
2270 static const struct gdb_xml_attribute btrace_conf_pt_attributes[] = {
2271   { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2272   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2273 };
2274 
2275 static const struct gdb_xml_attribute btrace_conf_bts_attributes[] = {
2276   { "size", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2277   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2278 };
2279 
2280 static const struct gdb_xml_element btrace_conf_children[] = {
2281   { "bts", btrace_conf_bts_attributes, NULL, GDB_XML_EF_OPTIONAL,
2282     parse_xml_btrace_conf_bts, NULL },
2283   { "pt", btrace_conf_pt_attributes, NULL, GDB_XML_EF_OPTIONAL,
2284     parse_xml_btrace_conf_pt, NULL },
2285   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2286 };
2287 
2288 static const struct gdb_xml_attribute btrace_conf_attributes[] = {
2289   { "version", GDB_XML_AF_NONE, NULL, NULL },
2290   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2291 };
2292 
2293 static const struct gdb_xml_element btrace_conf_elements[] = {
2294   { "btrace-conf", btrace_conf_attributes, btrace_conf_children,
2295     GDB_XML_EF_NONE, NULL, NULL },
2296   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2297 };
2298 
2299 #endif /* defined (HAVE_LIBEXPAT) */
2300 
2301 /* See btrace.h.  */
2302 
2303 void
2304 parse_xml_btrace_conf (struct btrace_config *conf, const char *xml)
2305 {
2306 #if defined (HAVE_LIBEXPAT)
2307 
2308   int errcode;
2309   errcode = gdb_xml_parse_quick (_("btrace-conf"), "btrace-conf.dtd",
2310 				 btrace_conf_elements, xml, conf);
2311   if (errcode != 0)
2312     error (_("Error parsing branch trace configuration."));
2313 
2314 #else  /* !defined (HAVE_LIBEXPAT) */
2315 
2316   error (_("Cannot process the branch trace configuration.  XML support "
2317 	   "was disabled at compile time."));
2318 
2319 #endif  /* !defined (HAVE_LIBEXPAT) */
2320 }
2321 
2322 /* See btrace.h.  */
2323 
2324 const struct btrace_insn *
2325 btrace_insn_get (const struct btrace_insn_iterator *it)
2326 {
2327   const struct btrace_function *bfun;
2328   unsigned int index, end;
2329 
2330   index = it->insn_index;
2331   bfun = &it->btinfo->functions[it->call_index];
2332 
2333   /* Check if the iterator points to a gap in the trace.  */
2334   if (bfun->errcode != 0)
2335     return NULL;
2336 
2337   /* The index is within the bounds of this function's instruction vector.  */
2338   end = bfun->insn.size ();
2339   gdb_assert (0 < end);
2340   gdb_assert (index < end);
2341 
2342   return &bfun->insn[index];
2343 }
2344 
2345 /* See btrace.h.  */
2346 
2347 int
2348 btrace_insn_get_error (const struct btrace_insn_iterator *it)
2349 {
2350   return it->btinfo->functions[it->call_index].errcode;
2351 }
2352 
2353 /* See btrace.h.  */
2354 
2355 unsigned int
2356 btrace_insn_number (const struct btrace_insn_iterator *it)
2357 {
2358   return it->btinfo->functions[it->call_index].insn_offset + it->insn_index;
2359 }
2360 
2361 /* See btrace.h.  */
2362 
2363 void
2364 btrace_insn_begin (struct btrace_insn_iterator *it,
2365 		   const struct btrace_thread_info *btinfo)
2366 {
2367   if (btinfo->functions.empty ())
2368     error (_("No trace."));
2369 
2370   it->btinfo = btinfo;
2371   it->call_index = 0;
2372   it->insn_index = 0;
2373 }
2374 
2375 /* See btrace.h.  */
2376 
2377 void
2378 btrace_insn_end (struct btrace_insn_iterator *it,
2379 		 const struct btrace_thread_info *btinfo)
2380 {
2381   const struct btrace_function *bfun;
2382   unsigned int length;
2383 
2384   if (btinfo->functions.empty ())
2385     error (_("No trace."));
2386 
2387   bfun = &btinfo->functions.back ();
2388   length = bfun->insn.size ();
2389 
2390   /* The last function may either be a gap or it contains the current
2391      instruction, which is one past the end of the execution trace; ignore
2392      it.  */
2393   if (length > 0)
2394     length -= 1;
2395 
2396   it->btinfo = btinfo;
2397   it->call_index = bfun->number - 1;
2398   it->insn_index = length;
2399 }
2400 
2401 /* See btrace.h.  */
2402 
2403 unsigned int
2404 btrace_insn_next (struct btrace_insn_iterator *it, unsigned int stride)
2405 {
2406   const struct btrace_function *bfun;
2407   unsigned int index, steps;
2408 
2409   bfun = &it->btinfo->functions[it->call_index];
2410   steps = 0;
2411   index = it->insn_index;
2412 
2413   while (stride != 0)
2414     {
2415       unsigned int end, space, adv;
2416 
2417       end = bfun->insn.size ();
2418 
2419       /* An empty function segment represents a gap in the trace.  We count
2420 	 it as one instruction.  */
2421       if (end == 0)
2422 	{
2423 	  const struct btrace_function *next;
2424 
2425 	  next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2426 	  if (next == NULL)
2427 	    break;
2428 
2429 	  stride -= 1;
2430 	  steps += 1;
2431 
2432 	  bfun = next;
2433 	  index = 0;
2434 
2435 	  continue;
2436 	}
2437 
2438       gdb_assert (0 < end);
2439       gdb_assert (index < end);
2440 
2441       /* Compute the number of instructions remaining in this segment.  */
2442       space = end - index;
2443 
2444       /* Advance the iterator as far as possible within this segment.  */
2445       adv = std::min (space, stride);
2446       stride -= adv;
2447       index += adv;
2448       steps += adv;
2449 
2450       /* Move to the next function if we're at the end of this one.  */
2451       if (index == end)
2452 	{
2453 	  const struct btrace_function *next;
2454 
2455 	  next = ftrace_find_call_by_number (it->btinfo, bfun->number + 1);
2456 	  if (next == NULL)
2457 	    {
2458 	      /* We stepped past the last function.
2459 
2460 		 Let's adjust the index to point to the last instruction in
2461 		 the previous function.  */
2462 	      index -= 1;
2463 	      steps -= 1;
2464 	      break;
2465 	    }
2466 
2467 	  /* We now point to the first instruction in the new function.  */
2468 	  bfun = next;
2469 	  index = 0;
2470 	}
2471 
2472       /* We did make progress.  */
2473       gdb_assert (adv > 0);
2474     }
2475 
2476   /* Update the iterator.  */
2477   it->call_index = bfun->number - 1;
2478   it->insn_index = index;
2479 
2480   return steps;
2481 }
2482 
2483 /* See btrace.h.  */
2484 
2485 unsigned int
2486 btrace_insn_prev (struct btrace_insn_iterator *it, unsigned int stride)
2487 {
2488   const struct btrace_function *bfun;
2489   unsigned int index, steps;
2490 
2491   bfun = &it->btinfo->functions[it->call_index];
2492   steps = 0;
2493   index = it->insn_index;
2494 
2495   while (stride != 0)
2496     {
2497       unsigned int adv;
2498 
2499       /* Move to the previous function if we're at the start of this one.  */
2500       if (index == 0)
2501 	{
2502 	  const struct btrace_function *prev;
2503 
2504 	  prev = ftrace_find_call_by_number (it->btinfo, bfun->number - 1);
2505 	  if (prev == NULL)
2506 	    break;
2507 
2508 	  /* We point to one after the last instruction in the new function.  */
2509 	  bfun = prev;
2510 	  index = bfun->insn.size ();
2511 
2512 	  /* An empty function segment represents a gap in the trace.  We count
2513 	     it as one instruction.  */
2514 	  if (index == 0)
2515 	    {
2516 	      stride -= 1;
2517 	      steps += 1;
2518 
2519 	      continue;
2520 	    }
2521 	}
2522 
2523       /* Advance the iterator as far as possible within this segment.  */
2524       adv = std::min (index, stride);
2525 
2526       stride -= adv;
2527       index -= adv;
2528       steps += adv;
2529 
2530       /* We did make progress.  */
2531       gdb_assert (adv > 0);
2532     }
2533 
2534   /* Update the iterator.  */
2535   it->call_index = bfun->number - 1;
2536   it->insn_index = index;
2537 
2538   return steps;
2539 }
2540 
2541 /* See btrace.h.  */
2542 
2543 int
2544 btrace_insn_cmp (const struct btrace_insn_iterator *lhs,
2545 		 const struct btrace_insn_iterator *rhs)
2546 {
2547   gdb_assert (lhs->btinfo == rhs->btinfo);
2548 
2549   if (lhs->call_index != rhs->call_index)
2550     return lhs->call_index - rhs->call_index;
2551 
2552   return lhs->insn_index - rhs->insn_index;
2553 }
2554 
2555 /* See btrace.h.  */
2556 
2557 int
2558 btrace_find_insn_by_number (struct btrace_insn_iterator *it,
2559 			    const struct btrace_thread_info *btinfo,
2560 			    unsigned int number)
2561 {
2562   const struct btrace_function *bfun;
2563   unsigned int upper, lower;
2564 
2565   if (btinfo->functions.empty ())
2566       return 0;
2567 
2568   lower = 0;
2569   bfun = &btinfo->functions[lower];
2570   if (number < bfun->insn_offset)
2571     return 0;
2572 
2573   upper = btinfo->functions.size () - 1;
2574   bfun = &btinfo->functions[upper];
2575   if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2576     return 0;
2577 
2578   /* We assume that there are no holes in the numbering.  */
2579   for (;;)
2580     {
2581       const unsigned int average = lower + (upper - lower) / 2;
2582 
2583       bfun = &btinfo->functions[average];
2584 
2585       if (number < bfun->insn_offset)
2586 	{
2587 	  upper = average - 1;
2588 	  continue;
2589 	}
2590 
2591       if (number >= bfun->insn_offset + ftrace_call_num_insn (bfun))
2592 	{
2593 	  lower = average + 1;
2594 	  continue;
2595 	}
2596 
2597       break;
2598     }
2599 
2600   it->btinfo = btinfo;
2601   it->call_index = bfun->number - 1;
2602   it->insn_index = number - bfun->insn_offset;
2603   return 1;
2604 }
2605 
2606 /* Returns true if the recording ends with a function segment that
2607    contains only a single (i.e. the current) instruction.  */
2608 
2609 static bool
2610 btrace_ends_with_single_insn (const struct btrace_thread_info *btinfo)
2611 {
2612   const btrace_function *bfun;
2613 
2614   if (btinfo->functions.empty ())
2615     return false;
2616 
2617   bfun = &btinfo->functions.back ();
2618   if (bfun->errcode != 0)
2619     return false;
2620 
2621   return ftrace_call_num_insn (bfun) == 1;
2622 }
2623 
2624 /* See btrace.h.  */
2625 
2626 const struct btrace_function *
2627 btrace_call_get (const struct btrace_call_iterator *it)
2628 {
2629   if (it->index >= it->btinfo->functions.size ())
2630     return NULL;
2631 
2632   return &it->btinfo->functions[it->index];
2633 }
2634 
2635 /* See btrace.h.  */
2636 
2637 unsigned int
2638 btrace_call_number (const struct btrace_call_iterator *it)
2639 {
2640   const unsigned int length = it->btinfo->functions.size ();
2641 
2642   /* If the last function segment contains only a single instruction (i.e. the
2643      current instruction), skip it.  */
2644   if ((it->index == length) && btrace_ends_with_single_insn (it->btinfo))
2645     return length;
2646 
2647   return it->index + 1;
2648 }
2649 
2650 /* See btrace.h.  */
2651 
2652 void
2653 btrace_call_begin (struct btrace_call_iterator *it,
2654 		   const struct btrace_thread_info *btinfo)
2655 {
2656   if (btinfo->functions.empty ())
2657     error (_("No trace."));
2658 
2659   it->btinfo = btinfo;
2660   it->index = 0;
2661 }
2662 
2663 /* See btrace.h.  */
2664 
2665 void
2666 btrace_call_end (struct btrace_call_iterator *it,
2667 		 const struct btrace_thread_info *btinfo)
2668 {
2669   if (btinfo->functions.empty ())
2670     error (_("No trace."));
2671 
2672   it->btinfo = btinfo;
2673   it->index = btinfo->functions.size ();
2674 }
2675 
2676 /* See btrace.h.  */
2677 
2678 unsigned int
2679 btrace_call_next (struct btrace_call_iterator *it, unsigned int stride)
2680 {
2681   const unsigned int length = it->btinfo->functions.size ();
2682 
2683   if (it->index + stride < length - 1)
2684     /* Default case: Simply advance the iterator.  */
2685     it->index += stride;
2686   else if (it->index + stride == length - 1)
2687     {
2688       /* We land exactly at the last function segment.  If it contains only one
2689 	 instruction (i.e. the current instruction) it is not actually part of
2690 	 the trace.  */
2691       if (btrace_ends_with_single_insn (it->btinfo))
2692 	it->index = length;
2693       else
2694 	it->index = length - 1;
2695     }
2696   else
2697     {
2698       /* We land past the last function segment and have to adjust the stride.
2699 	 If the last function segment contains only one instruction (i.e. the
2700 	 current instruction) it is not actually part of the trace.  */
2701       if (btrace_ends_with_single_insn (it->btinfo))
2702 	stride = length - it->index - 1;
2703       else
2704 	stride = length - it->index;
2705 
2706       it->index = length;
2707     }
2708 
2709   return stride;
2710 }
2711 
2712 /* See btrace.h.  */
2713 
2714 unsigned int
2715 btrace_call_prev (struct btrace_call_iterator *it, unsigned int stride)
2716 {
2717   const unsigned int length = it->btinfo->functions.size ();
2718   int steps = 0;
2719 
2720   gdb_assert (it->index <= length);
2721 
2722   if (stride == 0 || it->index == 0)
2723     return 0;
2724 
2725   /* If we are at the end, the first step is a special case.  If the last
2726      function segment contains only one instruction (i.e. the current
2727      instruction) it is not actually part of the trace.  To be able to step
2728      over this instruction, we need at least one more function segment.  */
2729   if ((it->index == length)  && (length > 1))
2730     {
2731       if (btrace_ends_with_single_insn (it->btinfo))
2732 	it->index = length - 2;
2733       else
2734 	it->index = length - 1;
2735 
2736       steps = 1;
2737       stride -= 1;
2738     }
2739 
2740   stride = std::min (stride, it->index);
2741 
2742   it->index -= stride;
2743   return steps + stride;
2744 }
2745 
2746 /* See btrace.h.  */
2747 
2748 int
2749 btrace_call_cmp (const struct btrace_call_iterator *lhs,
2750 		 const struct btrace_call_iterator *rhs)
2751 {
2752   gdb_assert (lhs->btinfo == rhs->btinfo);
2753   return (int) (lhs->index - rhs->index);
2754 }
2755 
2756 /* See btrace.h.  */
2757 
2758 int
2759 btrace_find_call_by_number (struct btrace_call_iterator *it,
2760 			    const struct btrace_thread_info *btinfo,
2761 			    unsigned int number)
2762 {
2763   const unsigned int length = btinfo->functions.size ();
2764 
2765   if ((number == 0) || (number > length))
2766     return 0;
2767 
2768   it->btinfo = btinfo;
2769   it->index = number - 1;
2770   return 1;
2771 }
2772 
2773 /* See btrace.h.  */
2774 
2775 void
2776 btrace_set_insn_history (struct btrace_thread_info *btinfo,
2777 			 const struct btrace_insn_iterator *begin,
2778 			 const struct btrace_insn_iterator *end)
2779 {
2780   if (btinfo->insn_history == NULL)
2781     btinfo->insn_history = XCNEW (struct btrace_insn_history);
2782 
2783   btinfo->insn_history->begin = *begin;
2784   btinfo->insn_history->end = *end;
2785 }
2786 
2787 /* See btrace.h.  */
2788 
2789 void
2790 btrace_set_call_history (struct btrace_thread_info *btinfo,
2791 			 const struct btrace_call_iterator *begin,
2792 			 const struct btrace_call_iterator *end)
2793 {
2794   gdb_assert (begin->btinfo == end->btinfo);
2795 
2796   if (btinfo->call_history == NULL)
2797     btinfo->call_history = XCNEW (struct btrace_call_history);
2798 
2799   btinfo->call_history->begin = *begin;
2800   btinfo->call_history->end = *end;
2801 }
2802 
2803 /* See btrace.h.  */
2804 
2805 int
2806 btrace_is_replaying (struct thread_info *tp)
2807 {
2808   return tp->btrace.replay != NULL;
2809 }
2810 
2811 /* See btrace.h.  */
2812 
2813 int
2814 btrace_is_empty (struct thread_info *tp)
2815 {
2816   struct btrace_insn_iterator begin, end;
2817   struct btrace_thread_info *btinfo;
2818 
2819   btinfo = &tp->btrace;
2820 
2821   if (btinfo->functions.empty ())
2822     return 1;
2823 
2824   btrace_insn_begin (&begin, btinfo);
2825   btrace_insn_end (&end, btinfo);
2826 
2827   return btrace_insn_cmp (&begin, &end) == 0;
2828 }
2829 
2830 #if defined (HAVE_LIBIPT)
2831 
2832 /* Print a single packet.  */
2833 
2834 static void
2835 pt_print_packet (const struct pt_packet *packet)
2836 {
2837   switch (packet->type)
2838     {
2839     default:
2840       printf_unfiltered (("[??: %x]"), packet->type);
2841       break;
2842 
2843     case ppt_psb:
2844       printf_unfiltered (("psb"));
2845       break;
2846 
2847     case ppt_psbend:
2848       printf_unfiltered (("psbend"));
2849       break;
2850 
2851     case ppt_pad:
2852       printf_unfiltered (("pad"));
2853       break;
2854 
2855     case ppt_tip:
2856       printf_unfiltered (("tip %u: 0x%" PRIx64 ""),
2857 			 packet->payload.ip.ipc,
2858 			 packet->payload.ip.ip);
2859       break;
2860 
2861     case ppt_tip_pge:
2862       printf_unfiltered (("tip.pge %u: 0x%" PRIx64 ""),
2863 			 packet->payload.ip.ipc,
2864 			 packet->payload.ip.ip);
2865       break;
2866 
2867     case ppt_tip_pgd:
2868       printf_unfiltered (("tip.pgd %u: 0x%" PRIx64 ""),
2869 			 packet->payload.ip.ipc,
2870 			 packet->payload.ip.ip);
2871       break;
2872 
2873     case ppt_fup:
2874       printf_unfiltered (("fup %u: 0x%" PRIx64 ""),
2875 			 packet->payload.ip.ipc,
2876 			 packet->payload.ip.ip);
2877       break;
2878 
2879     case ppt_tnt_8:
2880       printf_unfiltered (("tnt-8 %u: 0x%" PRIx64 ""),
2881 			 packet->payload.tnt.bit_size,
2882 			 packet->payload.tnt.payload);
2883       break;
2884 
2885     case ppt_tnt_64:
2886       printf_unfiltered (("tnt-64 %u: 0x%" PRIx64 ""),
2887 			 packet->payload.tnt.bit_size,
2888 			 packet->payload.tnt.payload);
2889       break;
2890 
2891     case ppt_pip:
2892       printf_unfiltered (("pip %" PRIx64 "%s"), packet->payload.pip.cr3,
2893 			 packet->payload.pip.nr ? (" nr") : (""));
2894       break;
2895 
2896     case ppt_tsc:
2897       printf_unfiltered (("tsc %" PRIx64 ""), packet->payload.tsc.tsc);
2898       break;
2899 
2900     case ppt_cbr:
2901       printf_unfiltered (("cbr %u"), packet->payload.cbr.ratio);
2902       break;
2903 
2904     case ppt_mode:
2905       switch (packet->payload.mode.leaf)
2906 	{
2907 	default:
2908 	  printf_unfiltered (("mode %u"), packet->payload.mode.leaf);
2909 	  break;
2910 
2911 	case pt_mol_exec:
2912 	  printf_unfiltered (("mode.exec%s%s"),
2913 			     packet->payload.mode.bits.exec.csl
2914 			     ? (" cs.l") : (""),
2915 			     packet->payload.mode.bits.exec.csd
2916 			     ? (" cs.d") : (""));
2917 	  break;
2918 
2919 	case pt_mol_tsx:
2920 	  printf_unfiltered (("mode.tsx%s%s"),
2921 			     packet->payload.mode.bits.tsx.intx
2922 			     ? (" intx") : (""),
2923 			     packet->payload.mode.bits.tsx.abrt
2924 			     ? (" abrt") : (""));
2925 	  break;
2926 	}
2927       break;
2928 
2929     case ppt_ovf:
2930       printf_unfiltered (("ovf"));
2931       break;
2932 
2933     case ppt_stop:
2934       printf_unfiltered (("stop"));
2935       break;
2936 
2937     case ppt_vmcs:
2938       printf_unfiltered (("vmcs %" PRIx64 ""), packet->payload.vmcs.base);
2939       break;
2940 
2941     case ppt_tma:
2942       printf_unfiltered (("tma %x %x"), packet->payload.tma.ctc,
2943 			 packet->payload.tma.fc);
2944       break;
2945 
2946     case ppt_mtc:
2947       printf_unfiltered (("mtc %x"), packet->payload.mtc.ctc);
2948       break;
2949 
2950     case ppt_cyc:
2951       printf_unfiltered (("cyc %" PRIx64 ""), packet->payload.cyc.value);
2952       break;
2953 
2954     case ppt_mnt:
2955       printf_unfiltered (("mnt %" PRIx64 ""), packet->payload.mnt.payload);
2956       break;
2957     }
2958 }
2959 
2960 /* Decode packets into MAINT using DECODER.  */
2961 
2962 static void
2963 btrace_maint_decode_pt (struct btrace_maint_info *maint,
2964 			struct pt_packet_decoder *decoder)
2965 {
2966   int errcode;
2967 
2968   if (maint->variant.pt.packets == NULL)
2969     maint->variant.pt.packets = new std::vector<btrace_pt_packet>;
2970 
2971   for (;;)
2972     {
2973       struct btrace_pt_packet packet;
2974 
2975       errcode = pt_pkt_sync_forward (decoder);
2976       if (errcode < 0)
2977 	break;
2978 
2979       for (;;)
2980 	{
2981 	  pt_pkt_get_offset (decoder, &packet.offset);
2982 
2983 	  errcode = pt_pkt_next (decoder, &packet.packet,
2984 				 sizeof(packet.packet));
2985 	  if (errcode < 0)
2986 	    break;
2987 
2988 	  if (maint_btrace_pt_skip_pad == 0 || packet.packet.type != ppt_pad)
2989 	    {
2990 	      packet.errcode = pt_errcode (errcode);
2991 	      maint->variant.pt.packets->push_back (packet);
2992 	    }
2993 	}
2994 
2995       if (errcode == -pte_eos)
2996 	break;
2997 
2998       packet.errcode = pt_errcode (errcode);
2999       maint->variant.pt.packets->push_back (packet);
3000 
3001       warning (_("Error at trace offset 0x%" PRIx64 ": %s."),
3002 	       packet.offset, pt_errstr (packet.errcode));
3003     }
3004 
3005   if (errcode != -pte_eos)
3006     warning (_("Failed to synchronize onto the Intel Processor Trace "
3007 	       "stream: %s."), pt_errstr (pt_errcode (errcode)));
3008 }
3009 
3010 /* Update the packet history in BTINFO.  */
3011 
3012 static void
3013 btrace_maint_update_pt_packets (struct btrace_thread_info *btinfo)
3014 {
3015   struct pt_packet_decoder *decoder;
3016   const struct btrace_cpu *cpu;
3017   struct btrace_data_pt *pt;
3018   struct pt_config config;
3019   int errcode;
3020 
3021   pt = &btinfo->data.variant.pt;
3022 
3023   /* Nothing to do if there is no trace.  */
3024   if (pt->size == 0)
3025     return;
3026 
3027   memset (&config, 0, sizeof(config));
3028 
3029   config.size = sizeof (config);
3030   config.begin = pt->data;
3031   config.end = pt->data + pt->size;
3032 
3033   cpu = record_btrace_get_cpu ();
3034   if (cpu == nullptr)
3035     cpu = &pt->config.cpu;
3036 
3037   /* We treat an unknown vendor as 'no errata'.  */
3038   if (cpu->vendor != CV_UNKNOWN)
3039     {
3040       config.cpu.vendor = pt_translate_cpu_vendor (cpu->vendor);
3041       config.cpu.family = cpu->family;
3042       config.cpu.model = cpu->model;
3043       config.cpu.stepping = cpu->stepping;
3044 
3045       errcode = pt_cpu_errata (&config.errata, &config.cpu);
3046       if (errcode < 0)
3047 	error (_("Failed to configure the Intel Processor Trace "
3048 		 "decoder: %s."), pt_errstr (pt_errcode (errcode)));
3049     }
3050 
3051   decoder = pt_pkt_alloc_decoder (&config);
3052   if (decoder == NULL)
3053     error (_("Failed to allocate the Intel Processor Trace decoder."));
3054 
3055   try
3056     {
3057       btrace_maint_decode_pt (&btinfo->maint, decoder);
3058     }
3059   catch (const gdb_exception &except)
3060     {
3061       pt_pkt_free_decoder (decoder);
3062 
3063       if (except.reason < 0)
3064 	throw;
3065     }
3066 
3067   pt_pkt_free_decoder (decoder);
3068 }
3069 
3070 #endif /* !defined (HAVE_LIBIPT)  */
3071 
3072 /* Update the packet maintenance information for BTINFO and store the
3073    low and high bounds into BEGIN and END, respectively.
3074    Store the current iterator state into FROM and TO.  */
3075 
3076 static void
3077 btrace_maint_update_packets (struct btrace_thread_info *btinfo,
3078 			     unsigned int *begin, unsigned int *end,
3079 			     unsigned int *from, unsigned int *to)
3080 {
3081   switch (btinfo->data.format)
3082     {
3083     default:
3084       *begin = 0;
3085       *end = 0;
3086       *from = 0;
3087       *to = 0;
3088       break;
3089 
3090     case BTRACE_FORMAT_BTS:
3091       /* Nothing to do - we operate directly on BTINFO->DATA.  */
3092       *begin = 0;
3093       *end = btinfo->data.variant.bts.blocks->size ();
3094       *from = btinfo->maint.variant.bts.packet_history.begin;
3095       *to = btinfo->maint.variant.bts.packet_history.end;
3096       break;
3097 
3098 #if defined (HAVE_LIBIPT)
3099     case BTRACE_FORMAT_PT:
3100       if (btinfo->maint.variant.pt.packets == nullptr)
3101 	btinfo->maint.variant.pt.packets = new std::vector<btrace_pt_packet>;
3102 
3103       if (btinfo->maint.variant.pt.packets->empty ())
3104 	btrace_maint_update_pt_packets (btinfo);
3105 
3106       *begin = 0;
3107       *end = btinfo->maint.variant.pt.packets->size ();
3108       *from = btinfo->maint.variant.pt.packet_history.begin;
3109       *to = btinfo->maint.variant.pt.packet_history.end;
3110       break;
3111 #endif /* defined (HAVE_LIBIPT)  */
3112     }
3113 }
3114 
3115 /* Print packets in BTINFO from BEGIN (inclusive) until END (exclusive) and
3116    update the current iterator position.  */
3117 
3118 static void
3119 btrace_maint_print_packets (struct btrace_thread_info *btinfo,
3120 			    unsigned int begin, unsigned int end)
3121 {
3122   switch (btinfo->data.format)
3123     {
3124     default:
3125       break;
3126 
3127     case BTRACE_FORMAT_BTS:
3128       {
3129 	const std::vector<btrace_block> &blocks
3130 	  = *btinfo->data.variant.bts.blocks;
3131 	unsigned int blk;
3132 
3133 	for (blk = begin; blk < end; ++blk)
3134 	  {
3135 	    const btrace_block &block = blocks.at (blk);
3136 
3137 	    printf_unfiltered ("%u\tbegin: %s, end: %s\n", blk,
3138 			       core_addr_to_string_nz (block.begin),
3139 			       core_addr_to_string_nz (block.end));
3140 	  }
3141 
3142 	btinfo->maint.variant.bts.packet_history.begin = begin;
3143 	btinfo->maint.variant.bts.packet_history.end = end;
3144       }
3145       break;
3146 
3147 #if defined (HAVE_LIBIPT)
3148     case BTRACE_FORMAT_PT:
3149       {
3150 	const std::vector<btrace_pt_packet> &packets
3151 	  = *btinfo->maint.variant.pt.packets;
3152 	unsigned int pkt;
3153 
3154 	for (pkt = begin; pkt < end; ++pkt)
3155 	  {
3156 	    const struct btrace_pt_packet &packet = packets.at (pkt);
3157 
3158 	    printf_unfiltered ("%u\t", pkt);
3159 	    printf_unfiltered ("0x%" PRIx64 "\t", packet.offset);
3160 
3161 	    if (packet.errcode == pte_ok)
3162 	      pt_print_packet (&packet.packet);
3163 	    else
3164 	      printf_unfiltered ("[error: %s]", pt_errstr (packet.errcode));
3165 
3166 	    printf_unfiltered ("\n");
3167 	  }
3168 
3169 	btinfo->maint.variant.pt.packet_history.begin = begin;
3170 	btinfo->maint.variant.pt.packet_history.end = end;
3171       }
3172       break;
3173 #endif /* defined (HAVE_LIBIPT)  */
3174     }
3175 }
3176 
3177 /* Read a number from an argument string.  */
3178 
3179 static unsigned int
3180 get_uint (const char **arg)
3181 {
3182   const char *begin, *pos;
3183   char *end;
3184   unsigned long number;
3185 
3186   begin = *arg;
3187   pos = skip_spaces (begin);
3188 
3189   if (!isdigit (*pos))
3190     error (_("Expected positive number, got: %s."), pos);
3191 
3192   number = strtoul (pos, &end, 10);
3193   if (number > UINT_MAX)
3194     error (_("Number too big."));
3195 
3196   *arg += (end - begin);
3197 
3198   return (unsigned int) number;
3199 }
3200 
3201 /* Read a context size from an argument string.  */
3202 
3203 static int
3204 get_context_size (const char **arg)
3205 {
3206   const char *pos = skip_spaces (*arg);
3207 
3208   if (!isdigit (*pos))
3209     error (_("Expected positive number, got: %s."), pos);
3210 
3211   char *end;
3212   long result = strtol (pos, &end, 10);
3213   *arg = end;
3214   return result;
3215 }
3216 
3217 /* Complain about junk at the end of an argument string.  */
3218 
3219 static void
3220 no_chunk (const char *arg)
3221 {
3222   if (*arg != 0)
3223     error (_("Junk after argument: %s."), arg);
3224 }
3225 
3226 /* The "maintenance btrace packet-history" command.  */
3227 
3228 static void
3229 maint_btrace_packet_history_cmd (const char *arg, int from_tty)
3230 {
3231   struct btrace_thread_info *btinfo;
3232   unsigned int size, begin, end, from, to;
3233 
3234   thread_info *tp = find_thread_ptid (current_inferior (), inferior_ptid);
3235   if (tp == NULL)
3236     error (_("No thread."));
3237 
3238   size = 10;
3239   btinfo = &tp->btrace;
3240 
3241   btrace_maint_update_packets (btinfo, &begin, &end, &from, &to);
3242   if (begin == end)
3243     {
3244       printf_unfiltered (_("No trace.\n"));
3245       return;
3246     }
3247 
3248   if (arg == NULL || *arg == 0 || strcmp (arg, "+") == 0)
3249     {
3250       from = to;
3251 
3252       if (end - from < size)
3253 	size = end - from;
3254       to = from + size;
3255     }
3256   else if (strcmp (arg, "-") == 0)
3257     {
3258       to = from;
3259 
3260       if (to - begin < size)
3261 	size = to - begin;
3262       from = to - size;
3263     }
3264   else
3265     {
3266       from = get_uint (&arg);
3267       if (end <= from)
3268 	error (_("'%u' is out of range."), from);
3269 
3270       arg = skip_spaces (arg);
3271       if (*arg == ',')
3272 	{
3273 	  arg = skip_spaces (++arg);
3274 
3275 	  if (*arg == '+')
3276 	    {
3277 	      arg += 1;
3278 	      size = get_context_size (&arg);
3279 
3280 	      no_chunk (arg);
3281 
3282 	      if (end - from < size)
3283 		size = end - from;
3284 	      to = from + size;
3285 	    }
3286 	  else if (*arg == '-')
3287 	    {
3288 	      arg += 1;
3289 	      size = get_context_size (&arg);
3290 
3291 	      no_chunk (arg);
3292 
3293 	      /* Include the packet given as first argument.  */
3294 	      from += 1;
3295 	      to = from;
3296 
3297 	      if (to - begin < size)
3298 		size = to - begin;
3299 	      from = to - size;
3300 	    }
3301 	  else
3302 	    {
3303 	      to = get_uint (&arg);
3304 
3305 	      /* Include the packet at the second argument and silently
3306 		 truncate the range.  */
3307 	      if (to < end)
3308 		to += 1;
3309 	      else
3310 		to = end;
3311 
3312 	      no_chunk (arg);
3313 	    }
3314 	}
3315       else
3316 	{
3317 	  no_chunk (arg);
3318 
3319 	  if (end - from < size)
3320 	    size = end - from;
3321 	  to = from + size;
3322 	}
3323 
3324       dont_repeat ();
3325     }
3326 
3327   btrace_maint_print_packets (btinfo, from, to);
3328 }
3329 
3330 /* The "maintenance btrace clear-packet-history" command.  */
3331 
3332 static void
3333 maint_btrace_clear_packet_history_cmd (const char *args, int from_tty)
3334 {
3335   if (args != NULL && *args != 0)
3336     error (_("Invalid argument."));
3337 
3338   if (inferior_ptid == null_ptid)
3339     error (_("No thread."));
3340 
3341   thread_info *tp = inferior_thread ();
3342   btrace_thread_info *btinfo = &tp->btrace;
3343 
3344   /* Must clear the maint data before - it depends on BTINFO->DATA.  */
3345   btrace_maint_clear (btinfo);
3346   btinfo->data.clear ();
3347 }
3348 
3349 /* The "maintenance btrace clear" command.  */
3350 
3351 static void
3352 maint_btrace_clear_cmd (const char *args, int from_tty)
3353 {
3354   if (args != NULL && *args != 0)
3355     error (_("Invalid argument."));
3356 
3357   if (inferior_ptid == null_ptid)
3358     error (_("No thread."));
3359 
3360   thread_info *tp = inferior_thread ();
3361   btrace_clear (tp);
3362 }
3363 
3364 /* The "maintenance info btrace" command.  */
3365 
3366 static void
3367 maint_info_btrace_cmd (const char *args, int from_tty)
3368 {
3369   struct btrace_thread_info *btinfo;
3370   const struct btrace_config *conf;
3371 
3372   if (args != NULL && *args != 0)
3373     error (_("Invalid argument."));
3374 
3375   if (inferior_ptid == null_ptid)
3376     error (_("No thread."));
3377 
3378   thread_info *tp = inferior_thread ();
3379 
3380   btinfo = &tp->btrace;
3381 
3382   conf = btrace_conf (btinfo);
3383   if (conf == NULL)
3384     error (_("No btrace configuration."));
3385 
3386   printf_unfiltered (_("Format: %s.\n"),
3387 		     btrace_format_string (conf->format));
3388 
3389   switch (conf->format)
3390     {
3391     default:
3392       break;
3393 
3394     case BTRACE_FORMAT_BTS:
3395       printf_unfiltered (_("Number of packets: %zu.\n"),
3396 			 btinfo->data.variant.bts.blocks->size ());
3397       break;
3398 
3399 #if defined (HAVE_LIBIPT)
3400     case BTRACE_FORMAT_PT:
3401       {
3402 	struct pt_version version;
3403 
3404 	version = pt_library_version ();
3405 	printf_unfiltered (_("Version: %u.%u.%u%s.\n"), version.major,
3406 			   version.minor, version.build,
3407 			   version.ext != NULL ? version.ext : "");
3408 
3409 	btrace_maint_update_pt_packets (btinfo);
3410 	printf_unfiltered (_("Number of packets: %zu.\n"),
3411 			   ((btinfo->maint.variant.pt.packets == nullptr)
3412 			    ? 0 : btinfo->maint.variant.pt.packets->size ()));
3413       }
3414       break;
3415 #endif /* defined (HAVE_LIBIPT)  */
3416     }
3417 }
3418 
3419 /* The "maint show btrace pt skip-pad" show value function. */
3420 
3421 static void
3422 show_maint_btrace_pt_skip_pad  (struct ui_file *file, int from_tty,
3423 				  struct cmd_list_element *c,
3424 				  const char *value)
3425 {
3426   fprintf_filtered (file, _("Skip PAD packets is %s.\n"), value);
3427 }
3428 
3429 
3430 /* Initialize btrace maintenance commands.  */
3431 
3432 void _initialize_btrace ();
3433 void
3434 _initialize_btrace ()
3435 {
3436   add_cmd ("btrace", class_maintenance, maint_info_btrace_cmd,
3437 	   _("Info about branch tracing data."), &maintenanceinfolist);
3438 
3439   add_basic_prefix_cmd ("btrace", class_maintenance,
3440 			_("Branch tracing maintenance commands."),
3441 			&maint_btrace_cmdlist, "maintenance btrace ",
3442 			0, &maintenancelist);
3443 
3444   add_basic_prefix_cmd ("btrace", class_maintenance, _("\
3445 Set branch tracing specific variables."),
3446 			&maint_btrace_set_cmdlist, "maintenance set btrace ",
3447 			0, &maintenance_set_cmdlist);
3448 
3449   add_basic_prefix_cmd ("pt", class_maintenance, _("\
3450 Set Intel Processor Trace specific variables."),
3451 			&maint_btrace_pt_set_cmdlist,
3452 			"maintenance set btrace pt ",
3453 			0, &maint_btrace_set_cmdlist);
3454 
3455   add_show_prefix_cmd ("btrace", class_maintenance, _("\
3456 Show branch tracing specific variables."),
3457 		       &maint_btrace_show_cmdlist, "maintenance show btrace ",
3458 		       0, &maintenance_show_cmdlist);
3459 
3460   add_show_prefix_cmd ("pt", class_maintenance, _("\
3461 Show Intel Processor Trace specific variables."),
3462 		       &maint_btrace_pt_show_cmdlist,
3463 		       "maintenance show btrace pt ",
3464 		       0, &maint_btrace_show_cmdlist);
3465 
3466   add_setshow_boolean_cmd ("skip-pad", class_maintenance,
3467 			   &maint_btrace_pt_skip_pad, _("\
3468 Set whether PAD packets should be skipped in the btrace packet history."), _("\
3469 Show whether PAD packets should be skipped in the btrace packet history."),_("\
3470 When enabled, PAD packets are ignored in the btrace packet history."),
3471 			   NULL, show_maint_btrace_pt_skip_pad,
3472 			   &maint_btrace_pt_set_cmdlist,
3473 			   &maint_btrace_pt_show_cmdlist);
3474 
3475   add_cmd ("packet-history", class_maintenance, maint_btrace_packet_history_cmd,
3476 	   _("Print the raw branch tracing data.\n\
3477 With no argument, print ten more packets after the previous ten-line print.\n\
3478 With '-' as argument print ten packets before a previous ten-line print.\n\
3479 One argument specifies the starting packet of a ten-line print.\n\
3480 Two arguments with comma between specify starting and ending packets to \
3481 print.\n\
3482 Preceded with '+'/'-' the second argument specifies the distance from the \
3483 first."),
3484 	   &maint_btrace_cmdlist);
3485 
3486   add_cmd ("clear-packet-history", class_maintenance,
3487 	   maint_btrace_clear_packet_history_cmd,
3488 	   _("Clears the branch tracing packet history.\n\
3489 Discards the raw branch tracing data but not the execution history data."),
3490 	   &maint_btrace_cmdlist);
3491 
3492   add_cmd ("clear", class_maintenance, maint_btrace_clear_cmd,
3493 	   _("Clears the branch tracing data.\n\
3494 Discards the raw branch tracing data and the execution history data.\n\
3495 The next 'record' command will fetch the branch tracing data anew."),
3496 	   &maint_btrace_cmdlist);
3497 
3498 }
3499