gdb/nat/linux-btrace.c - gdb

Data types defined

Functions defined

Source code

  1. /* Linux-dependent part of branch trace support for GDB, and GDBserver.

  2.    Copyright (C) 2013-2015 Free Software Foundation, Inc.

  3.    Contributed by Intel Corp. <markus.t.metzger@intel.com>

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. #include "common-defs.h"
  16. #include "linux-btrace.h"
  17. #include "common-regcache.h"
  18. #include "gdb_wait.h"
  19. #include "x86-cpuid.h"

  20. #ifdef HAVE_SYS_SYSCALL_H
  21. #include <sys/syscall.h>
  22. #endif

  23. #if HAVE_LINUX_PERF_EVENT_H && defined(SYS_perf_event_open)

  24. #include <stdint.h>
  25. #include <unistd.h>
  26. #include <sys/mman.h>
  27. #include <sys/user.h>
  28. #include <sys/ptrace.h>
  29. #include <sys/types.h>
  30. #include <signal.h>

  31. /* A branch trace record in perf_event.  */
  32. struct perf_event_bts
  33. {
  34.   /* The linear address of the branch source.  */
  35.   uint64_t from;

  36.   /* The linear address of the branch destination.  */
  37.   uint64_t to;
  38. };

  39. /* A perf_event branch trace sample.  */
  40. struct perf_event_sample
  41. {
  42.   /* The perf_event sample header.  */
  43.   struct perf_event_header header;

  44.   /* The perf_event branch tracing payload.  */
  45.   struct perf_event_bts bts;
  46. };

  47. /* Get the perf_event header.  */

  48. static inline volatile struct perf_event_mmap_page *
  49. perf_event_header (struct btrace_target_info* tinfo)
  50. {
  51.   return tinfo->buffer;
  52. }

  53. /* Get the size of the perf_event mmap buffer.  */

  54. static inline size_t
  55. perf_event_mmap_size (const struct btrace_target_info *tinfo)
  56. {
  57.   /* The branch trace buffer is preceded by a configuration page.  */
  58.   return (tinfo->size + 1) * PAGE_SIZE;
  59. }

  60. /* Get the size of the perf_event buffer.  */

  61. static inline size_t
  62. perf_event_buffer_size (struct btrace_target_info* tinfo)
  63. {
  64.   return tinfo->size * PAGE_SIZE;
  65. }

  66. /* Get the start address of the perf_event buffer.  */

  67. static inline const uint8_t *
  68. perf_event_buffer_begin (struct btrace_target_info* tinfo)
  69. {
  70.   return ((const uint8_t *) tinfo->buffer) + PAGE_SIZE;
  71. }

  72. /* Get the end address of the perf_event buffer.  */

  73. static inline const uint8_t *
  74. perf_event_buffer_end (struct btrace_target_info* tinfo)
  75. {
  76.   return perf_event_buffer_begin (tinfo) + perf_event_buffer_size (tinfo);
  77. }

  78. /* Check whether an address is in the kernel.  */

  79. static inline int
  80. perf_event_is_kernel_addr (const struct btrace_target_info *tinfo,
  81.                            uint64_t addr)
  82. {
  83.   uint64_t mask;

  84.   /* If we don't know the size of a pointer, we can't check.  Let's assume it's
  85.      not a kernel address in this case.  */
  86.   if (tinfo->ptr_bits == 0)
  87.     return 0;

  88.   /* A bit mask for the most significant bit in an address.  */
  89.   mask = (uint64_t) 1 << (tinfo->ptr_bits - 1);

  90.   /* Check whether the most significant bit in the address is set.  */
  91.   return (addr & mask) != 0;
  92. }

  93. /* Check whether a perf event record should be skipped.  */

  94. static inline int
  95. perf_event_skip_record (const struct btrace_target_info *tinfo,
  96.                         const struct perf_event_bts *bts)
  97. {
  98.   /* The hardware may report branches from kernel into user space.  Branches
  99.      from user into kernel space will be suppressed.  We filter the former to
  100.      provide a consistent branch trace excluding kernel.  */
  101.   return perf_event_is_kernel_addr (tinfo, bts->from);
  102. }

  103. /* Perform a few consistency checks on a perf event sample record.  This is
  104.    meant to catch cases when we get out of sync with the perf event stream.  */

  105. static inline int
  106. perf_event_sample_ok (const struct perf_event_sample *sample)
  107. {
  108.   if (sample->header.type != PERF_RECORD_SAMPLE)
  109.     return 0;

  110.   if (sample->header.size != sizeof (*sample))
  111.     return 0;

  112.   return 1;
  113. }

  114. /* Branch trace is collected in a circular buffer [begin; end) as pairs of from
  115.    and to addresses (plus a header).

  116.    Start points into that buffer at the next sample position.
  117.    We read the collected samples backwards from start.

  118.    While reading the samples, we convert the information into a list of blocks.
  119.    For two adjacent samples s1 and s2, we form a block b such that b.begin =
  120.    s1.to and b.end = s2.from.

  121.    In case the buffer overflows during sampling, one sample may have its lower
  122.    part at the end and its upper part at the beginning of the buffer.  */

  123. static VEC (btrace_block_s) *
  124. perf_event_read_bts (struct btrace_target_info* tinfo, const uint8_t *begin,
  125.                      const uint8_t *end, const uint8_t *start, size_t size)
  126. {
  127.   VEC (btrace_block_s) *btrace = NULL;
  128.   struct perf_event_sample sample;
  129.   size_t read = 0;
  130.   struct btrace_block block = { 0, 0 };
  131.   struct regcache *regcache;

  132.   gdb_assert (begin <= start);
  133.   gdb_assert (start <= end);

  134.   /* The first block ends at the current pc.  */
  135.   regcache = get_thread_regcache_for_ptid (tinfo->ptid);
  136.   block.end = regcache_read_pc (regcache);

  137.   /* The buffer may contain a partial record as its last entry (i.e. when the
  138.      buffer size is not a multiple of the sample size).  */
  139.   read = sizeof (sample) - 1;

  140.   for (; read < size; read += sizeof (sample))
  141.     {
  142.       const struct perf_event_sample *psample;

  143.       /* Find the next perf_event sample in a backwards traversal.  */
  144.       start -= sizeof (sample);

  145.       /* If we're still inside the buffer, we're done.  */
  146.       if (begin <= start)
  147.         psample = (const struct perf_event_sample *) start;
  148.       else
  149.         {
  150.           int missing;

  151.           /* We're to the left of the ring buffer, we will wrap around and
  152.              reappear at the very right of the ring buffer.  */

  153.           missing = (begin - start);
  154.           start = (end - missing);

  155.           /* If the entire sample is missing, we're done.  */
  156.           if (missing == sizeof (sample))
  157.             psample = (const struct perf_event_sample *) start;
  158.           else
  159.             {
  160.               uint8_t *stack;

  161.               /* The sample wrapped around.  The lower part is at the end and
  162.                  the upper part is at the beginning of the buffer.  */
  163.               stack = (uint8_t *) &sample;

  164.               /* Copy the two parts so we have a contiguous sample.  */
  165.               memcpy (stack, start, missing);
  166.               memcpy (stack + missing, begin, sizeof (sample) - missing);

  167.               psample = &sample;
  168.             }
  169.         }

  170.       if (!perf_event_sample_ok (psample))
  171.         {
  172.           warning (_("Branch trace may be incomplete."));
  173.           break;
  174.         }

  175.       if (perf_event_skip_record (tinfo, &psample->bts))
  176.         continue;

  177.       /* We found a valid sample, so we can complete the current block.  */
  178.       block.begin = psample->bts.to;

  179.       VEC_safe_push (btrace_block_s, btrace, &block);

  180.       /* Start the next block.  */
  181.       block.end = psample->bts.from;
  182.     }

  183.   /* Push the last block (i.e. the first one of inferior execution), as well.
  184.      We don't know where it ends, but we know where it starts.  If we're
  185.      reading delta trace, we can fill in the start address later on.
  186.      Otherwise we will prune it.  */
  187.   block.begin = 0;
  188.   VEC_safe_push (btrace_block_s, btrace, &block);

  189.   return btrace;
  190. }

  191. /* Check whether the kernel supports branch tracing.  */

  192. static int
  193. kernel_supports_btrace (void)
  194. {
  195.   struct perf_event_attr attr;
  196.   pid_t child, pid;
  197.   int status, file;

  198.   errno = 0;
  199.   child = fork ();
  200.   switch (child)
  201.     {
  202.     case -1:
  203.       warning (_("test branch tracing: cannot fork: %s."), strerror (errno));
  204.       return 0;

  205.     case 0:
  206.       status = ptrace (PTRACE_TRACEME, 0, NULL, NULL);
  207.       if (status != 0)
  208.         {
  209.           warning (_("test branch tracing: cannot PTRACE_TRACEME: %s."),
  210.                    strerror (errno));
  211.           _exit (1);
  212.         }

  213.       status = raise (SIGTRAP);
  214.       if (status != 0)
  215.         {
  216.           warning (_("test branch tracing: cannot raise SIGTRAP: %s."),
  217.                    strerror (errno));
  218.           _exit (1);
  219.         }

  220.       _exit (1);

  221.     default:
  222.       pid = waitpid (child, &status, 0);
  223.       if (pid != child)
  224.         {
  225.           warning (_("test branch tracing: bad pid %ld, error: %s."),
  226.                    (long) pid, strerror (errno));
  227.           return 0;
  228.         }

  229.       if (!WIFSTOPPED (status))
  230.         {
  231.           warning (_("test branch tracing: expected stop. status: %d."),
  232.                    status);
  233.           return 0;
  234.         }

  235.       memset (&attr, 0, sizeof (attr));

  236.       attr.type = PERF_TYPE_HARDWARE;
  237.       attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
  238.       attr.sample_period = 1;
  239.       attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_ADDR;
  240.       attr.exclude_kernel = 1;
  241.       attr.exclude_hv = 1;
  242.       attr.exclude_idle = 1;

  243.       file = syscall (SYS_perf_event_open, &attr, child, -1, -1, 0);
  244.       if (file >= 0)
  245.         close (file);

  246.       kill (child, SIGKILL);
  247.       ptrace (PTRACE_KILL, child, NULL, NULL);

  248.       pid = waitpid (child, &status, 0);
  249.       if (pid != child)
  250.         {
  251.           warning (_("test branch tracing: bad pid %ld, error: %s."),
  252.                    (long) pid, strerror (errno));
  253.           if (!WIFSIGNALED (status))
  254.             warning (_("test branch tracing: expected killed. status: %d."),
  255.                      status);
  256.         }

  257.       return (file >= 0);
  258.     }
  259. }

  260. /* Check whether an Intel cpu supports branch tracing.  */

  261. static int
  262. intel_supports_btrace (void)
  263. {
  264.   unsigned int cpuid, model, family;

  265.   if (!x86_cpuid (1, &cpuid, NULL, NULL, NULL))
  266.     return 0;

  267.   family = (cpuid >> 8) & 0xf;
  268.   model = (cpuid >> 4) & 0xf;

  269.   switch (family)
  270.     {
  271.     case 0x6:
  272.       model += (cpuid >> 12) & 0xf0;

  273.       switch (model)
  274.         {
  275.         case 0x1a: /* Nehalem */
  276.         case 0x1f:
  277.         case 0x1e:
  278.         case 0x2e:
  279.         case 0x25: /* Westmere */
  280.         case 0x2c:
  281.         case 0x2f:
  282.         case 0x2a: /* Sandy Bridge */
  283.         case 0x2d:
  284.         case 0x3a: /* Ivy Bridge */

  285.           /* AAJ122: LBR, BTM, or BTS records may have incorrect branch
  286.              "from" information afer an EIST transition, T-states, C1E, or
  287.              Adaptive Thermal Throttling.  */
  288.           return 0;
  289.         }
  290.     }

  291.   return 1;
  292. }

  293. /* Check whether the cpu supports branch tracing.  */

  294. static int
  295. cpu_supports_btrace (void)
  296. {
  297.   unsigned int ebx, ecx, edx;

  298.   if (!x86_cpuid (0, NULL, &ebx, &ecx, &edx))
  299.     return 0;

  300.   if (ebx == signature_INTEL_ebx && ecx == signature_INTEL_ecx
  301.       && edx == signature_INTEL_edx)
  302.     return intel_supports_btrace ();

  303.   /* Don't know about others.  Let's assume they do.  */
  304.   return 1;
  305. }

  306. /* See linux-btrace.h.  */

  307. int
  308. linux_supports_btrace (struct target_ops *ops)
  309. {
  310.   static int cached;

  311.   if (cached == 0)
  312.     {
  313.       if (!kernel_supports_btrace ())
  314.         cached = -1;
  315.       else if (!cpu_supports_btrace ())
  316.         cached = -1;
  317.       else
  318.         cached = 1;
  319.     }

  320.   return cached > 0;
  321. }

  322. /* See linux-btrace.h.  */

  323. struct btrace_target_info *
  324. linux_enable_btrace (ptid_t ptid)
  325. {
  326.   struct btrace_target_info *tinfo;
  327.   int pid, pg;

  328.   tinfo = xzalloc (sizeof (*tinfo));
  329.   tinfo->ptid = ptid;

  330.   tinfo->attr.size = sizeof (tinfo->attr);
  331.   tinfo->attr.type = PERF_TYPE_HARDWARE;
  332.   tinfo->attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
  333.   tinfo->attr.sample_period = 1;

  334.   /* We sample from and to address.  */
  335.   tinfo->attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_ADDR;

  336.   tinfo->attr.exclude_kernel = 1;
  337.   tinfo->attr.exclude_hv = 1;
  338.   tinfo->attr.exclude_idle = 1;

  339.   tinfo->ptr_bits = 0;

  340.   pid = ptid_get_lwp (ptid);
  341.   if (pid == 0)
  342.     pid = ptid_get_pid (ptid);

  343.   errno = 0;
  344.   tinfo->file = syscall (SYS_perf_event_open, &tinfo->attr, pid, -1, -1, 0);
  345.   if (tinfo->file < 0)
  346.     goto err;

  347.   /* We try to allocate as much buffer as we can get.
  348.      We could allow the user to specify the size of the buffer, but then
  349.      we'd leave this search for the maximum buffer size to him.  */
  350.   for (pg = 4; pg >= 0; --pg)
  351.     {
  352.       /* The number of pages we request needs to be a power of two.  */
  353.       tinfo->size = 1 << pg;
  354.       tinfo->buffer = mmap (NULL, perf_event_mmap_size (tinfo),
  355.                             PROT_READ, MAP_SHARED, tinfo->file, 0);
  356.       if (tinfo->buffer == MAP_FAILED)
  357.         continue;

  358.       return tinfo;
  359.     }

  360.   /* We were not able to allocate any buffer.  */
  361.   close (tinfo->file);

  362. err:
  363.   xfree (tinfo);
  364.   return NULL;
  365. }

  366. /* See linux-btrace.h.  */

  367. enum btrace_error
  368. linux_disable_btrace (struct btrace_target_info *tinfo)
  369. {
  370.   int errcode;

  371.   errno = 0;
  372.   errcode = munmap (tinfo->buffer, perf_event_mmap_size (tinfo));
  373.   if (errcode != 0)
  374.     return BTRACE_ERR_UNKNOWN;

  375.   close (tinfo->file);
  376.   xfree (tinfo);

  377.   return BTRACE_ERR_NONE;
  378. }

  379. /* Check whether the branch trace has changed.  */

  380. static int
  381. linux_btrace_has_changed (struct btrace_target_info *tinfo)
  382. {
  383.   volatile struct perf_event_mmap_page *header = perf_event_header (tinfo);

  384.   return header->data_head != tinfo->data_head;
  385. }

  386. /* See linux-btrace.h.  */

  387. enum btrace_error
  388. linux_read_btrace (VEC (btrace_block_s) **btrace,
  389.                    struct btrace_target_info *tinfo,
  390.                    enum btrace_read_type type)
  391. {
  392.   volatile struct perf_event_mmap_page *header;
  393.   const uint8_t *begin, *end, *start;
  394.   unsigned long data_head, data_tail, retries = 5;
  395.   size_t buffer_size, size;

  396.   /* For delta reads, we return at least the partial last block containing
  397.      the current PC.  */
  398.   if (type == BTRACE_READ_NEW && !linux_btrace_has_changed (tinfo))
  399.     return BTRACE_ERR_NONE;

  400.   header = perf_event_header (tinfo);
  401.   buffer_size = perf_event_buffer_size (tinfo);
  402.   data_tail = tinfo->data_head;

  403.   /* We may need to retry reading the trace.  See below.  */
  404.   while (retries--)
  405.     {
  406.       data_head = header->data_head;

  407.       /* Delete any leftover trace from the previous iteration.  */
  408.       VEC_free (btrace_block_s, *btrace);

  409.       if (type == BTRACE_READ_DELTA)
  410.         {
  411.           /* Determine the number of bytes to read and check for buffer
  412.              overflows.  */

  413.           /* Check for data head overflows.  We might be able to recover from
  414.              those but they are very unlikely and it's not really worth the
  415.              effort, I think.  */
  416.           if (data_head < data_tail)
  417.             return BTRACE_ERR_OVERFLOW;

  418.           /* If the buffer is smaller than the trace delta, we overflowed.  */
  419.           size = data_head - data_tail;
  420.           if (buffer_size < size)
  421.             return BTRACE_ERR_OVERFLOW;
  422.         }
  423.       else
  424.         {
  425.           /* Read the entire buffer.  */
  426.           size = buffer_size;

  427.           /* Adjust the size if the buffer has not overflowed, yet.  */
  428.           if (data_head < size)
  429.             size = data_head;
  430.         }

  431.       /* Data_head keeps growing; the buffer itself is circular.  */
  432.       begin = perf_event_buffer_begin (tinfo);
  433.       start = begin + data_head % buffer_size;

  434.       if (data_head <= buffer_size)
  435.         end = start;
  436.       else
  437.         end = perf_event_buffer_end (tinfo);

  438.       *btrace = perf_event_read_bts (tinfo, begin, end, start, size);

  439.       /* The stopping thread notifies its ptracer before it is scheduled out.
  440.          On multi-core systems, the debugger might therefore run while the
  441.          kernel might be writing the last branch trace records.

  442.          Let's check whether the data head moved while we read the trace.  */
  443.       if (data_head == header->data_head)
  444.         break;
  445.     }

  446.   tinfo->data_head = data_head;

  447.   /* Prune the incomplete last block (i.e. the first one of inferior execution)
  448.      if we're not doing a delta read.  There is no way of filling in its zeroed
  449.      BEGIN element.  */
  450.   if (!VEC_empty (btrace_block_s, *btrace) && type != BTRACE_READ_DELTA)
  451.     VEC_pop (btrace_block_s, *btrace);

  452.   return BTRACE_ERR_NONE;
  453. }

  454. #else /* !HAVE_LINUX_PERF_EVENT_H */

  455. /* See linux-btrace.h.  */

  456. int
  457. linux_supports_btrace (struct target_ops *ops)
  458. {
  459.   return 0;
  460. }

  461. /* See linux-btrace.h.  */

  462. struct btrace_target_info *
  463. linux_enable_btrace (ptid_t ptid)
  464. {
  465.   return NULL;
  466. }

  467. /* See linux-btrace.h.  */

  468. enum btrace_error
  469. linux_disable_btrace (struct btrace_target_info *tinfo)
  470. {
  471.   return BTRACE_ERR_NOT_SUPPORTED;
  472. }

  473. /* See linux-btrace.h.  */

  474. enum btrace_error
  475. linux_read_btrace (VEC (btrace_block_s) **btrace,
  476.                    struct btrace_target_info *tinfo,
  477.                    enum btrace_read_type type)
  478. {
  479.   return BTRACE_ERR_NOT_SUPPORTED;
  480. }

  481. #endif /* !HAVE_LINUX_PERF_EVENT_H */