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