gdb/tracefile-tfile.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Trace file TFILE format support in GDB.

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

  3.    This file is part of GDB.

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

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

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

  14. #include "defs.h"
  15. #include "tracefile.h"
  16. #include "readline/tilde.h"
  17. #include "filestuff.h"
  18. #include "rsp-low.h" /* bin2hex */
  19. #include "regcache.h"
  20. #include "inferior.h"
  21. #include "gdbthread.h"
  22. #include "exec.h" /* exec_bfd */
  23. #include "completer.h"
  24. #include "filenames.h"

  25. #ifndef O_LARGEFILE
  26. #define O_LARGEFILE 0
  27. #endif

  28. /* TFILE trace writer.  */

  29. struct tfile_trace_file_writer
  30. {
  31.   struct trace_file_writer base;

  32.   /* File pointer to tfile trace file.  */
  33.   FILE *fp;
  34.   /* Path name of the tfile trace file.  */
  35.   char *pathname;
  36. };

  37. /* This is the implementation of trace_file_write_ops method
  38.    target_save.  We just call the generic target
  39.    target_save_trace_data to do target-side saving.  */

  40. static int
  41. tfile_target_save (struct trace_file_writer *self,
  42.                    const char *filename)
  43. {
  44.   int err = target_save_trace_data (filename);

  45.   return (err >= 0);
  46. }

  47. /* This is the implementation of trace_file_write_ops method
  48.    dtor.  */

  49. static void
  50. tfile_dtor (struct trace_file_writer *self)
  51. {
  52.   struct tfile_trace_file_writer *writer
  53.     = (struct tfile_trace_file_writer *) self;

  54.   xfree (writer->pathname);

  55.   if (writer->fp != NULL)
  56.     fclose (writer->fp);
  57. }

  58. /* This is the implementation of trace_file_write_ops method
  59.    start.  It creates the trace file FILENAME and registers some
  60.    cleanups.  */

  61. static void
  62. tfile_start (struct trace_file_writer *self, const char *filename)
  63. {
  64.   struct tfile_trace_file_writer *writer
  65.     = (struct tfile_trace_file_writer *) self;

  66.   writer->pathname = tilde_expand (filename);
  67.   writer->fp = gdb_fopen_cloexec (writer->pathname, "wb");
  68.   if (writer->fp == NULL)
  69.     error (_("Unable to open file '%s' for saving trace data (%s)"),
  70.            writer->pathname, safe_strerror (errno));
  71. }

  72. /* This is the implementation of trace_file_write_ops method
  73.    write_header.  Write the TFILE header.  */

  74. static void
  75. tfile_write_header (struct trace_file_writer *self)
  76. {
  77.   struct tfile_trace_file_writer *writer
  78.     = (struct tfile_trace_file_writer *) self;
  79.   int written;

  80.   /* Write a file header, with a high-bit-set char to indicate a
  81.      binary file, plus a hint as what this file is, and a version
  82.      number in case of future needs.  */
  83.   written = fwrite ("\x7fTRACE0\n", 8, 1, writer->fp);
  84.   if (written < 1)
  85.     perror_with_name (writer->pathname);
  86. }

  87. /* This is the implementation of trace_file_write_ops method
  88.    write_regblock_type.  Write the size of register block.  */

  89. static void
  90. tfile_write_regblock_type (struct trace_file_writer *self, int size)
  91. {
  92.   struct tfile_trace_file_writer *writer
  93.     = (struct tfile_trace_file_writer *) self;

  94.   fprintf (writer->fp, "R %x\n", size);
  95. }

  96. /* This is the implementation of trace_file_write_ops method
  97.    write_status.  */

  98. static void
  99. tfile_write_status (struct trace_file_writer *self,
  100.                     struct trace_status *ts)
  101. {
  102.   struct tfile_trace_file_writer *writer
  103.     = (struct tfile_trace_file_writer *) self;

  104.   fprintf (writer->fp, "status %c;%s",
  105.            (ts->running ? '1' : '0'), stop_reason_names[ts->stop_reason]);
  106.   if (ts->stop_reason == tracepoint_error
  107.       || ts->stop_reason == tstop_command)
  108.     {
  109.       char *buf = (char *) alloca (strlen (ts->stop_desc) * 2 + 1);

  110.       bin2hex ((gdb_byte *) ts->stop_desc, buf, strlen (ts->stop_desc));
  111.       fprintf (writer->fp, ":%s", buf);
  112.     }
  113.   fprintf (writer->fp, ":%x", ts->stopping_tracepoint);
  114.   if (ts->traceframe_count >= 0)
  115.     fprintf (writer->fp, ";tframes:%x", ts->traceframe_count);
  116.   if (ts->traceframes_created >= 0)
  117.     fprintf (writer->fp, ";tcreated:%x", ts->traceframes_created);
  118.   if (ts->buffer_free >= 0)
  119.     fprintf (writer->fp, ";tfree:%x", ts->buffer_free);
  120.   if (ts->buffer_size >= 0)
  121.     fprintf (writer->fp, ";tsize:%x", ts->buffer_size);
  122.   if (ts->disconnected_tracing)
  123.     fprintf (writer->fp, ";disconn:%x", ts->disconnected_tracing);
  124.   if (ts->circular_buffer)
  125.     fprintf (writer->fp, ";circular:%x", ts->circular_buffer);
  126.   if (ts->start_time)
  127.     {
  128.       fprintf (writer->fp, ";starttime:%s",
  129.       phex_nz (ts->start_time, sizeof (ts->start_time)));
  130.     }
  131.   if (ts->stop_time)
  132.     {
  133.       fprintf (writer->fp, ";stoptime:%s",
  134.       phex_nz (ts->stop_time, sizeof (ts->stop_time)));
  135.     }
  136.   if (ts->notes != NULL)
  137.     {
  138.       char *buf = (char *) alloca (strlen (ts->notes) * 2 + 1);

  139.       bin2hex ((gdb_byte *) ts->notes, buf, strlen (ts->notes));
  140.       fprintf (writer->fp, ";notes:%s", buf);
  141.     }
  142.   if (ts->user_name != NULL)
  143.     {
  144.       char *buf = (char *) alloca (strlen (ts->user_name) * 2 + 1);

  145.       bin2hex ((gdb_byte *) ts->user_name, buf, strlen (ts->user_name));
  146.       fprintf (writer->fp, ";username:%s", buf);
  147.     }
  148.   fprintf (writer->fp, "\n");
  149. }

  150. /* This is the implementation of trace_file_write_ops method
  151.    write_uploaded_tsv.  */

  152. static void
  153. tfile_write_uploaded_tsv (struct trace_file_writer *self,
  154.                           struct uploaded_tsv *utsv)
  155. {
  156.   char *buf = "";
  157.   struct tfile_trace_file_writer *writer
  158.     = (struct tfile_trace_file_writer *) self;

  159.   if (utsv->name)
  160.     {
  161.       buf = (char *) xmalloc (strlen (utsv->name) * 2 + 1);
  162.       bin2hex ((gdb_byte *) (utsv->name), buf, strlen (utsv->name));
  163.     }

  164.   fprintf (writer->fp, "tsv %x:%s:%x:%s\n",
  165.            utsv->number, phex_nz (utsv->initial_value, 8),
  166.            utsv->builtin, buf);

  167.   if (utsv->name)
  168.     xfree (buf);
  169. }

  170. #define MAX_TRACE_UPLOAD 2000

  171. /* This is the implementation of trace_file_write_ops method
  172.    write_uploaded_tp.  */

  173. static void
  174. tfile_write_uploaded_tp (struct trace_file_writer *self,
  175.                          struct uploaded_tp *utp)
  176. {
  177.   struct tfile_trace_file_writer *writer
  178.     = (struct tfile_trace_file_writer *) self;
  179.   int a;
  180.   char *act;
  181.   char buf[MAX_TRACE_UPLOAD];

  182.   fprintf (writer->fp, "tp T%x:%s:%c:%x:%x",
  183.            utp->number, phex_nz (utp->addr, sizeof (utp->addr)),
  184.            (utp->enabled ? 'E' : 'D'), utp->step, utp->pass);
  185.   if (utp->type == bp_fast_tracepoint)
  186.     fprintf (writer->fp, ":F%x", utp->orig_size);
  187.   if (utp->cond)
  188.     fprintf (writer->fp,
  189.              ":X%x,%s", (unsigned int) strlen (utp->cond) / 2,
  190.              utp->cond);
  191.   fprintf (writer->fp, "\n");
  192.   for (a = 0; VEC_iterate (char_ptr, utp->actions, a, act); ++a)
  193.     fprintf (writer->fp, "tp A%x:%s:%s\n",
  194.              utp->number, phex_nz (utp->addr, sizeof (utp->addr)), act);
  195.   for (a = 0; VEC_iterate (char_ptr, utp->step_actions, a, act); ++a)
  196.     fprintf (writer->fp, "tp S%x:%s:%s\n",
  197.              utp->number, phex_nz (utp->addr, sizeof (utp->addr)), act);
  198.   if (utp->at_string)
  199.     {
  200.       encode_source_string (utp->number, utp->addr,
  201.                             "at", utp->at_string, buf, MAX_TRACE_UPLOAD);
  202.       fprintf (writer->fp, "tp Z%s\n", buf);
  203.     }
  204.   if (utp->cond_string)
  205.     {
  206.       encode_source_string (utp->number, utp->addr,
  207.                             "cond", utp->cond_string,
  208.                             buf, MAX_TRACE_UPLOAD);
  209.       fprintf (writer->fp, "tp Z%s\n", buf);
  210.     }
  211.   for (a = 0; VEC_iterate (char_ptr, utp->cmd_strings, a, act); ++a)
  212.     {
  213.       encode_source_string (utp->number, utp->addr, "cmd", act,
  214.                             buf, MAX_TRACE_UPLOAD);
  215.       fprintf (writer->fp, "tp Z%s\n", buf);
  216.     }
  217.   fprintf (writer->fp, "tp V%x:%s:%x:%s\n",
  218.            utp->number, phex_nz (utp->addr, sizeof (utp->addr)),
  219.            utp->hit_count,
  220.            phex_nz (utp->traceframe_usage,
  221.                     sizeof (utp->traceframe_usage)));
  222. }

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

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

  230.   fprintf (writer->fp, "\n");
  231. }

  232. /* This is the implementation of trace_file_write_ops method
  233.    write_raw_data.  */

  234. static void
  235. tfile_write_raw_data (struct trace_file_writer *self, gdb_byte *buf,
  236.                       LONGEST len)
  237. {
  238.   struct tfile_trace_file_writer *writer
  239.     = (struct tfile_trace_file_writer *) self;

  240.   if (fwrite (buf, len, 1, writer->fp) < 1)
  241.     perror_with_name (writer->pathname);
  242. }

  243. /* This is the implementation of trace_file_write_ops method
  244.    end.  */

  245. static void
  246. tfile_end (struct trace_file_writer *self)
  247. {
  248.   struct tfile_trace_file_writer *writer
  249.     = (struct tfile_trace_file_writer *) self;
  250.   uint32_t gotten = 0;

  251.   /* Mark the end of trace data.  */
  252.   if (fwrite (&gotten, 4, 1, writer->fp) < 1)
  253.     perror_with_name (writer->pathname);
  254. }

  255. /* Operations to write trace buffers into TFILE format.  */

  256. static const struct trace_file_write_ops tfile_write_ops =
  257. {
  258.   tfile_dtor,
  259.   tfile_target_save,
  260.   tfile_start,
  261.   tfile_write_header,
  262.   tfile_write_regblock_type,
  263.   tfile_write_status,
  264.   tfile_write_uploaded_tsv,
  265.   tfile_write_uploaded_tp,
  266.   tfile_write_definition_end,
  267.   tfile_write_raw_data,
  268.   NULL,
  269.   tfile_end,
  270. };

  271. /* Return a trace writer for TFILE format.  */

  272. struct trace_file_writer *
  273. tfile_trace_file_writer_new (void)
  274. {
  275.   struct tfile_trace_file_writer *writer
  276.     = xmalloc (sizeof (struct tfile_trace_file_writer));

  277.   writer->base.ops = &tfile_write_ops;
  278.   writer->fp = NULL;
  279.   writer->pathname = NULL;

  280.   return (struct trace_file_writer *) writer;
  281. }

  282. /* target tfile command */

  283. static struct target_ops tfile_ops;

  284. /* Fill in tfile_ops with its defined operations and properties.  */

  285. #define TRACE_HEADER_SIZE 8

  286. #define TFILE_PID (1)

  287. static char *trace_filename;
  288. static int trace_fd = -1;
  289. static off_t trace_frames_offset;
  290. static off_t cur_offset;
  291. static int cur_data_size;
  292. int trace_regblock_size;

  293. static void tfile_interp_line (char *line,
  294.                                struct uploaded_tp **utpp,
  295.                                struct uploaded_tsv **utsvp);

  296. /* Read SIZE bytes into READBUF from the trace frame, starting at
  297.    TRACE_FD's current position.  Note that this call `read'
  298.    underneath, hence it advances the file's seek position.  Throws an
  299.    error if the `read' syscall fails, or less than SIZE bytes are
  300.    read.  */

  301. static void
  302. tfile_read (gdb_byte *readbuf, int size)
  303. {
  304.   int gotten;

  305.   gotten = read (trace_fd, readbuf, size);
  306.   if (gotten < 0)
  307.     perror_with_name (trace_filename);
  308.   else if (gotten < size)
  309.     error (_("Premature end of file while reading trace file"));
  310. }

  311. static void
  312. tfile_open (const char *arg, int from_tty)
  313. {
  314.   volatile struct gdb_exception ex;
  315.   char *temp;
  316.   struct cleanup *old_chain;
  317.   int flags;
  318.   int scratch_chan;
  319.   char header[TRACE_HEADER_SIZE];
  320.   char linebuf[1000]; /* Should be max remote packet size or so.  */
  321.   gdb_byte byte;
  322.   int bytes, i;
  323.   struct trace_status *ts;
  324.   struct uploaded_tp *uploaded_tps = NULL;
  325.   struct uploaded_tsv *uploaded_tsvs = NULL;
  326.   char *filename;

  327.   target_preopen (from_tty);
  328.   if (!arg)
  329.     error (_("No trace file specified."));

  330.   filename = tilde_expand (arg);
  331.   if (!IS_ABSOLUTE_PATH(filename))
  332.     {
  333.       temp = concat (current_directory, "/", filename, (char *) NULL);
  334.       xfree (filename);
  335.       filename = temp;
  336.     }

  337.   old_chain = make_cleanup (xfree, filename);

  338.   flags = O_BINARY | O_LARGEFILE;
  339.   flags |= O_RDONLY;
  340.   scratch_chan = gdb_open_cloexec (filename, flags, 0);
  341.   if (scratch_chan < 0)
  342.     perror_with_name (filename);

  343.   /* Looks semi-reasonable.  Toss the old trace file and work on the new.  */

  344.   discard_cleanups (old_chain);        /* Don't free filename any more.  */
  345.   unpush_target (&tfile_ops);

  346.   trace_filename = xstrdup (filename);
  347.   trace_fd = scratch_chan;

  348.   bytes = 0;
  349.   /* Read the file header and test for validity.  */
  350.   tfile_read ((gdb_byte *) &header, TRACE_HEADER_SIZE);

  351.   bytes += TRACE_HEADER_SIZE;
  352.   if (!(header[0] == 0x7f
  353.         && (strncmp (header + 1, "TRACE0\n", 7) == 0)))
  354.     error (_("File is not a valid trace file."));

  355.   push_target (&tfile_ops);

  356.   trace_regblock_size = 0;
  357.   ts = current_trace_status ();
  358.   /* We know we're working with a file.  Record its name.  */
  359.   ts->filename = trace_filename;
  360.   /* Set defaults in case there is no status line.  */
  361.   ts->running_known = 0;
  362.   ts->stop_reason = trace_stop_reason_unknown;
  363.   ts->traceframe_count = -1;
  364.   ts->buffer_free = 0;
  365.   ts->disconnected_tracing = 0;
  366.   ts->circular_buffer = 0;

  367.   TRY_CATCH (ex, RETURN_MASK_ALL)
  368.     {
  369.       /* Read through a section of newline-terminated lines that
  370.          define things like tracepoints.  */
  371.       i = 0;
  372.       while (1)
  373.         {
  374.           tfile_read (&byte, 1);

  375.           ++bytes;
  376.           if (byte == '\n')
  377.             {
  378.               /* Empty line marks end of the definition section.  */
  379.               if (i == 0)
  380.                 break;
  381.               linebuf[i] = '\0';
  382.               i = 0;
  383.               tfile_interp_line (linebuf, &uploaded_tps, &uploaded_tsvs);
  384.             }
  385.           else
  386.             linebuf[i++] = byte;
  387.           if (i >= 1000)
  388.             error (_("Excessively long lines in trace file"));
  389.         }

  390.       /* Record the starting offset of the binary trace data.  */
  391.       trace_frames_offset = bytes;

  392.       /* If we don't have a blocksize, we can't interpret the
  393.          traceframes.  */
  394.       if (trace_regblock_size == 0)
  395.         error (_("No register block size recorded in trace file"));
  396.     }
  397.   if (ex.reason < 0)
  398.     {
  399.       /* Remove the partially set up target.  */
  400.       unpush_target (&tfile_ops);
  401.       throw_exception (ex);
  402.     }

  403.   inferior_appeared (current_inferior (), TFILE_PID);
  404.   inferior_ptid = pid_to_ptid (TFILE_PID);
  405.   add_thread_silent (inferior_ptid);

  406.   if (ts->traceframe_count <= 0)
  407.     warning (_("No traceframes present in this file."));

  408.   /* Add the file's tracepoints and variables into the current mix.  */

  409.   /* Get trace state variables first, they may be checked when parsing
  410.      uploaded commands.  */
  411.   merge_uploaded_trace_state_variables (&uploaded_tsvs);

  412.   merge_uploaded_tracepoints (&uploaded_tps);

  413.   post_create_inferior (&tfile_ops, from_tty);
  414. }

  415. /* Interpret the given line from the definitions part of the trace
  416.    file.  */

  417. static void
  418. tfile_interp_line (char *line, struct uploaded_tp **utpp,
  419.                    struct uploaded_tsv **utsvp)
  420. {
  421.   char *p = line;

  422.   if (strncmp (p, "R ", strlen ("R ")) == 0)
  423.     {
  424.       p += strlen ("R ");
  425.       trace_regblock_size = strtol (p, &p, 16);
  426.     }
  427.   else if (strncmp (p, "status ", strlen ("status ")) == 0)
  428.     {
  429.       p += strlen ("status ");
  430.       parse_trace_status (p, current_trace_status ());
  431.     }
  432.   else if (strncmp (p, "tp ", strlen ("tp ")) == 0)
  433.     {
  434.       p += strlen ("tp ");
  435.       parse_tracepoint_definition (p, utpp);
  436.     }
  437.   else if (strncmp (p, "tsv ", strlen ("tsv ")) == 0)
  438.     {
  439.       p += strlen ("tsv ");
  440.       parse_tsv_definition (p, utsvp);
  441.     }
  442.   else
  443.     warning (_("Ignoring trace file definition \"%s\""), line);
  444. }

  445. /* Close the trace file and generally clean up.  */

  446. static void
  447. tfile_close (struct target_ops *self)
  448. {
  449.   int pid;

  450.   if (trace_fd < 0)
  451.     return;

  452.   pid = ptid_get_pid (inferior_ptid);
  453.   inferior_ptid = null_ptid;        /* Avoid confusion from thread stuff.  */
  454.   exit_inferior_silent (pid);

  455.   close (trace_fd);
  456.   trace_fd = -1;
  457.   xfree (trace_filename);
  458.   trace_filename = NULL;

  459.   trace_reset_local_state ();
  460. }

  461. static void
  462. tfile_files_info (struct target_ops *t)
  463. {
  464.   printf_filtered ("\t`%s'\n", trace_filename);
  465. }

  466. static void
  467. tfile_get_tracepoint_status (struct target_ops *self,
  468.                              struct breakpoint *tp, struct uploaded_tp *utp)
  469. {
  470.   /* Other bits of trace status were collected as part of opening the
  471.      trace files, so nothing to do here.  */
  472. }

  473. /* Given the position of a traceframe in the file, figure out what
  474.    address the frame was collected at.  This would normally be the
  475.    value of a collected PC register, but if not available, we
  476.    improvise.  */

  477. static CORE_ADDR
  478. tfile_get_traceframe_address (off_t tframe_offset)
  479. {
  480.   CORE_ADDR addr = 0;
  481.   short tpnum;
  482.   struct tracepoint *tp;
  483.   off_t saved_offset = cur_offset;

  484.   /* FIXME dig pc out of collected registers.  */

  485.   /* Fall back to using tracepoint address.  */
  486.   lseek (trace_fd, tframe_offset, SEEK_SET);
  487.   tfile_read ((gdb_byte *) &tpnum, 2);
  488.   tpnum = (short) extract_signed_integer ((gdb_byte *) &tpnum, 2,
  489.                                           gdbarch_byte_order
  490.                                               (target_gdbarch ()));

  491.   tp = get_tracepoint_by_number_on_target (tpnum);
  492.   /* FIXME this is a poor heuristic if multiple locations.  */
  493.   if (tp && tp->base.loc)
  494.     addr = tp->base.loc->address;

  495.   /* Restore our seek position.  */
  496.   cur_offset = saved_offset;
  497.   lseek (trace_fd, cur_offset, SEEK_SET);
  498.   return addr;
  499. }

  500. /* Given a type of search and some parameters, scan the collection of
  501.    traceframes in the file looking for a match.  When found, return
  502.    both the traceframe and tracepoint number, otherwise -1 for
  503.    each.  */

  504. static int
  505. tfile_trace_find (struct target_ops *self, enum trace_find_type type, int num,
  506.                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
  507. {
  508.   short tpnum;
  509.   int tfnum = 0, found = 0;
  510.   unsigned int data_size;
  511.   struct tracepoint *tp;
  512.   off_t offset, tframe_offset;
  513.   CORE_ADDR tfaddr;

  514.   if (num == -1)
  515.     {
  516.       if (tpp)
  517.         *tpp = -1;
  518.       return -1;
  519.     }

  520.   lseek (trace_fd, trace_frames_offset, SEEK_SET);
  521.   offset = trace_frames_offset;
  522.   while (1)
  523.     {
  524.       tframe_offset = offset;
  525.       tfile_read ((gdb_byte *) &tpnum, 2);
  526.       tpnum = (short) extract_signed_integer ((gdb_byte *) &tpnum, 2,
  527.                                               gdbarch_byte_order
  528.                                                   (target_gdbarch ()));
  529.       offset += 2;
  530.       if (tpnum == 0)
  531.         break;
  532.       tfile_read ((gdb_byte *) &data_size, 4);
  533.       data_size = (unsigned int) extract_unsigned_integer
  534.                                      ((gdb_byte *) &data_size, 4,
  535.                                       gdbarch_byte_order (target_gdbarch ()));
  536.       offset += 4;

  537.       if (type == tfind_number)
  538.         {
  539.           /* Looking for a specific trace frame.  */
  540.           if (tfnum == num)
  541.             found = 1;
  542.         }
  543.       else
  544.         {
  545.           /* Start from the _next_ trace frame.  */
  546.           if (tfnum > get_traceframe_number ())
  547.             {
  548.               switch (type)
  549.                 {
  550.                 case tfind_pc:
  551.                   tfaddr = tfile_get_traceframe_address (tframe_offset);
  552.                   if (tfaddr == addr1)
  553.                     found = 1;
  554.                   break;
  555.                 case tfind_tp:
  556.                   tp = get_tracepoint (num);
  557.                   if (tp && tpnum == tp->number_on_target)
  558.                     found = 1;
  559.                   break;
  560.                 case tfind_range:
  561.                   tfaddr = tfile_get_traceframe_address (tframe_offset);
  562.                   if (addr1 <= tfaddr && tfaddr <= addr2)
  563.                     found = 1;
  564.                   break;
  565.                 case tfind_outside:
  566.                   tfaddr = tfile_get_traceframe_address (tframe_offset);
  567.                   if (!(addr1 <= tfaddr && tfaddr <= addr2))
  568.                     found = 1;
  569.                   break;
  570.                 default:
  571.                   internal_error (__FILE__, __LINE__, _("unknown tfind type"));
  572.                 }
  573.             }
  574.         }

  575.       if (found)
  576.         {
  577.           if (tpp)
  578.             *tpp = tpnum;
  579.           cur_offset = offset;
  580.           cur_data_size = data_size;

  581.           return tfnum;
  582.         }
  583.       /* Skip past the traceframe's data.  */
  584.       lseek (trace_fd, data_size, SEEK_CUR);
  585.       offset += data_size;
  586.       /* Update our own count of traceframes.  */
  587.       ++tfnum;
  588.     }
  589.   /* Did not find what we were looking for.  */
  590.   if (tpp)
  591.     *tpp = -1;
  592.   return -1;
  593. }

  594. /* Prototype of the callback passed to tframe_walk_blocks.  */
  595. typedef int (*walk_blocks_callback_func) (char blocktype, void *data);

  596. /* Callback for traceframe_walk_blocks, used to find a given block
  597.    type in a traceframe.  */

  598. static int
  599. match_blocktype (char blocktype, void *data)
  600. {
  601.   char *wantedp = data;

  602.   if (*wantedp == blocktype)
  603.     return 1;

  604.   return 0;
  605. }

  606. /* Walk over all traceframe block starting at POS offset from
  607.    CUR_OFFSET, and call CALLBACK for each block found, passing in DATA
  608.    unmodified.  If CALLBACK returns true, this returns the position in
  609.    the traceframe where the block is found, relative to the start of
  610.    the traceframe (cur_offset).  Returns -1 if no callback call
  611.    returned true, indicating that all blocks have been walked.  */

  612. static int
  613. traceframe_walk_blocks (walk_blocks_callback_func callback,
  614.                         int pos, void *data)
  615. {
  616.   /* Iterate through a traceframe's blocks, looking for a block of the
  617.      requested type.  */

  618.   lseek (trace_fd, cur_offset + pos, SEEK_SET);
  619.   while (pos < cur_data_size)
  620.     {
  621.       unsigned short mlen;
  622.       char block_type;

  623.       tfile_read ((gdb_byte *) &block_type, 1);

  624.       ++pos;

  625.       if ((*callback) (block_type, data))
  626.         return pos;

  627.       switch (block_type)
  628.         {
  629.         case 'R':
  630.           lseek (trace_fd, cur_offset + pos + trace_regblock_size, SEEK_SET);
  631.           pos += trace_regblock_size;
  632.           break;
  633.         case 'M':
  634.           lseek (trace_fd, cur_offset + pos + 8, SEEK_SET);
  635.           tfile_read ((gdb_byte *) &mlen, 2);
  636.           mlen = (unsigned short)
  637.                 extract_unsigned_integer ((gdb_byte *) &mlen, 2,
  638.                                           gdbarch_byte_order
  639.                                               (target_gdbarch ()));
  640.           lseek (trace_fd, mlen, SEEK_CUR);
  641.           pos += (8 + 2 + mlen);
  642.           break;
  643.         case 'V':
  644.           lseek (trace_fd, cur_offset + pos + 4 + 8, SEEK_SET);
  645.           pos += (4 + 8);
  646.           break;
  647.         default:
  648.           error (_("Unknown block type '%c' (0x%x) in trace frame"),
  649.                  block_type, block_type);
  650.           break;
  651.         }
  652.     }

  653.   return -1;
  654. }

  655. /* Convenience wrapper around traceframe_walk_blocks.  Looks for the
  656.    position offset of a block of type TYPE_WANTED in the current trace
  657.    frame, starting at POS.  Returns -1 if no such block was found.  */

  658. static int
  659. traceframe_find_block_type (char type_wanted, int pos)
  660. {
  661.   return traceframe_walk_blocks (match_blocktype, pos, &type_wanted);
  662. }

  663. /* Look for a block of saved registers in the traceframe, and get the
  664.    requested register from it.  */

  665. static void
  666. tfile_fetch_registers (struct target_ops *ops,
  667.                        struct regcache *regcache, int regno)
  668. {
  669.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  670.   int offset, regn, regsize;

  671.   /* An uninitialized reg size says we're not going to be
  672.      successful at getting register blocks.  */
  673.   if (!trace_regblock_size)
  674.     return;

  675.   if (traceframe_find_block_type ('R', 0) >= 0)
  676.     {
  677.       gdb_byte *regs = alloca (trace_regblock_size);

  678.       tfile_read (regs, trace_regblock_size);

  679.       /* Assume the block is laid out in GDB register number order,
  680.          each register with the size that it has in GDB.  */
  681.       offset = 0;
  682.       for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
  683.         {
  684.           regsize = register_size (gdbarch, regn);
  685.           /* Make sure we stay within block bounds.  */
  686.           if (offset + regsize >= trace_regblock_size)
  687.             break;
  688.           if (regcache_register_status (regcache, regn) == REG_UNKNOWN)
  689.             {
  690.               if (regno == regn)
  691.                 {
  692.                   regcache_raw_supply (regcache, regno, regs + offset);
  693.                   break;
  694.                 }
  695.               else if (regno == -1)
  696.                 {
  697.                   regcache_raw_supply (regcache, regn, regs + offset);
  698.                 }
  699.             }
  700.           offset += regsize;
  701.         }
  702.     }
  703.   else
  704.     tracefile_fetch_registers (regcache, regno);
  705. }

  706. static enum target_xfer_status
  707. tfile_xfer_partial (struct target_ops *ops, enum target_object object,
  708.                     const char *annex, gdb_byte *readbuf,
  709.                     const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  710.                     ULONGEST *xfered_len)
  711. {
  712.   /* We're only doing regular memory for now.  */
  713.   if (object != TARGET_OBJECT_MEMORY)
  714.     return TARGET_XFER_E_IO;

  715.   if (readbuf == NULL)
  716.     error (_("tfile_xfer_partial: trace file is read-only"));

  717.   if (get_traceframe_number () != -1)
  718.     {
  719.       int pos = 0;
  720.       enum target_xfer_status res;
  721.       /* Records the lowest available address of all blocks that
  722.          intersects the requested range.  */
  723.       ULONGEST low_addr_available = 0;

  724.       /* Iterate through the traceframe's blocks, looking for
  725.          memory.  */
  726.       while ((pos = traceframe_find_block_type ('M', pos)) >= 0)
  727.         {
  728.           ULONGEST maddr, amt;
  729.           unsigned short mlen;
  730.           enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());

  731.           tfile_read ((gdb_byte *) &maddr, 8);
  732.           maddr = extract_unsigned_integer ((gdb_byte *) &maddr, 8,
  733.                                             byte_order);
  734.           tfile_read ((gdb_byte *) &mlen, 2);
  735.           mlen = (unsigned short)
  736.             extract_unsigned_integer ((gdb_byte *) &mlen, 2, byte_order);

  737.           /* If the block includes the first part of the desired
  738.              range, return as much it has; GDB will re-request the
  739.              remainder, which might be in a different block of this
  740.              trace frame.  */
  741.           if (maddr <= offset && offset < (maddr + mlen))
  742.             {
  743.               amt = (maddr + mlen) - offset;
  744.               if (amt > len)
  745.                 amt = len;

  746.               if (maddr != offset)
  747.                 lseek (trace_fd, offset - maddr, SEEK_CUR);
  748.               tfile_read (readbuf, amt);
  749.               *xfered_len = amt;
  750.               return TARGET_XFER_OK;
  751.             }

  752.           if (offset < maddr && maddr < (offset + len))
  753.             if (low_addr_available == 0 || low_addr_available > maddr)
  754.               low_addr_available = maddr;

  755.           /* Skip over this block.  */
  756.           pos += (8 + 2 + mlen);
  757.         }

  758.       /* Requested memory is unavailable in the context of traceframes,
  759.          and this address falls within a read-only section, fallback
  760.          to reading from executable, up to LOW_ADDR_AVAILABLE.  */
  761.       if (offset < low_addr_available)
  762.         len = min (len, low_addr_available - offset);
  763.       res = exec_read_partial_read_only (readbuf, offset, len, xfered_len);

  764.       if (res == TARGET_XFER_OK)
  765.         return TARGET_XFER_OK;
  766.       else
  767.         {
  768.           /* No use trying further, we know some memory starting
  769.              at MEMADDR isn't available.  */
  770.           *xfered_len = len;
  771.           return TARGET_XFER_UNAVAILABLE;
  772.         }
  773.     }
  774.   else
  775.     {
  776.       /* Fallback to reading from read-only sections.  */
  777.       return section_table_read_available_memory (readbuf, offset, len,
  778.                                                   xfered_len);
  779.     }
  780. }

  781. /* Iterate through the blocks of a trace frame, looking for a 'V'
  782.    block with a matching tsv number.  */

  783. static int
  784. tfile_get_trace_state_variable_value (struct target_ops *self,
  785.                                       int tsvnum, LONGEST *val)
  786. {
  787.   int pos;
  788.   int found = 0;

  789.   /* Iterate over blocks in current frame and find the last 'V'
  790.      block in which tsv number is TSVNUM.  In one trace frame, there
  791.      may be multiple 'V' blocks created for a given trace variable,
  792.      and the last matched 'V' block contains the updated value.  */
  793.   pos = 0;
  794.   while ((pos = traceframe_find_block_type ('V', pos)) >= 0)
  795.     {
  796.       int vnum;

  797.       tfile_read ((gdb_byte *) &vnum, 4);
  798.       vnum = (int) extract_signed_integer ((gdb_byte *) &vnum, 4,
  799.                                            gdbarch_byte_order
  800.                                            (target_gdbarch ()));
  801.       if (tsvnum == vnum)
  802.         {
  803.           tfile_read ((gdb_byte *) val, 8);
  804.           *val = extract_signed_integer ((gdb_byte *) val, 8,
  805.                                          gdbarch_byte_order
  806.                                          (target_gdbarch ()));
  807.           found = 1;
  808.         }
  809.       pos += (4 + 8);
  810.     }

  811.   return found;
  812. }

  813. /* Callback for traceframe_walk_blocks.  Builds a traceframe_info
  814.    object for the tfile target's current traceframe.  */

  815. static int
  816. build_traceframe_info (char blocktype, void *data)
  817. {
  818.   struct traceframe_info *info = data;

  819.   switch (blocktype)
  820.     {
  821.     case 'M':
  822.       {
  823.         struct mem_range *r;
  824.         ULONGEST maddr;
  825.         unsigned short mlen;

  826.         tfile_read ((gdb_byte *) &maddr, 8);
  827.         maddr = extract_unsigned_integer ((gdb_byte *) &maddr, 8,
  828.                                           gdbarch_byte_order
  829.                                           (target_gdbarch ()));
  830.         tfile_read ((gdb_byte *) &mlen, 2);
  831.         mlen = (unsigned short)
  832.                 extract_unsigned_integer ((gdb_byte *) &mlen,
  833.                                           2, gdbarch_byte_order
  834.                                           (target_gdbarch ()));

  835.         r = VEC_safe_push (mem_range_s, info->memory, NULL);

  836.         r->start = maddr;
  837.         r->length = mlen;
  838.         break;
  839.       }
  840.     case 'V':
  841.       {
  842.         int vnum;

  843.         tfile_read ((gdb_byte *) &vnum, 4);
  844.         VEC_safe_push (int, info->tvars, vnum);
  845.       }
  846.     case 'R':
  847.     case 'S':
  848.       {
  849.         break;
  850.       }
  851.     default:
  852.       warning (_("Unhandled trace block type (%d) '%c ' "
  853.                  "while building trace frame info."),
  854.                blocktype, blocktype);
  855.       break;
  856.     }

  857.   return 0;
  858. }

  859. static struct traceframe_info *
  860. tfile_traceframe_info (struct target_ops *self)
  861. {
  862.   struct traceframe_info *info = XCNEW (struct traceframe_info);

  863.   traceframe_walk_blocks (build_traceframe_info, 0, info);
  864.   return info;
  865. }

  866. static void
  867. init_tfile_ops (void)
  868. {
  869.   init_tracefile_ops (&tfile_ops);

  870.   tfile_ops.to_shortname = "tfile";
  871.   tfile_ops.to_longname = "Local trace dump file";
  872.   tfile_ops.to_doc
  873.     = "Use a trace file as a target.  Specify the filename of the trace file.";
  874.   tfile_ops.to_open = tfile_open;
  875.   tfile_ops.to_close = tfile_close;
  876.   tfile_ops.to_fetch_registers = tfile_fetch_registers;
  877.   tfile_ops.to_xfer_partial = tfile_xfer_partial;
  878.   tfile_ops.to_files_info = tfile_files_info;
  879.   tfile_ops.to_get_tracepoint_status = tfile_get_tracepoint_status;
  880.   tfile_ops.to_trace_find = tfile_trace_find;
  881.   tfile_ops.to_get_trace_state_variable_value
  882.     = tfile_get_trace_state_variable_value;
  883.   tfile_ops.to_traceframe_info = tfile_traceframe_info;
  884. }

  885. extern initialize_file_ftype _initialize_tracefile_tfile;

  886. void
  887. _initialize_tracefile_tfile (void)
  888. {
  889.   init_tfile_ops ();

  890.   add_target_with_completer (&tfile_ops, filename_completer);
  891. }