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