gdb/ctf.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* CTF format support.

  2.    Copyright (C) 2012-2015 Free Software Foundation, Inc.
  3.    Contributed by Hui Zhu <hui_zhu@mentor.com>
  4.    Contributed by Yao Qi <yao@codesourcery.com>

  5.    This file is part of GDB.

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

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

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

  16. #include "defs.h"
  17. #include "ctf.h"
  18. #include "tracepoint.h"
  19. #include "regcache.h"
  20. #include <sys/stat.h>
  21. #include "exec.h"
  22. #include "completer.h"
  23. #include "inferior.h"
  24. #include "gdbthread.h"
  25. #include "tracefile.h"

  26. #include <ctype.h>

  27. /* GDB saves trace buffers and other information (such as trace
  28.    status) got from the remote target into Common Trace Format (CTF).
  29.    The following types of information are expected to save in CTF:

  30.    1. The length (in bytes) of register cache.  Event "register" will
  31.    be defined in metadata, which includes the length.

  32.    2. Trace status.  Event "status" is defined in metadata, which
  33.    includes all aspects of trace status.

  34.    3. Uploaded trace variables.  Event "tsv_def" is defined in
  35.    metadata, which is about all aspects of a uploaded trace variable.
  36.    Uploaded tracepoints.   Event "tp_def" is defined in meta, which
  37.    is about all aspects of an uploaded tracepoint.  Note that the
  38.    "sequence" (a CTF type, which is a dynamically-sized array.) is
  39.    used for "actions" "step_actions" and "cmd_strings".

  40.    4. Trace frames.  Each trace frame is composed by several blocks
  41.    of different types ('R', 'M', 'V').  One trace frame is saved in
  42.    one CTF packet and the blocks of this frame are saved as events.
  43.    4.1: The trace frame related information (such as the number of
  44.    tracepoint associated with this frame) is saved in the packet
  45.    context.
  46.    4.2: The block 'M', 'R' and 'V' are saved in event "memory",
  47.    "register" and "tsv" respectively.
  48.    4.3: When iterating over events, babeltrace can't tell iterator
  49.    goes to a new packet, so we need a marker or anchor to tell GDB
  50.    that iterator goes into a new packet or frame.  We define event
  51.    "frame".  */

  52. #define CTF_MAGIC                0xC1FC1FC1
  53. #define CTF_SAVE_MAJOR                1
  54. #define CTF_SAVE_MINOR                8

  55. #define CTF_METADATA_NAME        "metadata"
  56. #define CTF_DATASTREAM_NAME        "datastream"

  57. /* Reserved event id.  */

  58. #define CTF_EVENT_ID_REGISTER 0
  59. #define CTF_EVENT_ID_TSV 1
  60. #define CTF_EVENT_ID_MEMORY 2
  61. #define CTF_EVENT_ID_FRAME 3
  62. #define CTF_EVENT_ID_STATUS 4
  63. #define CTF_EVENT_ID_TSV_DEF 5
  64. #define CTF_EVENT_ID_TP_DEF 6

  65. #define CTF_PID (2)

  66. /* The state kept while writing the CTF datastream file.  */

  67. struct trace_write_handler
  68. {
  69.   /* File descriptor of metadata.  */
  70.   FILE *metadata_fd;
  71.   /* File descriptor of traceframes.  */
  72.   FILE *datastream_fd;

  73.   /* This is the content size of the current packet.  */
  74.   size_t content_size;

  75.   /* This is the start offset of current packet.  */
  76.   long packet_start;
  77. };

  78. /* Write metadata in FORMAT.  */

  79. static void
  80. ctf_save_write_metadata (struct trace_write_handler *handler,
  81.                          const char *format, ...)
  82. {
  83.   va_list args;

  84.   va_start (args, format);
  85.   if (vfprintf (handler->metadata_fd, format, args) < 0)
  86.     error (_("Unable to write metadata file (%s)"),
  87.              safe_strerror (errno));
  88.   va_end (args);
  89. }

  90. /* Write BUF of length SIZE to datastream file represented by
  91.    HANDLER.  */

  92. static int
  93. ctf_save_write (struct trace_write_handler *handler,
  94.                 const gdb_byte *buf, size_t size)
  95. {
  96.   if (fwrite (buf, size, 1, handler->datastream_fd) != 1)
  97.     error (_("Unable to write file for saving trace data (%s)"),
  98.            safe_strerror (errno));

  99.   handler->content_size += size;

  100.   return 0;
  101. }

  102. /* Write a unsigned 32-bit integer to datastream file represented by
  103.    HANDLER.  */

  104. #define ctf_save_write_uint32(HANDLER, U32) \
  105.   ctf_save_write (HANDLER, (gdb_byte *) &U32, 4)

  106. /* Write a signed 32-bit integer to datastream file represented by
  107.    HANDLER.  */

  108. #define ctf_save_write_int32(HANDLER, INT32) \
  109.   ctf_save_write ((HANDLER), (gdb_byte *) &(INT32), 4)

  110. /* Set datastream file position.  Update HANDLER->content_size
  111.    if WHENCE is SEEK_CUR.  */

  112. static int
  113. ctf_save_fseek (struct trace_write_handler *handler, long offset,
  114.                 int whence)
  115. {
  116.   gdb_assert (whence != SEEK_END);
  117.   gdb_assert (whence != SEEK_SET
  118.               || offset <= handler->content_size + handler->packet_start);

  119.   if (fseek (handler->datastream_fd, offset, whence))
  120.     error (_("Unable to seek file for saving trace data (%s)"),
  121.            safe_strerror (errno));

  122.   if (whence == SEEK_CUR)
  123.     handler->content_size += offset;

  124.   return 0;
  125. }

  126. /* Change the datastream file position to align on ALIGN_SIZE,
  127.    and write BUF to datastream file.  The size of BUF is SIZE.  */

  128. static int
  129. ctf_save_align_write (struct trace_write_handler *handler,
  130.                       const gdb_byte *buf,
  131.                       size_t size, size_t align_size)
  132. {
  133.   long offset
  134.     = (align_up (handler->content_size, align_size)
  135.        - handler->content_size);

  136.   if (ctf_save_fseek (handler, offset, SEEK_CUR))
  137.     return -1;

  138.   if (ctf_save_write (handler, buf, size))
  139.     return -1;

  140.   return 0;
  141. }

  142. /* Write events to next new packet.  */

  143. static void
  144. ctf_save_next_packet (struct trace_write_handler *handler)
  145. {
  146.   handler->packet_start += (handler->content_size + 4);
  147.   ctf_save_fseek (handler, handler->packet_start, SEEK_SET);
  148.   handler->content_size = 0;
  149. }

  150. /* Write the CTF metadata header.  */

  151. static void
  152. ctf_save_metadata_header (struct trace_write_handler *handler)
  153. {
  154.   const char metadata_fmt[] =
  155.   "\ntrace {\n"
  156.   "        major = %u;\n"
  157.   "        minor = %u;\n"
  158.   "        byte_order = %s;\n"                /* be or le */
  159.   "        packet.header := struct {\n"
  160.   "                uint32_t magic;\n"
  161.   "        };\n"
  162.   "};\n"
  163.   "\n"
  164.   "stream {\n"
  165.   "        packet.context := struct {\n"
  166.   "                uint32_t content_size;\n"
  167.   "                uint32_t packet_size;\n"
  168.   "                uint16_t tpnum;\n"
  169.   "        };\n"
  170.   "        event.header := struct {\n"
  171.   "                uint32_t id;\n"
  172.   "        };\n"
  173.   "};\n";

  174.   ctf_save_write_metadata (handler, "/* CTF %d.%d */\n",
  175.                            CTF_SAVE_MAJOR, CTF_SAVE_MINOR);
  176.   ctf_save_write_metadata (handler,
  177.                            "typealias integer { size = 8; align = 8; "
  178.                            "signed = false; encoding = ascii;}"
  179.                            " := ascii;\n");
  180.   ctf_save_write_metadata (handler,
  181.                            "typealias integer { size = 8; align = 8; "
  182.                            "signed = false; }"
  183.                            " := uint8_t;\n");
  184.   ctf_save_write_metadata (handler,
  185.                            "typealias integer { size = 16; align = 16;"
  186.                            "signed = false; } := uint16_t;\n");
  187.   ctf_save_write_metadata (handler,
  188.                            "typealias integer { size = 32; align = 32;"
  189.                            "signed = false; } := uint32_t;\n");
  190.   ctf_save_write_metadata (handler,
  191.                            "typealias integer { size = 64; align = 64;"
  192.                            "signed = false; base = hex;}"
  193.                            " := uint64_t;\n");
  194.   ctf_save_write_metadata (handler,
  195.                            "typealias integer { size = 32; align = 32;"
  196.                            "signed = true; } := int32_t;\n");
  197.   ctf_save_write_metadata (handler,
  198.                            "typealias integer { size = 64; align = 64;"
  199.                            "signed = true; } := int64_t;\n");
  200.   ctf_save_write_metadata (handler,
  201.                            "typealias string { encoding = ascii;"
  202.                            " } := chars;\n");
  203.   ctf_save_write_metadata (handler, "\n");

  204.   /* Get the byte order of the host and write CTF data in this byte
  205.      order.  */
  206. #if WORDS_BIGENDIAN
  207. #define HOST_ENDIANNESS "be"
  208. #else
  209. #define HOST_ENDIANNESS "le"
  210. #endif

  211.   ctf_save_write_metadata (handler, metadata_fmt,
  212.                            CTF_SAVE_MAJOR, CTF_SAVE_MINOR,
  213.                            HOST_ENDIANNESS);
  214.   ctf_save_write_metadata (handler, "\n");
  215. }

  216. /* CTF trace writer.  */

  217. struct ctf_trace_file_writer
  218. {
  219.   struct trace_file_writer base;

  220.   /* States related to writing CTF trace file.  */
  221.   struct trace_write_handler tcs;
  222. };

  223. /* This is the implementation of trace_file_write_ops method
  224.    dtor.  */

  225. static void
  226. ctf_dtor (struct trace_file_writer *self)
  227. {
  228.   struct ctf_trace_file_writer *writer
  229.     = (struct ctf_trace_file_writer *) self;

  230.   if (writer->tcs.metadata_fd != NULL)
  231.     fclose (writer->tcs.metadata_fd);

  232.   if (writer->tcs.datastream_fd != NULL)
  233.     fclose (writer->tcs.datastream_fd);

  234. }

  235. /* This is the implementation of trace_file_write_ops method
  236.    target_save.  */

  237. static int
  238. ctf_target_save (struct trace_file_writer *self,
  239.                  const char *dirname)
  240. {
  241.   /* Don't support save trace file to CTF format in the target.  */
  242.   return 0;
  243. }

  244. #ifdef USE_WIN32API
  245. #undef mkdir
  246. #define mkdir(pathname, mode) mkdir (pathname)
  247. #endif

  248. /* This is the implementation of trace_file_write_ops method
  249.    start.  It creates the directory DIRNAME, metadata and datastream
  250.    in the directory.  */

  251. static void
  252. ctf_start (struct trace_file_writer *self, const char *dirname)
  253. {
  254.   char *file_name;
  255.   struct cleanup *old_chain;
  256.   struct ctf_trace_file_writer *writer
  257.     = (struct ctf_trace_file_writer *) self;
  258.   int i;
  259.   mode_t hmode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH;

  260.   /* Create DIRNAME.  */
  261.   if (mkdir (dirname, hmode) && errno != EEXIST)
  262.     error (_("Unable to open directory '%s' for saving trace data (%s)"),
  263.            dirname, safe_strerror (errno));

  264.   memset (&writer->tcs, '\0', sizeof (writer->tcs));

  265.   file_name = xstrprintf ("%s/%s", dirname, CTF_METADATA_NAME);
  266.   old_chain = make_cleanup (xfree, file_name);

  267.   writer->tcs.metadata_fd = fopen (file_name, "w");
  268.   if (writer->tcs.metadata_fd == NULL)
  269.     error (_("Unable to open file '%s' for saving trace data (%s)"),
  270.            file_name, safe_strerror (errno));
  271.   do_cleanups (old_chain);

  272.   ctf_save_metadata_header (&writer->tcs);

  273.   file_name = xstrprintf ("%s/%s", dirname, CTF_DATASTREAM_NAME);
  274.   old_chain = make_cleanup (xfree, file_name);
  275.   writer->tcs.datastream_fd = fopen (file_name, "w");
  276.   if (writer->tcs.datastream_fd == NULL)
  277.     error (_("Unable to open file '%s' for saving trace data (%s)"),
  278.            file_name, safe_strerror (errno));
  279.   do_cleanups (old_chain);
  280. }

  281. /* This is the implementation of trace_file_write_ops method
  282.    write_header.  Write the types of events on trace variable and
  283.    frame.  */

  284. static void
  285. ctf_write_header (struct trace_file_writer *self)
  286. {
  287.   struct ctf_trace_file_writer *writer
  288.     = (struct ctf_trace_file_writer *) self;


  289.   ctf_save_write_metadata (&writer->tcs, "\n");
  290.   ctf_save_write_metadata (&writer->tcs,
  291.                            "event {\n\tname = \"memory\";\n\tid = %u;\n"
  292.                            "\tfields := struct { \n"
  293.                            "\t\tuint64_t address;\n"
  294.                            "\t\tuint16_t length;\n"
  295.                            "\t\tuint8_t contents[length];\n"
  296.                            "\t};\n"
  297.                            "};\n", CTF_EVENT_ID_MEMORY);

  298.   ctf_save_write_metadata (&writer->tcs, "\n");
  299.   ctf_save_write_metadata (&writer->tcs,
  300.                            "event {\n\tname = \"tsv\";\n\tid = %u;\n"
  301.                            "\tfields := struct { \n"
  302.                            "\t\tuint64_t val;\n"
  303.                            "\t\tuint32_t num;\n"
  304.                            "\t};\n"
  305.                            "};\n", CTF_EVENT_ID_TSV);

  306.   ctf_save_write_metadata (&writer->tcs, "\n");
  307.   ctf_save_write_metadata (&writer->tcs,
  308.                            "event {\n\tname = \"frame\";\n\tid = %u;\n"
  309.                            "\tfields := struct { \n"
  310.                            "\t};\n"
  311.                            "};\n", CTF_EVENT_ID_FRAME);

  312.   ctf_save_write_metadata (&writer->tcs, "\n");
  313.   ctf_save_write_metadata (&writer->tcs,
  314.                           "event {\n\tname = \"tsv_def\";\n"
  315.                           "\tid = %u;\n\tfields := struct { \n"
  316.                           "\t\tint64_t initial_value;\n"
  317.                           "\t\tint32_t number;\n"
  318.                           "\t\tint32_t builtin;\n"
  319.                           "\t\tchars name;\n"
  320.                           "\t};\n"
  321.                           "};\n", CTF_EVENT_ID_TSV_DEF);

  322.   ctf_save_write_metadata (&writer->tcs, "\n");
  323.   ctf_save_write_metadata (&writer->tcs,
  324.                            "event {\n\tname = \"tp_def\";\n"
  325.                            "\tid = %u;\n\tfields := struct { \n"
  326.                            "\t\tuint64_t addr;\n"
  327.                            "\t\tuint64_t traceframe_usage;\n"
  328.                            "\t\tint32_t number;\n"
  329.                            "\t\tint32_t enabled;\n"
  330.                            "\t\tint32_t step;\n"
  331.                            "\t\tint32_t pass;\n"
  332.                            "\t\tint32_t hit_count;\n"
  333.                            "\t\tint32_t type;\n"
  334.                            "\t\tchars cond;\n"

  335.                           "\t\tuint32_t action_num;\n"
  336.                           "\t\tchars actions[action_num];\n"

  337.                           "\t\tuint32_t step_action_num;\n"
  338.                           "\t\tchars step_actions[step_action_num];\n"

  339.                           "\t\tchars at_string;\n"
  340.                           "\t\tchars cond_string;\n"

  341.                           "\t\tuint32_t cmd_num;\n"
  342.                           "\t\tchars cmd_strings[cmd_num];\n"
  343.                           "\t};\n"
  344.                           "};\n", CTF_EVENT_ID_TP_DEF);

  345.   gdb_assert (writer->tcs.content_size == 0);
  346.   gdb_assert (writer->tcs.packet_start == 0);

  347.   /* Create a new packet to contain this event.  */
  348.   self->ops->frame_ops->start (self, 0);
  349. }

  350. /* This is the implementation of trace_file_write_ops method
  351.    write_regblock_type.  Write the type of register event in
  352.    metadata.  */

  353. static void
  354. ctf_write_regblock_type (struct trace_file_writer *self, int size)
  355. {
  356.   struct ctf_trace_file_writer *writer
  357.     = (struct ctf_trace_file_writer *) self;

  358.   ctf_save_write_metadata (&writer->tcs, "\n");

  359.   ctf_save_write_metadata (&writer->tcs,
  360.                            "event {\n\tname = \"register\";\n\tid = %u;\n"
  361.                            "\tfields := struct { \n"
  362.                            "\t\tascii contents[%d];\n"
  363.                            "\t};\n"
  364.                            "};\n",
  365.                            CTF_EVENT_ID_REGISTER, size);
  366. }

  367. /* This is the implementation of trace_file_write_ops method
  368.    write_status.  */

  369. static void
  370. ctf_write_status (struct trace_file_writer *self,
  371.                   struct trace_status *ts)
  372. {
  373.   struct ctf_trace_file_writer *writer
  374.     = (struct ctf_trace_file_writer *) self;
  375.   uint32_t id;
  376.   int32_t int32;

  377.   ctf_save_write_metadata (&writer->tcs, "\n");
  378.   ctf_save_write_metadata (&writer->tcs,
  379.                            "event {\n\tname = \"status\";\n\tid = %u;\n"
  380.                            "\tfields := struct { \n"
  381.                            "\t\tint32_t stop_reason;\n"
  382.                            "\t\tint32_t stopping_tracepoint;\n"
  383.                            "\t\tint32_t traceframe_count;\n"
  384.                            "\t\tint32_t traceframes_created;\n"
  385.                            "\t\tint32_t buffer_free;\n"
  386.                            "\t\tint32_t buffer_size;\n"
  387.                            "\t\tint32_t disconnected_tracing;\n"
  388.                            "\t\tint32_t circular_buffer;\n"
  389.                            "\t};\n"
  390.                            "};\n",
  391.                            CTF_EVENT_ID_STATUS);

  392.   id = CTF_EVENT_ID_STATUS;
  393.   /* Event Id.  */
  394.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);

  395.   ctf_save_write_int32 (&writer->tcs, ts->stop_reason);
  396.   ctf_save_write_int32 (&writer->tcs, ts->stopping_tracepoint);
  397.   ctf_save_write_int32 (&writer->tcs, ts->traceframe_count);
  398.   ctf_save_write_int32 (&writer->tcs, ts->traceframes_created);
  399.   ctf_save_write_int32 (&writer->tcs, ts->buffer_free);
  400.   ctf_save_write_int32 (&writer->tcs, ts->buffer_size);
  401.   ctf_save_write_int32 (&writer->tcs, ts->disconnected_tracing);
  402.   ctf_save_write_int32 (&writer->tcs, ts->circular_buffer);
  403. }

  404. /* This is the implementation of trace_file_write_ops method
  405.    write_uploaded_tsv.  */

  406. static void
  407. ctf_write_uploaded_tsv (struct trace_file_writer *self,
  408.                         struct uploaded_tsv *tsv)
  409. {
  410.   struct ctf_trace_file_writer *writer
  411.     = (struct ctf_trace_file_writer *) self;
  412.   int32_t int32;
  413.   int64_t int64;
  414.   unsigned int len;
  415.   const gdb_byte zero = 0;

  416.   /* Event Id.  */
  417.   int32 = CTF_EVENT_ID_TSV_DEF;
  418.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);

  419.   /* initial_value */
  420.   int64 = tsv->initial_value;
  421.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);

  422.   /* number */
  423.   ctf_save_write_int32 (&writer->tcs, tsv->number);

  424.   /* builtin */
  425.   ctf_save_write_int32 (&writer->tcs, tsv->builtin);

  426.   /* name */
  427.   if (tsv->name != NULL)
  428.     ctf_save_write (&writer->tcs, (gdb_byte *) tsv->name,
  429.                     strlen (tsv->name));
  430.   ctf_save_write (&writer->tcs, &zero, 1);
  431. }

  432. /* This is the implementation of trace_file_write_ops method
  433.    write_uploaded_tp.  */

  434. static void
  435. ctf_write_uploaded_tp (struct trace_file_writer *self,
  436.                        struct uploaded_tp *tp)
  437. {
  438.   struct ctf_trace_file_writer *writer
  439.     = (struct ctf_trace_file_writer *) self;
  440.   int32_t int32;
  441.   int64_t int64;
  442.   uint32_t u32;
  443.   const gdb_byte zero = 0;
  444.   int a;
  445.   char *act;

  446.   /* Event Id.  */
  447.   int32 = CTF_EVENT_ID_TP_DEF;
  448.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);

  449.   /* address */
  450.   int64 = tp->addr;
  451.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);

  452.   /* traceframe_usage */
  453.   int64 = tp->traceframe_usage;
  454.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);

  455.   /* number */
  456.   ctf_save_write_int32 (&writer->tcs, tp->number);

  457.   /* enabled */
  458.   ctf_save_write_int32 (&writer->tcs, tp->enabled);

  459.   /* step */
  460.   ctf_save_write_int32 (&writer->tcs, tp->step);

  461.   /* pass */
  462.   ctf_save_write_int32 (&writer->tcs, tp->pass);

  463.   /* hit_count */
  464.   ctf_save_write_int32 (&writer->tcs, tp->hit_count);

  465.   /* type */
  466.   ctf_save_write_int32 (&writer->tcs, tp->type);

  467.   /* condition  */
  468.   if (tp->cond != NULL)
  469.     ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond, strlen (tp->cond));
  470.   ctf_save_write (&writer->tcs, &zero, 1);

  471.   /* actions */
  472.   u32 = VEC_length (char_ptr, tp->actions);
  473.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
  474.   for (a = 0; VEC_iterate (char_ptr, tp->actions, a, act); ++a)
  475.     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);

  476.   /* step_actions */
  477.   u32 = VEC_length (char_ptr, tp->step_actions);
  478.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
  479.   for (a = 0; VEC_iterate (char_ptr, tp->step_actions, a, act); ++a)
  480.     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);

  481.   /* at_string */
  482.   if (tp->at_string != NULL)
  483.     ctf_save_write (&writer->tcs, (gdb_byte *) tp->at_string,
  484.                     strlen (tp->at_string));
  485.   ctf_save_write (&writer->tcs, &zero, 1);

  486.   /* cond_string */
  487.   if (tp->cond_string != NULL)
  488.     ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond_string,
  489.                     strlen (tp->cond_string));
  490.   ctf_save_write (&writer->tcs, &zero, 1);

  491.   /* cmd_strings */
  492.   u32 = VEC_length (char_ptr, tp->cmd_strings);
  493.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
  494.   for (a = 0; VEC_iterate (char_ptr, tp->cmd_strings, a, act); ++a)
  495.     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);

  496. }

  497. /* This is the implementation of trace_file_write_ops method
  498.    write_definition_end.  */

  499. static void
  500. ctf_write_definition_end (struct trace_file_writer *self)
  501. {
  502.   struct ctf_trace_file_writer *writer
  503.     = (struct ctf_trace_file_writer *) self;

  504.   self->ops->frame_ops->end (self);
  505. }

  506. /* This is the implementation of trace_file_write_ops method
  507.    end.  */

  508. static void
  509. ctf_end (struct trace_file_writer *self)
  510. {
  511.   struct ctf_trace_file_writer *writer = (struct ctf_trace_file_writer *) self;

  512.   gdb_assert (writer->tcs.content_size == 0);
  513. }

  514. /* This is the implementation of trace_frame_write_ops method
  515.    start.  */

  516. static void
  517. ctf_write_frame_start (struct trace_file_writer *self, uint16_t tpnum)
  518. {
  519.   struct ctf_trace_file_writer *writer
  520.     = (struct ctf_trace_file_writer *) self;
  521.   uint32_t id = CTF_EVENT_ID_FRAME;
  522.   uint32_t u32;

  523.   /* Step 1: Write packet context.  */
  524.   /* magic.  */
  525.   u32 = CTF_MAGIC;
  526.   ctf_save_write_uint32 (&writer->tcs, u32);
  527.   /* content_size and packet_size..  We still don't know the value,
  528.      write it later.  */
  529.   ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
  530.   ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
  531.   /* Tracepoint number.  */
  532.   ctf_save_write (&writer->tcs, (gdb_byte *) &tpnum, 2);

  533.   /* Step 2: Write event "frame".  */
  534.   /* Event Id.  */
  535.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
  536. }

  537. /* This is the implementation of trace_frame_write_ops method
  538.    write_r_block.  */

  539. static void
  540. ctf_write_frame_r_block (struct trace_file_writer *self,
  541.                          gdb_byte *buf, int32_t size)
  542. {
  543.   struct ctf_trace_file_writer *writer
  544.     = (struct ctf_trace_file_writer *) self;
  545.   uint32_t id = CTF_EVENT_ID_REGISTER;

  546.   /* Event Id.  */
  547.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);

  548.   /* array contents.  */
  549.   ctf_save_align_write (&writer->tcs, buf, size, 1);
  550. }

  551. /* This is the implementation of trace_frame_write_ops method
  552.    write_m_block_header.  */

  553. static void
  554. ctf_write_frame_m_block_header (struct trace_file_writer *self,
  555.                                 uint64_t addr, uint16_t length)
  556. {
  557.   struct ctf_trace_file_writer *writer
  558.     = (struct ctf_trace_file_writer *) self;
  559.   uint32_t event_id = CTF_EVENT_ID_MEMORY;

  560.   /* Event Id.  */
  561.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &event_id, 4, 4);

  562.   /* Address.  */
  563.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &addr, 8, 8);

  564.   /* Length.  */
  565.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &length, 2, 2);
  566. }

  567. /* This is the implementation of trace_frame_write_ops method
  568.    write_m_block_memory.  */

  569. static void
  570. ctf_write_frame_m_block_memory (struct trace_file_writer *self,
  571.                                 gdb_byte *buf, uint16_t length)
  572. {
  573.   struct ctf_trace_file_writer *writer
  574.     = (struct ctf_trace_file_writer *) self;

  575.   /* Contents.  */
  576.   ctf_save_align_write (&writer->tcs, (gdb_byte *) buf, length, 1);
  577. }

  578. /* This is the implementation of trace_frame_write_ops method
  579.    write_v_block.  */

  580. static void
  581. ctf_write_frame_v_block (struct trace_file_writer *self,
  582.                          int32_t num, uint64_t val)
  583. {
  584.   struct ctf_trace_file_writer *writer
  585.     = (struct ctf_trace_file_writer *) self;
  586.   uint32_t id = CTF_EVENT_ID_TSV;

  587.   /* Event Id.  */
  588.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);

  589.   /* val.  */
  590.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &val, 8, 8);
  591.   /* num.  */
  592.   ctf_save_align_write (&writer->tcs, (gdb_byte *) &num, 4, 4);
  593. }

  594. /* This is the implementation of trace_frame_write_ops method
  595.    end.  */

  596. static void
  597. ctf_write_frame_end (struct trace_file_writer *self)
  598. {
  599.   struct ctf_trace_file_writer *writer
  600.     = (struct ctf_trace_file_writer *) self;
  601.   uint32_t u32;
  602.   uint32_t t;

  603.   /* Write the content size to packet header.  */
  604.   ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + 4,
  605.                   SEEK_SET);
  606.   u32 = writer->tcs.content_size * TARGET_CHAR_BIT;

  607.   t = writer->tcs.content_size;
  608.   ctf_save_write_uint32 (&writer->tcs, u32);

  609.   /* Write the packet size.  */
  610.   u32 += 4 * TARGET_CHAR_BIT;
  611.   ctf_save_write_uint32 (&writer->tcs, u32);

  612.   writer->tcs.content_size = t;

  613.   /* Write zero at the end of the packet.  */
  614.   ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + t,
  615.                   SEEK_SET);
  616.   u32 = 0;
  617.   ctf_save_write_uint32 (&writer->tcs, u32);
  618.   writer->tcs.content_size = t;

  619.   ctf_save_next_packet (&writer->tcs);
  620. }

  621. /* Operations to write various types of trace frames into CTF
  622.    format.  */

  623. static const struct trace_frame_write_ops ctf_write_frame_ops =
  624. {
  625.   ctf_write_frame_start,
  626.   ctf_write_frame_r_block,
  627.   ctf_write_frame_m_block_header,
  628.   ctf_write_frame_m_block_memory,
  629.   ctf_write_frame_v_block,
  630.   ctf_write_frame_end,
  631. };

  632. /* Operations to write trace buffers into CTF format.  */

  633. static const struct trace_file_write_ops ctf_write_ops =
  634. {
  635.   ctf_dtor,
  636.   ctf_target_save,
  637.   ctf_start,
  638.   ctf_write_header,
  639.   ctf_write_regblock_type,
  640.   ctf_write_status,
  641.   ctf_write_uploaded_tsv,
  642.   ctf_write_uploaded_tp,
  643.   ctf_write_definition_end,
  644.   NULL,
  645.   &ctf_write_frame_ops,
  646.   ctf_end,
  647. };

  648. /* Return a trace writer for CTF format.  */

  649. struct trace_file_writer *
  650. ctf_trace_file_writer_new (void)
  651. {
  652.   struct ctf_trace_file_writer *writer
  653.     = xmalloc (sizeof (struct ctf_trace_file_writer));

  654.   writer->base.ops = &ctf_write_ops;

  655.   return (struct trace_file_writer *) writer;
  656. }

  657. #if HAVE_LIBBABELTRACE
  658. /* Use libbabeltrace to read CTF data.  The libbabeltrace provides
  659.    iterator to iterate over each event in CTF data and APIs to get
  660.    details of event and packet, so it is very convenient to use
  661.    libbabeltrace to access events in CTF.  */

  662. #include <babeltrace/babeltrace.h>
  663. #include <babeltrace/ctf/events.h>
  664. #include <babeltrace/ctf/iterator.h>

  665. /* The struct pointer for current CTF directory.  */
  666. static int handle_id = -1;
  667. static struct bt_context *ctx = NULL;
  668. static struct bt_ctf_iter *ctf_iter = NULL;
  669. /* The position of the first packet containing trace frame.  */
  670. static struct bt_iter_pos *start_pos;

  671. /* The name of CTF directory.  */
  672. static char *trace_dirname;

  673. static struct target_ops ctf_ops;

  674. /* Destroy ctf iterator and context.  */

  675. static void
  676. ctf_destroy (void)
  677. {
  678.   if (ctf_iter != NULL)
  679.     {
  680.       bt_ctf_iter_destroy (ctf_iter);
  681.       ctf_iter = NULL;
  682.     }
  683.   if (ctx != NULL)
  684.     {
  685.       bt_context_put (ctx);
  686.       ctx = NULL;
  687.     }
  688. }

  689. /* Open CTF trace data in DIRNAME.  */

  690. static void
  691. ctf_open_dir (const char *dirname)
  692. {
  693.   struct bt_iter_pos begin_pos;
  694.   struct bt_iter_pos *pos;
  695.   unsigned int count, i;
  696.   struct bt_ctf_event_decl * const *list;

  697.   ctx = bt_context_create ();
  698.   if (ctx == NULL)
  699.     error (_("Unable to create bt_context"));
  700.   handle_id = bt_context_add_trace (ctx, dirname, "ctf", NULL, NULL, NULL);
  701.   if (handle_id < 0)
  702.     {
  703.       ctf_destroy ();
  704.       error (_("Unable to use libbabeltrace on directory \"%s\""),
  705.              dirname);
  706.     }

  707.   begin_pos.type = BT_SEEK_BEGIN;
  708.   ctf_iter = bt_ctf_iter_create (ctx, &begin_pos, NULL);
  709.   if (ctf_iter == NULL)
  710.     {
  711.       ctf_destroy ();
  712.       error (_("Unable to create bt_iterator"));
  713.     }

  714.   /* Look for the declaration of register block.  Get the length of
  715.      array "contents" to set trace_regblock_size.  */

  716.   bt_ctf_get_event_decl_list (handle_id, ctx, &list, &count);
  717.   for (i = 0; i < count; i++)
  718.     if (strcmp ("register", bt_ctf_get_decl_event_name (list[i])) == 0)
  719.       {
  720.         unsigned int j;
  721.         const struct bt_ctf_field_decl * const *field_list;
  722.         const struct bt_declaration *decl;

  723.         bt_ctf_get_decl_fields (list[i], BT_EVENT_FIELDS, &field_list,
  724.                                 &count);

  725.         gdb_assert (count == 1);
  726.         gdb_assert (0 == strcmp ("contents",
  727.                                  bt_ctf_get_decl_field_name (field_list[0])));
  728.         decl = bt_ctf_get_decl_from_field_decl (field_list[0]);
  729.         trace_regblock_size = bt_ctf_get_array_len (decl);

  730.         break;
  731.       }
  732. }

  733. #define SET_INT32_FIELD(EVENT, SCOPE, VAR, FIELD)                        \
  734.   (VAR)->FIELD = (int) bt_ctf_get_int64 (bt_ctf_get_field ((EVENT),        \
  735.                                                            (SCOPE),        \
  736.                                                            #FIELD))

  737. /* EVENT is the "status" event and TS is filled in.  */

  738. static void
  739. ctf_read_status (struct bt_ctf_event *event, struct trace_status *ts)
  740. {
  741.   const struct bt_definition *scope
  742.     = bt_ctf_get_top_level_scope (event, BT_EVENT_FIELDS);

  743.   SET_INT32_FIELD (event, scope, ts, stop_reason);
  744.   SET_INT32_FIELD (event, scope, ts, stopping_tracepoint);
  745.   SET_INT32_FIELD (event, scope, ts, traceframe_count);
  746.   SET_INT32_FIELD (event, scope, ts, traceframes_created);
  747.   SET_INT32_FIELD (event, scope, ts, buffer_free);
  748.   SET_INT32_FIELD (event, scope, ts, buffer_size);
  749.   SET_INT32_FIELD (event, scope, ts, disconnected_tracing);
  750.   SET_INT32_FIELD (event, scope, ts, circular_buffer);

  751.   bt_iter_next (bt_ctf_get_iter (ctf_iter));
  752. }

  753. /* Read the events "tsv_def" one by one, extract its contents and fill
  754.    in the list UPLOADED_TSVS.  */

  755. static void
  756. ctf_read_tsv (struct uploaded_tsv **uploaded_tsvs)
  757. {
  758.   gdb_assert (ctf_iter != NULL);

  759.   while (1)
  760.     {
  761.       struct bt_ctf_event *event;
  762.       const struct bt_definition *scope;
  763.       const struct bt_definition *def;
  764.       uint32_t event_id;
  765.       struct uploaded_tsv *utsv = NULL;

  766.       event = bt_ctf_iter_read_event (ctf_iter);
  767.       scope = bt_ctf_get_top_level_scope (event,
  768.                                           BT_STREAM_EVENT_HEADER);
  769.       event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
  770.                                                       "id"));
  771.       if (event_id != CTF_EVENT_ID_TSV_DEF)
  772.         break;

  773.       scope = bt_ctf_get_top_level_scope (event,
  774.                                           BT_EVENT_FIELDS);

  775.       def = bt_ctf_get_field (event, scope, "number");
  776.       utsv = get_uploaded_tsv ((int32_t) bt_ctf_get_int64 (def),
  777.                                uploaded_tsvs);

  778.       def = bt_ctf_get_field (event, scope, "builtin");
  779.       utsv->builtin = (int32_t) bt_ctf_get_int64 (def);
  780.       def = bt_ctf_get_field (event, scope, "initial_value");
  781.       utsv->initial_value = bt_ctf_get_int64 (def);

  782.       def = bt_ctf_get_field (event, scope, "name");
  783.       utsv->namexstrdup (bt_ctf_get_string (def));

  784.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  785.         break;
  786.     }

  787. }

  788. /* Read the value of element whose index is NUM from CTF and write it
  789.    to the corresponding VAR->ARRAY. */

  790. #define SET_ARRAY_FIELD(EVENT, SCOPE, VAR, NUM, ARRAY)        \
  791.   do                                                        \
  792.     {                                                        \
  793.       uint32_t u32, i;                                                \
  794.       const struct bt_definition *def;                                \
  795.                                                                 \
  796.       u32 = (uint32_t) bt_ctf_get_uint64 (bt_ctf_get_field ((EVENT),        \
  797.                                                             (SCOPE),        \
  798.                                                             #NUM));        \
  799.       def = bt_ctf_get_field ((EVENT), (SCOPE), #ARRAY);                \
  800.       for (i = 0; i < u32; i++)                                        \
  801.         {                                                                \
  802.           const struct bt_definition *element                                \
  803.             = bt_ctf_get_index ((EVENT), def, i);                        \
  804.                                                                         \
  805.           VEC_safe_push (char_ptr, (VAR)->ARRAY,                        \
  806.                          xstrdup (bt_ctf_get_string (element)));        \
  807.         }                                                                \
  808.     }                                                                        \
  809.   while (0)

  810. /* Read a string from CTF and set VAR->FIELD. If the length of string
  811.    is zero, set VAR->FIELD to NULL.  */

  812. #define SET_STRING_FIELD(EVENT, SCOPE, VAR, FIELD)                        \
  813.   do                                                                        \
  814.     {                                                                        \
  815.       const char *p = bt_ctf_get_string (bt_ctf_get_field ((EVENT),        \
  816.                                                            (SCOPE),        \
  817.                                                            #FIELD));        \
  818.                                                                         \
  819.       if (strlen (p) > 0)                                                \
  820.         (VAR)->FIELD = xstrdup (p);                                        \
  821.       else                                                                \
  822.         (VAR)->FIELD = NULL;                                                \
  823.     }                                                                        \
  824.   while (0)

  825. /* Read the events "tp_def" one by one, extract its contents and fill
  826.    in the list UPLOADED_TPS.  */

  827. static void
  828. ctf_read_tp (struct uploaded_tp **uploaded_tps)
  829. {
  830.   gdb_assert (ctf_iter != NULL);

  831.   while (1)
  832.     {
  833.       struct bt_ctf_event *event;
  834.       const struct bt_definition *scope;
  835.       uint32_t u32;
  836.       int32_t int32;
  837.       uint64_t u64;
  838.       struct uploaded_tp *utp = NULL;

  839.       event = bt_ctf_iter_read_event (ctf_iter);
  840.       scope = bt_ctf_get_top_level_scope (event,
  841.                                           BT_STREAM_EVENT_HEADER);
  842.       u32 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
  843.                                                  "id"));
  844.       if (u32 != CTF_EVENT_ID_TP_DEF)
  845.         break;

  846.       scope = bt_ctf_get_top_level_scope (event,
  847.                                           BT_EVENT_FIELDS);
  848.       int32 = (int32_t) bt_ctf_get_int64 (bt_ctf_get_field (event,
  849.                                                             scope,
  850.                                                             "number"));
  851.       u64 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
  852.                                                  "addr"));
  853.       utp = get_uploaded_tp (int32, u64,  uploaded_tps);

  854.       SET_INT32_FIELD (event, scope, utp, enabled);
  855.       SET_INT32_FIELD (event, scope, utp, step);
  856.       SET_INT32_FIELD (event, scope, utp, pass);
  857.       SET_INT32_FIELD (event, scope, utp, hit_count);
  858.       SET_INT32_FIELD (event, scope, utp, type);

  859.       /* Read 'cmd_strings'.  */
  860.       SET_ARRAY_FIELD (event, scope, utp, cmd_num, cmd_strings);
  861.       /* Read 'actions'.  */
  862.       SET_ARRAY_FIELD (event, scope, utp, action_num, actions);
  863.       /* Read 'step_actions'.  */
  864.       SET_ARRAY_FIELD (event, scope, utp, step_action_num,
  865.                        step_actions);

  866.       SET_STRING_FIELD(event, scope, utp, at_string);
  867.       SET_STRING_FIELD(event, scope, utp, cond_string);

  868.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  869.         break;
  870.     }
  871. }

  872. /* This is the implementation of target_ops method to_open.  Open CTF
  873.    trace data, read trace status, trace state variables and tracepoint
  874.    definitions from the first packet.  Set the start position at the
  875.    second packet which contains events on trace blocks.  */

  876. static void
  877. ctf_open (const char *dirname, int from_tty)
  878. {
  879.   struct bt_ctf_event *event;
  880.   uint32_t event_id;
  881.   const struct bt_definition *scope;
  882.   struct uploaded_tsv *uploaded_tsvs = NULL;
  883.   struct uploaded_tp *uploaded_tps = NULL;

  884.   if (!dirname)
  885.     error (_("No CTF directory specified."));

  886.   ctf_open_dir (dirname);

  887.   target_preopen (from_tty);

  888.   /* Skip the first packet which about the trace status.  The first
  889.      event is "frame".  */
  890.   event = bt_ctf_iter_read_event (ctf_iter);
  891.   scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
  892.   event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
  893.   if (event_id != CTF_EVENT_ID_FRAME)
  894.     error (_("Wrong event id of the first event"));
  895.   /* The second event is "status".  */
  896.   bt_iter_next (bt_ctf_get_iter (ctf_iter));
  897.   event = bt_ctf_iter_read_event (ctf_iter);
  898.   scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
  899.   event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
  900.   if (event_id != CTF_EVENT_ID_STATUS)
  901.     error (_("Wrong event id of the second event"));
  902.   ctf_read_status (event, current_trace_status ());

  903.   ctf_read_tsv (&uploaded_tsvs);

  904.   ctf_read_tp (&uploaded_tps);

  905.   event = bt_ctf_iter_read_event (ctf_iter);
  906.   /* EVENT can be NULL if we've already gone to the end of stream of
  907.      events.  */
  908.   if (event != NULL)
  909.     {
  910.       scope = bt_ctf_get_top_level_scope (event,
  911.                                           BT_STREAM_EVENT_HEADER);
  912.       event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event,
  913.                                                       scope, "id"));
  914.       if (event_id != CTF_EVENT_ID_FRAME)
  915.         error (_("Wrong event id of the first event of the second packet"));
  916.     }

  917.   start_pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  918.   gdb_assert (start_pos->type == BT_SEEK_RESTORE);

  919.   trace_dirname = xstrdup (dirname);
  920.   push_target (&ctf_ops);

  921.   inferior_appeared (current_inferior (), CTF_PID);
  922.   inferior_ptid = pid_to_ptid (CTF_PID);
  923.   add_thread_silent (inferior_ptid);

  924.   merge_uploaded_trace_state_variables (&uploaded_tsvs);
  925.   merge_uploaded_tracepoints (&uploaded_tps);

  926.   post_create_inferior (&ctf_ops, from_tty);
  927. }

  928. /* This is the implementation of target_ops method to_close.  Destroy
  929.    CTF iterator and context.  */

  930. static void
  931. ctf_close (struct target_ops *self)
  932. {
  933.   int pid;

  934.   ctf_destroy ();
  935.   xfree (trace_dirname);
  936.   trace_dirname = NULL;

  937.   pid = ptid_get_pid (inferior_ptid);
  938.   inferior_ptid = null_ptid;        /* Avoid confusion from thread stuff.  */
  939.   exit_inferior_silent (pid);

  940.   trace_reset_local_state ();
  941. }

  942. /* This is the implementation of target_ops method to_files_info.
  943.    Print the directory name of CTF trace data.  */

  944. static void
  945. ctf_files_info (struct target_ops *t)
  946. {
  947.   printf_filtered ("\t`%s'\n", trace_dirname);
  948. }

  949. /* This is the implementation of target_ops method to_fetch_registers.
  950.    Iterate over events whose name is "register" in current frame,
  951.    extract contents from events, and set REGCACHE with the contents.
  952.    If no matched events are found, mark registers unavailable.  */

  953. static void
  954. ctf_fetch_registers (struct target_ops *ops,
  955.                      struct regcache *regcache, int regno)
  956. {
  957.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  958.   struct bt_ctf_event *event = NULL;
  959.   struct bt_iter_pos *pos;

  960.   /* An uninitialized reg size says we're not going to be
  961.      successful at getting register blocks.  */
  962.   if (trace_regblock_size == 0)
  963.     return;

  964.   gdb_assert (ctf_iter != NULL);
  965.   /* Save the current position.  */
  966.   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  967.   gdb_assert (pos->type == BT_SEEK_RESTORE);

  968.   while (1)
  969.     {
  970.       const char *name;
  971.       struct bt_ctf_event *event1;

  972.       event1 = bt_ctf_iter_read_event (ctf_iter);

  973.       name = bt_ctf_event_name (event1);

  974.       if (name == NULL || strcmp (name, "frame") == 0)
  975.         break;
  976.       else if (strcmp (name, "register") == 0)
  977.         {
  978.           event = event1;
  979.           break;
  980.         }

  981.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  982.         break;
  983.     }

  984.   /* Restore the position.  */
  985.   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  986.   if (event != NULL)
  987.     {
  988.       int offset, regsize, regn;
  989.       const struct bt_definition *scope
  990.         = bt_ctf_get_top_level_scope (event,
  991.                                       BT_EVENT_FIELDS);
  992.       const struct bt_definition *array
  993.         = bt_ctf_get_field (event, scope, "contents");
  994.       gdb_byte *regs = (gdb_byte *) bt_ctf_get_char_array (array);

  995.       /* Assume the block is laid out in GDB register number order,
  996.          each register with the size that it has in GDB.  */
  997.       offset = 0;
  998.       for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
  999.         {
  1000.           regsize = register_size (gdbarch, regn);
  1001.           /* Make sure we stay within block bounds.  */
  1002.           if (offset + regsize >= trace_regblock_size)
  1003.             break;
  1004.           if (regcache_register_status (regcache, regn) == REG_UNKNOWN)
  1005.             {
  1006.               if (regno == regn)
  1007.                 {
  1008.                   regcache_raw_supply (regcache, regno, regs + offset);
  1009.                   break;
  1010.                 }
  1011.               else if (regno == -1)
  1012.                 {
  1013.                   regcache_raw_supply (regcache, regn, regs + offset);
  1014.                 }
  1015.             }
  1016.           offset += regsize;
  1017.         }
  1018.     }
  1019.   else
  1020.     tracefile_fetch_registers (regcache, regno);
  1021. }

  1022. /* This is the implementation of target_ops method to_xfer_partial.
  1023.    Iterate over events whose name is "memory" in
  1024.    current frame, extract the address and length from events.  If
  1025.    OFFSET is within the range, read the contents from events to
  1026.    READBUF.  */

  1027. static enum target_xfer_status
  1028. ctf_xfer_partial (struct target_ops *ops, enum target_object object,
  1029.                   const char *annex, gdb_byte *readbuf,
  1030.                   const gdb_byte *writebuf, ULONGEST offset,
  1031.                   ULONGEST len, ULONGEST *xfered_len)
  1032. {
  1033.   /* We're only doing regular memory for now.  */
  1034.   if (object != TARGET_OBJECT_MEMORY)
  1035.     return -1;

  1036.   if (readbuf == NULL)
  1037.     error (_("ctf_xfer_partial: trace file is read-only"));

  1038.   if (get_traceframe_number () != -1)
  1039.     {
  1040.       struct bt_iter_pos *pos;
  1041.       int i = 0;
  1042.       enum target_xfer_status res;
  1043.       /* Records the lowest available address of all blocks that
  1044.          intersects the requested range.  */
  1045.       ULONGEST low_addr_available = 0;

  1046.       gdb_assert (ctf_iter != NULL);
  1047.       /* Save the current position.  */
  1048.       pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  1049.       gdb_assert (pos->type == BT_SEEK_RESTORE);

  1050.       /* Iterate through the traceframe's blocks, looking for
  1051.          memory.  */
  1052.       while (1)
  1053.         {
  1054.           ULONGEST amt;
  1055.           uint64_t maddr;
  1056.           uint16_t mlen;
  1057.           enum bfd_endian byte_order
  1058.             = gdbarch_byte_order (target_gdbarch ());
  1059.           const struct bt_definition *scope;
  1060.           const struct bt_definition *def;
  1061.           struct bt_ctf_event *event
  1062.             = bt_ctf_iter_read_event (ctf_iter);
  1063.           const char *name = bt_ctf_event_name (event);

  1064.           if (name == NULL || strcmp (name, "frame") == 0)
  1065.             break;
  1066.           else if (strcmp (name, "memory") != 0)
  1067.             {
  1068.               if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1069.                 break;

  1070.               continue;
  1071.             }

  1072.           scope = bt_ctf_get_top_level_scope (event,
  1073.                                               BT_EVENT_FIELDS);

  1074.           def = bt_ctf_get_field (event, scope, "address");
  1075.           maddr = bt_ctf_get_uint64 (def);
  1076.           def = bt_ctf_get_field (event, scope, "length");
  1077.           mlen = (uint16_t) bt_ctf_get_uint64 (def);

  1078.           /* If the block includes the first part of the desired
  1079.              range, return as much it has; GDB will re-request the
  1080.              remainder, which might be in a different block of this
  1081.              trace frame.  */
  1082.           if (maddr <= offset && offset < (maddr + mlen))
  1083.             {
  1084.               const struct bt_definition *array
  1085.                 = bt_ctf_get_field (event, scope, "contents");
  1086.               const struct bt_declaration *decl
  1087.                 = bt_ctf_get_decl_from_def (array);
  1088.               gdb_byte *contents;
  1089.               int k;

  1090.               contents = xmalloc (mlen);

  1091.               for (k = 0; k < mlen; k++)
  1092.                 {
  1093.                   const struct bt_definition *element
  1094.                     = bt_ctf_get_index (event, array, k);

  1095.                   contents[k] = (gdb_byte) bt_ctf_get_uint64 (element);
  1096.                 }

  1097.               amt = (maddr + mlen) - offset;
  1098.               if (amt > len)
  1099.                 amt = len;

  1100.               memcpy (readbuf, &contents[offset - maddr], amt);

  1101.               xfree (contents);

  1102.               /* Restore the position.  */
  1103.               bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  1104.               if (amt == 0)
  1105.                 return TARGET_XFER_EOF;
  1106.               else
  1107.                 {
  1108.                   *xfered_len = amt;
  1109.                   return TARGET_XFER_OK;
  1110.                 }
  1111.             }

  1112.           if (offset < maddr && maddr < (offset + len))
  1113.             if (low_addr_available == 0 || low_addr_available > maddr)
  1114.               low_addr_available = maddr;

  1115.           if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1116.             break;
  1117.         }

  1118.       /* Restore the position.  */
  1119.       bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  1120.       /* Requested memory is unavailable in the context of traceframes,
  1121.          and this address falls within a read-only section, fallback
  1122.          to reading from executable, up to LOW_ADDR_AVAILABLE  */
  1123.       if (offset < low_addr_available)
  1124.         len = min (len, low_addr_available - offset);
  1125.       res = exec_read_partial_read_only (readbuf, offset, len, xfered_len);

  1126.       if (res == TARGET_XFER_OK)
  1127.         return TARGET_XFER_OK;
  1128.       else
  1129.         {
  1130.           /* No use trying further, we know some memory starting
  1131.              at MEMADDR isn't available.  */
  1132.           *xfered_len = len;
  1133.           return TARGET_XFER_UNAVAILABLE;
  1134.         }
  1135.     }
  1136.   else
  1137.     {
  1138.       /* Fallback to reading from read-only sections.  */
  1139.       return section_table_read_available_memory (readbuf, offset, len, xfered_len);
  1140.     }
  1141. }

  1142. /* This is the implementation of target_ops method
  1143.    to_get_trace_state_variable_value.
  1144.    Iterate over events whose name is "tsv" in current frame.  When the
  1145.    trace variable is found, set the value of it to *VAL and return
  1146.    true, otherwise return false.  */

  1147. static int
  1148. ctf_get_trace_state_variable_value (struct target_ops *self,
  1149.                                     int tsvnum, LONGEST *val)
  1150. {
  1151.   struct bt_iter_pos *pos;
  1152.   int found = 0;

  1153.   gdb_assert (ctf_iter != NULL);
  1154.   /* Save the current position.  */
  1155.   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  1156.   gdb_assert (pos->type == BT_SEEK_RESTORE);

  1157.   /* Iterate through the traceframe's blocks, looking for 'V'
  1158.      block.  */
  1159.   while (1)
  1160.     {
  1161.       struct bt_ctf_event *event
  1162.         = bt_ctf_iter_read_event (ctf_iter);
  1163.       const char *name = bt_ctf_event_name (event);

  1164.       if (name == NULL || strcmp (name, "frame") == 0)
  1165.         break;
  1166.       else if (strcmp (name, "tsv") == 0)
  1167.         {
  1168.           const struct bt_definition *scope;
  1169.           const struct bt_definition *def;

  1170.           scope = bt_ctf_get_top_level_scope (event,
  1171.                                               BT_EVENT_FIELDS);

  1172.           def = bt_ctf_get_field (event, scope, "num");
  1173.           if (tsvnum == (int32_t) bt_ctf_get_uint64 (def))
  1174.             {
  1175.               def = bt_ctf_get_field (event, scope, "val");
  1176.               *val = bt_ctf_get_uint64 (def);

  1177.               found = 1;
  1178.             }
  1179.         }

  1180.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1181.         break;
  1182.     }

  1183.   /* Restore the position.  */
  1184.   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  1185.   return found;
  1186. }

  1187. /* Return the tracepoint number in "frame" event.  */

  1188. static int
  1189. ctf_get_tpnum_from_frame_event (struct bt_ctf_event *event)
  1190. {
  1191.   /* The packet context of events has a field "tpnum".  */
  1192.   const struct bt_definition *scope
  1193.     = bt_ctf_get_top_level_scope (event, BT_STREAM_PACKET_CONTEXT);
  1194.   uint64_t tpnum
  1195.     = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "tpnum"));

  1196.   return (int) tpnum;
  1197. }

  1198. /* Return the address at which the current frame was collected.  */

  1199. static CORE_ADDR
  1200. ctf_get_traceframe_address (void)
  1201. {
  1202.   struct bt_ctf_event *event = NULL;
  1203.   struct bt_iter_pos *pos;
  1204.   CORE_ADDR addr = 0;

  1205.   gdb_assert (ctf_iter != NULL);
  1206.   pos  = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  1207.   gdb_assert (pos->type == BT_SEEK_RESTORE);

  1208.   while (1)
  1209.     {
  1210.       const char *name;
  1211.       struct bt_ctf_event *event1;

  1212.       event1 = bt_ctf_iter_read_event (ctf_iter);

  1213.       name = bt_ctf_event_name (event1);

  1214.       if (name == NULL)
  1215.         break;
  1216.       else if (strcmp (name, "frame") == 0)
  1217.         {
  1218.           event = event1;
  1219.           break;
  1220.         }

  1221.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1222.         break;
  1223.     }

  1224.   if (event != NULL)
  1225.     {
  1226.       int tpnum = ctf_get_tpnum_from_frame_event (event);
  1227.       struct tracepoint *tp
  1228.         = get_tracepoint_by_number_on_target (tpnum);

  1229.       if (tp && tp->base.loc)
  1230.         addr = tp->base.loc->address;
  1231.     }

  1232.   /* Restore the position.  */
  1233.   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  1234.   return addr;
  1235. }

  1236. /* This is the implementation of target_ops method to_trace_find.
  1237.    Iterate the events whose name is "frame", extract the tracepoint
  1238.    number in it.  Return traceframe number when matched.  */

  1239. static int
  1240. ctf_trace_find (struct target_ops *self, enum trace_find_type type, int num,
  1241.                 CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
  1242. {
  1243.   int ret = -1;
  1244.   int tfnum = 0;
  1245.   int found = 0;
  1246.   struct bt_iter_pos pos;

  1247.   if (num == -1)
  1248.     {
  1249.       if (tpp != NULL)
  1250.         *tpp = -1;
  1251.       return -1;
  1252.     }

  1253.   gdb_assert (ctf_iter != NULL);
  1254.   /* Set iterator back to the start.  */
  1255.   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), start_pos);

  1256.   while (1)
  1257.     {
  1258.       int id;
  1259.       struct bt_ctf_event *event;
  1260.       const char *name;

  1261.       event = bt_ctf_iter_read_event (ctf_iter);

  1262.       name = bt_ctf_event_name (event);

  1263.       if (event == NULL || name == NULL)
  1264.         break;

  1265.       if (strcmp (name, "frame") == 0)
  1266.         {
  1267.           CORE_ADDR tfaddr;

  1268.           if (type == tfind_number)
  1269.             {
  1270.               /* Looking for a specific trace frame.  */
  1271.               if (tfnum == num)
  1272.                 found = 1;
  1273.             }
  1274.           else
  1275.             {
  1276.               /* Start from the _next_ trace frame.  */
  1277.               if (tfnum > get_traceframe_number ())
  1278.                 {
  1279.                   switch (type)
  1280.                     {
  1281.                     case tfind_tp:
  1282.                       {
  1283.                         struct tracepoint *tp = get_tracepoint (num);

  1284.                         if (tp != NULL
  1285.                             && (tp->number_on_target
  1286.                                 == ctf_get_tpnum_from_frame_event (event)))
  1287.                           found = 1;
  1288.                         break;
  1289.                       }
  1290.                     case tfind_pc:
  1291.                       tfaddr = ctf_get_traceframe_address ();
  1292.                       if (tfaddr == addr1)
  1293.                         found = 1;
  1294.                       break;
  1295.                     case tfind_range:
  1296.                       tfaddr = ctf_get_traceframe_address ();
  1297.                       if (addr1 <= tfaddr && tfaddr <= addr2)
  1298.                         found = 1;
  1299.                       break;
  1300.                     case tfind_outside:
  1301.                       tfaddr = ctf_get_traceframe_address ();
  1302.                       if (!(addr1 <= tfaddr && tfaddr <= addr2))
  1303.                         found = 1;
  1304.                       break;
  1305.                     default:
  1306.                       internal_error (__FILE__, __LINE__, _("unknown tfind type"));
  1307.                     }
  1308.                 }
  1309.             }
  1310.           if (found)
  1311.             {
  1312.               if (tpp != NULL)
  1313.                 *tpp = ctf_get_tpnum_from_frame_event (event);

  1314.               /* Skip the event "frame".  */
  1315.               bt_iter_next (bt_ctf_get_iter (ctf_iter));

  1316.               return tfnum;
  1317.             }
  1318.           tfnum++;
  1319.         }

  1320.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1321.         break;
  1322.     }

  1323.   return -1;
  1324. }

  1325. /* This is the implementation of target_ops method to_traceframe_info.
  1326.    Iterate the events whose name is "memory", in current
  1327.    frame, extract memory range information, and return them in
  1328.    traceframe_info.  */

  1329. static struct traceframe_info *
  1330. ctf_traceframe_info (struct target_ops *self)
  1331. {
  1332.   struct traceframe_info *info = XCNEW (struct traceframe_info);
  1333.   const char *name;
  1334.   struct bt_iter_pos *pos;

  1335.   gdb_assert (ctf_iter != NULL);
  1336.   /* Save the current position.  */
  1337.   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
  1338.   gdb_assert (pos->type == BT_SEEK_RESTORE);

  1339.   do
  1340.     {
  1341.       struct bt_ctf_event *event
  1342.         = bt_ctf_iter_read_event (ctf_iter);

  1343.       name = bt_ctf_event_name (event);

  1344.       if (name == NULL || strcmp (name, "register") == 0
  1345.           || strcmp (name, "frame") == 0)
  1346.         ;
  1347.       else if (strcmp (name, "memory") == 0)
  1348.         {
  1349.           const struct bt_definition *scope
  1350.             = bt_ctf_get_top_level_scope (event,
  1351.                                           BT_EVENT_FIELDS);
  1352.           const struct bt_definition *def;
  1353.           struct mem_range *r;

  1354.           r = VEC_safe_push (mem_range_s, info->memory, NULL);
  1355.           def = bt_ctf_get_field (event, scope, "address");
  1356.           r->start = bt_ctf_get_uint64 (def);

  1357.           def = bt_ctf_get_field (event, scope, "length");
  1358.           r->length = (uint16_t) bt_ctf_get_uint64 (def);
  1359.         }
  1360.       else if (strcmp (name, "tsv") == 0)
  1361.         {
  1362.           int vnum;
  1363.           const struct bt_definition *scope
  1364.             = bt_ctf_get_top_level_scope (event,
  1365.                                           BT_EVENT_FIELDS);
  1366.           const struct bt_definition *def;

  1367.           def = bt_ctf_get_field (event, scope, "num");
  1368.           vnum = (int) bt_ctf_get_int64 (def);
  1369.           VEC_safe_push (int, info->tvars, vnum);
  1370.         }
  1371.       else
  1372.         {
  1373.           warning (_("Unhandled trace block type (%s) "
  1374.                      "while building trace frame info."),
  1375.                    name);
  1376.         }

  1377.       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
  1378.         break;
  1379.     }
  1380.   while (name != NULL && strcmp (name, "frame") != 0);

  1381.   /* Restore the position.  */
  1382.   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);

  1383.   return info;
  1384. }

  1385. static void
  1386. init_ctf_ops (void)
  1387. {
  1388.   memset (&ctf_ops, 0, sizeof (ctf_ops));

  1389.   init_tracefile_ops (&ctf_ops);
  1390.   ctf_ops.to_shortname = "ctf";
  1391.   ctf_ops.to_longname = "CTF file";
  1392.   ctf_ops.to_doc = "Use a CTF directory as a target.\n\
  1393. Specify the filename of the CTF directory.";
  1394.   ctf_ops.to_open = ctf_open;
  1395.   ctf_ops.to_close = ctf_close;
  1396.   ctf_ops.to_fetch_registers = ctf_fetch_registers;
  1397.   ctf_ops.to_xfer_partial = ctf_xfer_partial;
  1398.   ctf_ops.to_files_info = ctf_files_info;
  1399.   ctf_ops.to_trace_find = ctf_trace_find;
  1400.   ctf_ops.to_get_trace_state_variable_value
  1401.     = ctf_get_trace_state_variable_value;
  1402.   ctf_ops.to_traceframe_info = ctf_traceframe_info;
  1403. }

  1404. #endif

  1405. /* -Wmissing-prototypes */

  1406. extern initialize_file_ftype _initialize_ctf;

  1407. /* module initialization */

  1408. void
  1409. _initialize_ctf (void)
  1410. {
  1411. #if HAVE_LIBBABELTRACE
  1412.   init_ctf_ops ();

  1413.   add_target_with_completer (&ctf_ops, filename_completer);
  1414. #endif
  1415. }