Convert struct target_ops to C++
[external/binutils.git] / gdb / ctf.c
1 /* CTF format support.
2
3    Copyright (C) 2012-2018 Free Software Foundation, Inc.
4    Contributed by Hui Zhu <hui_zhu@mentor.com>
5    Contributed by Yao Qi <yao@codesourcery.com>
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "ctf.h"
24 #include "tracepoint.h"
25 #include "regcache.h"
26 #include <sys/stat.h>
27 #include "exec.h"
28 #include "completer.h"
29 #include "inferior.h"
30 #include "gdbthread.h"
31 #include "tracefile.h"
32 #include <ctype.h>
33 #include <algorithm>
34
35 /* The CTF target.  */
36
37 class ctf_target final : public tracefile_target
38 {
39 public:
40   const char *shortname () override
41   { return "ctf"; }
42
43   const char *longname () override
44   { return _("CTF file"); }
45
46   const char *doc () override
47   {
48     return _("\
49 Use a CTF directory as a target.\n\
50 Specify the filename of the CTF directory.");
51   }
52
53   void open (const char *, int) override;
54   void close () override;
55   void fetch_registers (struct regcache *, int) override;
56   enum target_xfer_status xfer_partial (enum target_object object,
57                                                 const char *annex,
58                                                 gdb_byte *readbuf,
59                                                 const gdb_byte *writebuf,
60                                                 ULONGEST offset, ULONGEST len,
61                                                 ULONGEST *xfered_len) override;
62   void files_info () override;
63   int trace_find (enum trace_find_type type, int num,
64                           CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
65   int get_trace_state_variable_value (int tsv, LONGEST *val) override;
66   traceframe_info_up traceframe_info () override;
67 };
68
69 /* GDB saves trace buffers and other information (such as trace
70    status) got from the remote target into Common Trace Format (CTF).
71    The following types of information are expected to save in CTF:
72
73    1. The length (in bytes) of register cache.  Event "register" will
74    be defined in metadata, which includes the length.
75
76    2. Trace status.  Event "status" is defined in metadata, which
77    includes all aspects of trace status.
78
79    3. Uploaded trace variables.  Event "tsv_def" is defined in
80    metadata, which is about all aspects of a uploaded trace variable.
81    Uploaded tracepoints.   Event "tp_def" is defined in meta, which
82    is about all aspects of an uploaded tracepoint.  Note that the
83    "sequence" (a CTF type, which is a dynamically-sized array.) is
84    used for "actions" "step_actions" and "cmd_strings".
85
86    4. Trace frames.  Each trace frame is composed by several blocks
87    of different types ('R', 'M', 'V').  One trace frame is saved in
88    one CTF packet and the blocks of this frame are saved as events.
89    4.1: The trace frame related information (such as the number of
90    tracepoint associated with this frame) is saved in the packet
91    context.
92    4.2: The block 'M', 'R' and 'V' are saved in event "memory",
93    "register" and "tsv" respectively.
94    4.3: When iterating over events, babeltrace can't tell iterator
95    goes to a new packet, so we need a marker or anchor to tell GDB
96    that iterator goes into a new packet or frame.  We define event
97    "frame".  */
98
99 #define CTF_MAGIC               0xC1FC1FC1
100 #define CTF_SAVE_MAJOR          1
101 #define CTF_SAVE_MINOR          8
102
103 #define CTF_METADATA_NAME       "metadata"
104 #define CTF_DATASTREAM_NAME     "datastream"
105
106 /* Reserved event id.  */
107
108 #define CTF_EVENT_ID_REGISTER 0
109 #define CTF_EVENT_ID_TSV 1
110 #define CTF_EVENT_ID_MEMORY 2
111 #define CTF_EVENT_ID_FRAME 3
112 #define CTF_EVENT_ID_STATUS 4
113 #define CTF_EVENT_ID_TSV_DEF 5
114 #define CTF_EVENT_ID_TP_DEF 6
115
116 #define CTF_PID (2)
117
118 /* The state kept while writing the CTF datastream file.  */
119
120 struct trace_write_handler
121 {
122   /* File descriptor of metadata.  */
123   FILE *metadata_fd;
124   /* File descriptor of traceframes.  */
125   FILE *datastream_fd;
126
127   /* This is the content size of the current packet.  */
128   size_t content_size;
129
130   /* This is the start offset of current packet.  */
131   long packet_start;
132 };
133
134 /* Write metadata in FORMAT.  */
135
136 static void
137 ctf_save_write_metadata (struct trace_write_handler *handler,
138                          const char *format, ...)
139   ATTRIBUTE_PRINTF (2, 3);
140
141 static void
142 ctf_save_write_metadata (struct trace_write_handler *handler,
143                          const char *format, ...)
144 {
145   va_list args;
146
147   va_start (args, format);
148   if (vfprintf (handler->metadata_fd, format, args) < 0)
149     error (_("Unable to write metadata file (%s)"),
150              safe_strerror (errno));
151   va_end (args);
152 }
153
154 /* Write BUF of length SIZE to datastream file represented by
155    HANDLER.  */
156
157 static int
158 ctf_save_write (struct trace_write_handler *handler,
159                 const gdb_byte *buf, size_t size)
160 {
161   if (fwrite (buf, size, 1, handler->datastream_fd) != 1)
162     error (_("Unable to write file for saving trace data (%s)"),
163            safe_strerror (errno));
164
165   handler->content_size += size;
166
167   return 0;
168 }
169
170 /* Write a unsigned 32-bit integer to datastream file represented by
171    HANDLER.  */
172
173 #define ctf_save_write_uint32(HANDLER, U32) \
174   ctf_save_write (HANDLER, (gdb_byte *) &U32, 4)
175
176 /* Write a signed 32-bit integer to datastream file represented by
177    HANDLER.  */
178
179 #define ctf_save_write_int32(HANDLER, INT32) \
180   ctf_save_write ((HANDLER), (gdb_byte *) &(INT32), 4)
181
182 /* Set datastream file position.  Update HANDLER->content_size
183    if WHENCE is SEEK_CUR.  */
184
185 static int
186 ctf_save_fseek (struct trace_write_handler *handler, long offset,
187                 int whence)
188 {
189   gdb_assert (whence != SEEK_END);
190   gdb_assert (whence != SEEK_SET
191               || offset <= handler->content_size + handler->packet_start);
192
193   if (fseek (handler->datastream_fd, offset, whence))
194     error (_("Unable to seek file for saving trace data (%s)"),
195            safe_strerror (errno));
196
197   if (whence == SEEK_CUR)
198     handler->content_size += offset;
199
200   return 0;
201 }
202
203 /* Change the datastream file position to align on ALIGN_SIZE,
204    and write BUF to datastream file.  The size of BUF is SIZE.  */
205
206 static int
207 ctf_save_align_write (struct trace_write_handler *handler,
208                       const gdb_byte *buf,
209                       size_t size, size_t align_size)
210 {
211   long offset
212     = (align_up (handler->content_size, align_size)
213        - handler->content_size);
214
215   if (ctf_save_fseek (handler, offset, SEEK_CUR))
216     return -1;
217
218   if (ctf_save_write (handler, buf, size))
219     return -1;
220
221   return 0;
222 }
223
224 /* Write events to next new packet.  */
225
226 static void
227 ctf_save_next_packet (struct trace_write_handler *handler)
228 {
229   handler->packet_start += (handler->content_size + 4);
230   ctf_save_fseek (handler, handler->packet_start, SEEK_SET);
231   handler->content_size = 0;
232 }
233
234 /* Write the CTF metadata header.  */
235
236 static void
237 ctf_save_metadata_header (struct trace_write_handler *handler)
238 {
239   ctf_save_write_metadata (handler, "/* CTF %d.%d */\n",
240                            CTF_SAVE_MAJOR, CTF_SAVE_MINOR);
241   ctf_save_write_metadata (handler,
242                            "typealias integer { size = 8; align = 8; "
243                            "signed = false; encoding = ascii;}"
244                            " := ascii;\n");
245   ctf_save_write_metadata (handler,
246                            "typealias integer { size = 8; align = 8; "
247                            "signed = false; }"
248                            " := uint8_t;\n");
249   ctf_save_write_metadata (handler,
250                            "typealias integer { size = 16; align = 16;"
251                            "signed = false; } := uint16_t;\n");
252   ctf_save_write_metadata (handler,
253                            "typealias integer { size = 32; align = 32;"
254                            "signed = false; } := uint32_t;\n");
255   ctf_save_write_metadata (handler,
256                            "typealias integer { size = 64; align = 64;"
257                            "signed = false; base = hex;}"
258                            " := uint64_t;\n");
259   ctf_save_write_metadata (handler,
260                            "typealias integer { size = 32; align = 32;"
261                            "signed = true; } := int32_t;\n");
262   ctf_save_write_metadata (handler,
263                            "typealias integer { size = 64; align = 64;"
264                            "signed = true; } := int64_t;\n");
265   ctf_save_write_metadata (handler,
266                            "typealias string { encoding = ascii;"
267                            " } := chars;\n");
268   ctf_save_write_metadata (handler, "\n");
269
270   /* Get the byte order of the host and write CTF data in this byte
271      order.  */
272 #if WORDS_BIGENDIAN
273 #define HOST_ENDIANNESS "be"
274 #else
275 #define HOST_ENDIANNESS "le"
276 #endif
277
278   ctf_save_write_metadata (handler,
279                            "\ntrace {\n"
280                            "    major = %u;\n"
281                            "    minor = %u;\n"
282                            "    byte_order = %s;\n"
283                            "    packet.header := struct {\n"
284                            "            uint32_t magic;\n"
285                            "    };\n"
286                            "};\n"
287                            "\n"
288                            "stream {\n"
289                            "    packet.context := struct {\n"
290                            "            uint32_t content_size;\n"
291                            "            uint32_t packet_size;\n"
292                            "            uint16_t tpnum;\n"
293                            "    };\n"
294                            "    event.header := struct {\n"
295                            "            uint32_t id;\n"
296                            "    };\n"
297                            "};\n",
298                            CTF_SAVE_MAJOR, CTF_SAVE_MINOR,
299                            HOST_ENDIANNESS);
300   ctf_save_write_metadata (handler, "\n");
301 }
302
303 /* CTF trace writer.  */
304
305 struct ctf_trace_file_writer
306 {
307   struct trace_file_writer base;
308
309   /* States related to writing CTF trace file.  */
310   struct trace_write_handler tcs;
311 };
312
313 /* This is the implementation of trace_file_write_ops method
314    dtor.  */
315
316 static void
317 ctf_dtor (struct trace_file_writer *self)
318 {
319   struct ctf_trace_file_writer *writer
320     = (struct ctf_trace_file_writer *) self;
321
322   if (writer->tcs.metadata_fd != NULL)
323     fclose (writer->tcs.metadata_fd);
324
325   if (writer->tcs.datastream_fd != NULL)
326     fclose (writer->tcs.datastream_fd);
327
328 }
329
330 /* This is the implementation of trace_file_write_ops method
331    target_save.  */
332
333 static int
334 ctf_target_save (struct trace_file_writer *self,
335                  const char *dirname)
336 {
337   /* Don't support save trace file to CTF format in the target.  */
338   return 0;
339 }
340
341 /* This is the implementation of trace_file_write_ops method
342    start.  It creates the directory DIRNAME, metadata and datastream
343    in the directory.  */
344
345 static void
346 ctf_start (struct trace_file_writer *self, const char *dirname)
347 {
348   struct ctf_trace_file_writer *writer
349     = (struct ctf_trace_file_writer *) self;
350   mode_t hmode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH;
351
352   /* Create DIRNAME.  */
353   if (mkdir (dirname, hmode) && errno != EEXIST)
354     error (_("Unable to open directory '%s' for saving trace data (%s)"),
355            dirname, safe_strerror (errno));
356
357   memset (&writer->tcs, '\0', sizeof (writer->tcs));
358
359   std::string file_name = string_printf ("%s/%s", dirname, CTF_METADATA_NAME);
360
361   writer->tcs.metadata_fd = fopen (file_name.c_str (), "w");
362   if (writer->tcs.metadata_fd == NULL)
363     error (_("Unable to open file '%s' for saving trace data (%s)"),
364            file_name.c_str (), safe_strerror (errno));
365
366   ctf_save_metadata_header (&writer->tcs);
367
368   file_name = string_printf ("%s/%s", dirname, CTF_DATASTREAM_NAME);
369   writer->tcs.datastream_fd = fopen (file_name.c_str (), "w");
370   if (writer->tcs.datastream_fd == NULL)
371     error (_("Unable to open file '%s' for saving trace data (%s)"),
372            file_name.c_str (), safe_strerror (errno));
373 }
374
375 /* This is the implementation of trace_file_write_ops method
376    write_header.  Write the types of events on trace variable and
377    frame.  */
378
379 static void
380 ctf_write_header (struct trace_file_writer *self)
381 {
382   struct ctf_trace_file_writer *writer
383     = (struct ctf_trace_file_writer *) self;
384
385
386   ctf_save_write_metadata (&writer->tcs, "\n");
387   ctf_save_write_metadata (&writer->tcs,
388                            "event {\n\tname = \"memory\";\n\tid = %u;\n"
389                            "\tfields := struct { \n"
390                            "\t\tuint64_t address;\n"
391                            "\t\tuint16_t length;\n"
392                            "\t\tuint8_t contents[length];\n"
393                            "\t};\n"
394                            "};\n", CTF_EVENT_ID_MEMORY);
395
396   ctf_save_write_metadata (&writer->tcs, "\n");
397   ctf_save_write_metadata (&writer->tcs,
398                            "event {\n\tname = \"tsv\";\n\tid = %u;\n"
399                            "\tfields := struct { \n"
400                            "\t\tuint64_t val;\n"
401                            "\t\tuint32_t num;\n"
402                            "\t};\n"
403                            "};\n", CTF_EVENT_ID_TSV);
404
405   ctf_save_write_metadata (&writer->tcs, "\n");
406   ctf_save_write_metadata (&writer->tcs,
407                            "event {\n\tname = \"frame\";\n\tid = %u;\n"
408                            "\tfields := struct { \n"
409                            "\t};\n"
410                            "};\n", CTF_EVENT_ID_FRAME);
411
412   ctf_save_write_metadata (&writer->tcs, "\n");
413   ctf_save_write_metadata (&writer->tcs,
414                           "event {\n\tname = \"tsv_def\";\n"
415                           "\tid = %u;\n\tfields := struct { \n"
416                           "\t\tint64_t initial_value;\n"
417                           "\t\tint32_t number;\n"
418                           "\t\tint32_t builtin;\n"
419                           "\t\tchars name;\n"
420                           "\t};\n"
421                           "};\n", CTF_EVENT_ID_TSV_DEF);
422
423   ctf_save_write_metadata (&writer->tcs, "\n");
424   ctf_save_write_metadata (&writer->tcs,
425                            "event {\n\tname = \"tp_def\";\n"
426                            "\tid = %u;\n\tfields := struct { \n"
427                            "\t\tuint64_t addr;\n"
428                            "\t\tuint64_t traceframe_usage;\n"
429                            "\t\tint32_t number;\n"
430                            "\t\tint32_t enabled;\n"
431                            "\t\tint32_t step;\n"
432                            "\t\tint32_t pass;\n"
433                            "\t\tint32_t hit_count;\n"
434                            "\t\tint32_t type;\n"
435                            "\t\tchars cond;\n"
436
437                           "\t\tuint32_t action_num;\n"
438                           "\t\tchars actions[action_num];\n"
439
440                           "\t\tuint32_t step_action_num;\n"
441                           "\t\tchars step_actions[step_action_num];\n"
442
443                           "\t\tchars at_string;\n"
444                           "\t\tchars cond_string;\n"
445
446                           "\t\tuint32_t cmd_num;\n"
447                           "\t\tchars cmd_strings[cmd_num];\n"
448                           "\t};\n"
449                           "};\n", CTF_EVENT_ID_TP_DEF);
450
451   gdb_assert (writer->tcs.content_size == 0);
452   gdb_assert (writer->tcs.packet_start == 0);
453
454   /* Create a new packet to contain this event.  */
455   self->ops->frame_ops->start (self, 0);
456 }
457
458 /* This is the implementation of trace_file_write_ops method
459    write_regblock_type.  Write the type of register event in
460    metadata.  */
461
462 static void
463 ctf_write_regblock_type (struct trace_file_writer *self, int size)
464 {
465   struct ctf_trace_file_writer *writer
466     = (struct ctf_trace_file_writer *) self;
467
468   ctf_save_write_metadata (&writer->tcs, "\n");
469
470   ctf_save_write_metadata (&writer->tcs,
471                            "event {\n\tname = \"register\";\n\tid = %u;\n"
472                            "\tfields := struct { \n"
473                            "\t\tascii contents[%d];\n"
474                            "\t};\n"
475                            "};\n",
476                            CTF_EVENT_ID_REGISTER, size);
477 }
478
479 /* This is the implementation of trace_file_write_ops method
480    write_status.  */
481
482 static void
483 ctf_write_status (struct trace_file_writer *self,
484                   struct trace_status *ts)
485 {
486   struct ctf_trace_file_writer *writer
487     = (struct ctf_trace_file_writer *) self;
488   uint32_t id;
489
490   ctf_save_write_metadata (&writer->tcs, "\n");
491   ctf_save_write_metadata (&writer->tcs,
492                            "event {\n\tname = \"status\";\n\tid = %u;\n"
493                            "\tfields := struct { \n"
494                            "\t\tint32_t stop_reason;\n"
495                            "\t\tint32_t stopping_tracepoint;\n"
496                            "\t\tint32_t traceframe_count;\n"
497                            "\t\tint32_t traceframes_created;\n"
498                            "\t\tint32_t buffer_free;\n"
499                            "\t\tint32_t buffer_size;\n"
500                            "\t\tint32_t disconnected_tracing;\n"
501                            "\t\tint32_t circular_buffer;\n"
502                            "\t};\n"
503                            "};\n",
504                            CTF_EVENT_ID_STATUS);
505
506   id = CTF_EVENT_ID_STATUS;
507   /* Event Id.  */
508   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
509
510   ctf_save_write_int32 (&writer->tcs, ts->stop_reason);
511   ctf_save_write_int32 (&writer->tcs, ts->stopping_tracepoint);
512   ctf_save_write_int32 (&writer->tcs, ts->traceframe_count);
513   ctf_save_write_int32 (&writer->tcs, ts->traceframes_created);
514   ctf_save_write_int32 (&writer->tcs, ts->buffer_free);
515   ctf_save_write_int32 (&writer->tcs, ts->buffer_size);
516   ctf_save_write_int32 (&writer->tcs, ts->disconnected_tracing);
517   ctf_save_write_int32 (&writer->tcs, ts->circular_buffer);
518 }
519
520 /* This is the implementation of trace_file_write_ops method
521    write_uploaded_tsv.  */
522
523 static void
524 ctf_write_uploaded_tsv (struct trace_file_writer *self,
525                         struct uploaded_tsv *tsv)
526 {
527   struct ctf_trace_file_writer *writer
528     = (struct ctf_trace_file_writer *) self;
529   int32_t int32;
530   int64_t int64;
531   const gdb_byte zero = 0;
532
533   /* Event Id.  */
534   int32 = CTF_EVENT_ID_TSV_DEF;
535   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);
536
537   /* initial_value */
538   int64 = tsv->initial_value;
539   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
540
541   /* number */
542   ctf_save_write_int32 (&writer->tcs, tsv->number);
543
544   /* builtin */
545   ctf_save_write_int32 (&writer->tcs, tsv->builtin);
546
547   /* name */
548   if (tsv->name != NULL)
549     ctf_save_write (&writer->tcs, (gdb_byte *) tsv->name,
550                     strlen (tsv->name));
551   ctf_save_write (&writer->tcs, &zero, 1);
552 }
553
554 /* This is the implementation of trace_file_write_ops method
555    write_uploaded_tp.  */
556
557 static void
558 ctf_write_uploaded_tp (struct trace_file_writer *self,
559                        struct uploaded_tp *tp)
560 {
561   struct ctf_trace_file_writer *writer
562     = (struct ctf_trace_file_writer *) self;
563   int32_t int32;
564   int64_t int64;
565   uint32_t u32;
566   const gdb_byte zero = 0;
567
568   /* Event Id.  */
569   int32 = CTF_EVENT_ID_TP_DEF;
570   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);
571
572   /* address */
573   int64 = tp->addr;
574   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
575
576   /* traceframe_usage */
577   int64 = tp->traceframe_usage;
578   ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
579
580   /* number */
581   ctf_save_write_int32 (&writer->tcs, tp->number);
582
583   /* enabled */
584   ctf_save_write_int32 (&writer->tcs, tp->enabled);
585
586   /* step */
587   ctf_save_write_int32 (&writer->tcs, tp->step);
588
589   /* pass */
590   ctf_save_write_int32 (&writer->tcs, tp->pass);
591
592   /* hit_count */
593   ctf_save_write_int32 (&writer->tcs, tp->hit_count);
594
595   /* type */
596   ctf_save_write_int32 (&writer->tcs, tp->type);
597
598   /* condition  */
599   if (tp->cond != NULL)
600     ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond, strlen (tp->cond));
601   ctf_save_write (&writer->tcs, &zero, 1);
602
603   /* actions */
604   u32 = tp->actions.size ();
605   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
606   for (char *act : tp->actions)
607     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);
608
609   /* step_actions */
610   u32 = tp->step_actions.size ();
611   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
612   for (char *act : tp->step_actions)
613     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);
614
615   /* at_string */
616   if (tp->at_string != NULL)
617     ctf_save_write (&writer->tcs, (gdb_byte *) tp->at_string,
618                     strlen (tp->at_string));
619   ctf_save_write (&writer->tcs, &zero, 1);
620
621   /* cond_string */
622   if (tp->cond_string != NULL)
623     ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond_string,
624                     strlen (tp->cond_string));
625   ctf_save_write (&writer->tcs, &zero, 1);
626
627   /* cmd_strings */
628   u32 = tp->cmd_strings.size ();
629   ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
630   for (char *act : tp->cmd_strings)
631     ctf_save_write (&writer->tcs, (gdb_byte *) act, strlen (act) + 1);
632
633 }
634
635 /* This is the implementation of trace_file_write_ops method
636    write_tdesc.  */
637
638 static void
639 ctf_write_tdesc (struct trace_file_writer *self)
640 {
641   /* Nothing so far. */
642 }
643
644 /* This is the implementation of trace_file_write_ops method
645    write_definition_end.  */
646
647 static void
648 ctf_write_definition_end (struct trace_file_writer *self)
649 {
650   self->ops->frame_ops->end (self);
651 }
652
653 /* This is the implementation of trace_file_write_ops method
654    end.  */
655
656 static void
657 ctf_end (struct trace_file_writer *self)
658 {
659   struct ctf_trace_file_writer *writer = (struct ctf_trace_file_writer *) self;
660
661   gdb_assert (writer->tcs.content_size == 0);
662 }
663
664 /* This is the implementation of trace_frame_write_ops method
665    start.  */
666
667 static void
668 ctf_write_frame_start (struct trace_file_writer *self, uint16_t tpnum)
669 {
670   struct ctf_trace_file_writer *writer
671     = (struct ctf_trace_file_writer *) self;
672   uint32_t id = CTF_EVENT_ID_FRAME;
673   uint32_t u32;
674
675   /* Step 1: Write packet context.  */
676   /* magic.  */
677   u32 = CTF_MAGIC;
678   ctf_save_write_uint32 (&writer->tcs, u32);
679   /* content_size and packet_size..  We still don't know the value,
680      write it later.  */
681   ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
682   ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
683   /* Tracepoint number.  */
684   ctf_save_write (&writer->tcs, (gdb_byte *) &tpnum, 2);
685
686   /* Step 2: Write event "frame".  */
687   /* Event Id.  */
688   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
689 }
690
691 /* This is the implementation of trace_frame_write_ops method
692    write_r_block.  */
693
694 static void
695 ctf_write_frame_r_block (struct trace_file_writer *self,
696                          gdb_byte *buf, int32_t size)
697 {
698   struct ctf_trace_file_writer *writer
699     = (struct ctf_trace_file_writer *) self;
700   uint32_t id = CTF_EVENT_ID_REGISTER;
701
702   /* Event Id.  */
703   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
704
705   /* array contents.  */
706   ctf_save_align_write (&writer->tcs, buf, size, 1);
707 }
708
709 /* This is the implementation of trace_frame_write_ops method
710    write_m_block_header.  */
711
712 static void
713 ctf_write_frame_m_block_header (struct trace_file_writer *self,
714                                 uint64_t addr, uint16_t length)
715 {
716   struct ctf_trace_file_writer *writer
717     = (struct ctf_trace_file_writer *) self;
718   uint32_t event_id = CTF_EVENT_ID_MEMORY;
719
720   /* Event Id.  */
721   ctf_save_align_write (&writer->tcs, (gdb_byte *) &event_id, 4, 4);
722
723   /* Address.  */
724   ctf_save_align_write (&writer->tcs, (gdb_byte *) &addr, 8, 8);
725
726   /* Length.  */
727   ctf_save_align_write (&writer->tcs, (gdb_byte *) &length, 2, 2);
728 }
729
730 /* This is the implementation of trace_frame_write_ops method
731    write_m_block_memory.  */
732
733 static void
734 ctf_write_frame_m_block_memory (struct trace_file_writer *self,
735                                 gdb_byte *buf, uint16_t length)
736 {
737   struct ctf_trace_file_writer *writer
738     = (struct ctf_trace_file_writer *) self;
739
740   /* Contents.  */
741   ctf_save_align_write (&writer->tcs, (gdb_byte *) buf, length, 1);
742 }
743
744 /* This is the implementation of trace_frame_write_ops method
745    write_v_block.  */
746
747 static void
748 ctf_write_frame_v_block (struct trace_file_writer *self,
749                          int32_t num, uint64_t val)
750 {
751   struct ctf_trace_file_writer *writer
752     = (struct ctf_trace_file_writer *) self;
753   uint32_t id = CTF_EVENT_ID_TSV;
754
755   /* Event Id.  */
756   ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
757
758   /* val.  */
759   ctf_save_align_write (&writer->tcs, (gdb_byte *) &val, 8, 8);
760   /* num.  */
761   ctf_save_align_write (&writer->tcs, (gdb_byte *) &num, 4, 4);
762 }
763
764 /* This is the implementation of trace_frame_write_ops method
765    end.  */
766
767 static void
768 ctf_write_frame_end (struct trace_file_writer *self)
769 {
770   struct ctf_trace_file_writer *writer
771     = (struct ctf_trace_file_writer *) self;
772   uint32_t u32;
773   uint32_t t;
774
775   /* Write the content size to packet header.  */
776   ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + 4,
777                   SEEK_SET);
778   u32 = writer->tcs.content_size * TARGET_CHAR_BIT;
779
780   t = writer->tcs.content_size;
781   ctf_save_write_uint32 (&writer->tcs, u32);
782
783   /* Write the packet size.  */
784   u32 += 4 * TARGET_CHAR_BIT;
785   ctf_save_write_uint32 (&writer->tcs, u32);
786
787   writer->tcs.content_size = t;
788
789   /* Write zero at the end of the packet.  */
790   ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + t,
791                   SEEK_SET);
792   u32 = 0;
793   ctf_save_write_uint32 (&writer->tcs, u32);
794   writer->tcs.content_size = t;
795
796   ctf_save_next_packet (&writer->tcs);
797 }
798
799 /* Operations to write various types of trace frames into CTF
800    format.  */
801
802 static const struct trace_frame_write_ops ctf_write_frame_ops =
803 {
804   ctf_write_frame_start,
805   ctf_write_frame_r_block,
806   ctf_write_frame_m_block_header,
807   ctf_write_frame_m_block_memory,
808   ctf_write_frame_v_block,
809   ctf_write_frame_end,
810 };
811
812 /* Operations to write trace buffers into CTF format.  */
813
814 static const struct trace_file_write_ops ctf_write_ops =
815 {
816   ctf_dtor,
817   ctf_target_save,
818   ctf_start,
819   ctf_write_header,
820   ctf_write_regblock_type,
821   ctf_write_status,
822   ctf_write_uploaded_tsv,
823   ctf_write_uploaded_tp,
824   ctf_write_tdesc,
825   ctf_write_definition_end,
826   NULL,
827   &ctf_write_frame_ops,
828   ctf_end,
829 };
830
831 /* Return a trace writer for CTF format.  */
832
833 struct trace_file_writer *
834 ctf_trace_file_writer_new (void)
835 {
836   struct ctf_trace_file_writer *writer = XNEW (struct ctf_trace_file_writer);
837
838   writer->base.ops = &ctf_write_ops;
839
840   return (struct trace_file_writer *) writer;
841 }
842
843 #if HAVE_LIBBABELTRACE
844 /* Use libbabeltrace to read CTF data.  The libbabeltrace provides
845    iterator to iterate over each event in CTF data and APIs to get
846    details of event and packet, so it is very convenient to use
847    libbabeltrace to access events in CTF.  */
848
849 #include <babeltrace/babeltrace.h>
850 #include <babeltrace/ctf/events.h>
851 #include <babeltrace/ctf/iterator.h>
852
853 /* The struct pointer for current CTF directory.  */
854 static int handle_id = -1;
855 static struct bt_context *ctx = NULL;
856 static struct bt_ctf_iter *ctf_iter = NULL;
857 /* The position of the first packet containing trace frame.  */
858 static struct bt_iter_pos *start_pos;
859
860 /* The name of CTF directory.  */
861 static char *trace_dirname;
862
863 static ctf_target ctf_ops;
864
865 /* Destroy ctf iterator and context.  */
866
867 static void
868 ctf_destroy (void)
869 {
870   if (ctf_iter != NULL)
871     {
872       bt_ctf_iter_destroy (ctf_iter);
873       ctf_iter = NULL;
874     }
875   if (ctx != NULL)
876     {
877       bt_context_put (ctx);
878       ctx = NULL;
879     }
880 }
881
882 /* Open CTF trace data in DIRNAME.  */
883
884 static void
885 ctf_open_dir (const char *dirname)
886 {
887   struct bt_iter_pos begin_pos;
888   unsigned int count, i;
889   struct bt_ctf_event_decl * const *list;
890
891   ctx = bt_context_create ();
892   if (ctx == NULL)
893     error (_("Unable to create bt_context"));
894   handle_id = bt_context_add_trace (ctx, dirname, "ctf", NULL, NULL, NULL);
895   if (handle_id < 0)
896     {
897       ctf_destroy ();
898       error (_("Unable to use libbabeltrace on directory \"%s\""),
899              dirname);
900     }
901
902   begin_pos.type = BT_SEEK_BEGIN;
903   ctf_iter = bt_ctf_iter_create (ctx, &begin_pos, NULL);
904   if (ctf_iter == NULL)
905     {
906       ctf_destroy ();
907       error (_("Unable to create bt_iterator"));
908     }
909
910   /* Look for the declaration of register block.  Get the length of
911      array "contents" to set trace_regblock_size.  */
912
913   bt_ctf_get_event_decl_list (handle_id, ctx, &list, &count);
914   for (i = 0; i < count; i++)
915     if (strcmp ("register", bt_ctf_get_decl_event_name (list[i])) == 0)
916       {
917         const struct bt_ctf_field_decl * const *field_list;
918         const struct bt_declaration *decl;
919
920         bt_ctf_get_decl_fields (list[i], BT_EVENT_FIELDS, &field_list,
921                                 &count);
922
923         gdb_assert (count == 1);
924         gdb_assert (0 == strcmp ("contents",
925                                  bt_ctf_get_decl_field_name (field_list[0])));
926         decl = bt_ctf_get_decl_from_field_decl (field_list[0]);
927         trace_regblock_size = bt_ctf_get_array_len (decl);
928
929         break;
930       }
931 }
932
933 #define SET_INT32_FIELD(EVENT, SCOPE, VAR, FIELD)                       \
934   (VAR)->FIELD = (int) bt_ctf_get_int64 (bt_ctf_get_field ((EVENT),     \
935                                                            (SCOPE),     \
936                                                            #FIELD))
937
938 #define SET_ENUM_FIELD(EVENT, SCOPE, VAR, TYPE, FIELD)                  \
939   (VAR)->FIELD = (TYPE) bt_ctf_get_int64 (bt_ctf_get_field ((EVENT),    \
940                                                             (SCOPE),    \
941                                                             #FIELD))
942
943
944 /* EVENT is the "status" event and TS is filled in.  */
945
946 static void
947 ctf_read_status (struct bt_ctf_event *event, struct trace_status *ts)
948 {
949   const struct bt_definition *scope
950     = bt_ctf_get_top_level_scope (event, BT_EVENT_FIELDS);
951
952   SET_ENUM_FIELD (event, scope, ts, enum trace_stop_reason, stop_reason);
953   SET_INT32_FIELD (event, scope, ts, stopping_tracepoint);
954   SET_INT32_FIELD (event, scope, ts, traceframe_count);
955   SET_INT32_FIELD (event, scope, ts, traceframes_created);
956   SET_INT32_FIELD (event, scope, ts, buffer_free);
957   SET_INT32_FIELD (event, scope, ts, buffer_size);
958   SET_INT32_FIELD (event, scope, ts, disconnected_tracing);
959   SET_INT32_FIELD (event, scope, ts, circular_buffer);
960
961   bt_iter_next (bt_ctf_get_iter (ctf_iter));
962 }
963
964 /* Read the events "tsv_def" one by one, extract its contents and fill
965    in the list UPLOADED_TSVS.  */
966
967 static void
968 ctf_read_tsv (struct uploaded_tsv **uploaded_tsvs)
969 {
970   gdb_assert (ctf_iter != NULL);
971
972   while (1)
973     {
974       struct bt_ctf_event *event;
975       const struct bt_definition *scope;
976       const struct bt_definition *def;
977       uint32_t event_id;
978       struct uploaded_tsv *utsv = NULL;
979
980       event = bt_ctf_iter_read_event (ctf_iter);
981       scope = bt_ctf_get_top_level_scope (event,
982                                           BT_STREAM_EVENT_HEADER);
983       event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
984                                                       "id"));
985       if (event_id != CTF_EVENT_ID_TSV_DEF)
986         break;
987
988       scope = bt_ctf_get_top_level_scope (event,
989                                           BT_EVENT_FIELDS);
990
991       def = bt_ctf_get_field (event, scope, "number");
992       utsv = get_uploaded_tsv ((int32_t) bt_ctf_get_int64 (def),
993                                uploaded_tsvs);
994
995       def = bt_ctf_get_field (event, scope, "builtin");
996       utsv->builtin = (int32_t) bt_ctf_get_int64 (def);
997       def = bt_ctf_get_field (event, scope, "initial_value");
998       utsv->initial_value = bt_ctf_get_int64 (def);
999
1000       def = bt_ctf_get_field (event, scope, "name");
1001       utsv->name =  xstrdup (bt_ctf_get_string (def));
1002
1003       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1004         break;
1005     }
1006
1007 }
1008
1009 /* Read the value of element whose index is NUM from CTF and write it
1010    to the corresponding VAR->ARRAY. */
1011
1012 #define SET_ARRAY_FIELD(EVENT, SCOPE, VAR, NUM, ARRAY)  \
1013   do                                                    \
1014     {                                                   \
1015       uint32_t u32, i;                                          \
1016       const struct bt_definition *def;                          \
1017                                                                 \
1018       u32 = (uint32_t) bt_ctf_get_uint64 (bt_ctf_get_field ((EVENT),    \
1019                                                             (SCOPE),    \
1020                                                             #NUM));     \
1021       def = bt_ctf_get_field ((EVENT), (SCOPE), #ARRAY);                \
1022       for (i = 0; i < u32; i++)                                 \
1023         {                                                               \
1024           const struct bt_definition *element                           \
1025             = bt_ctf_get_index ((EVENT), def, i);                       \
1026                                                                         \
1027           (VAR)->ARRAY.push_back                                        \
1028             (xstrdup (bt_ctf_get_string (element)));                    \
1029         }                                                               \
1030     }                                                                   \
1031   while (0)
1032
1033 /* Read a string from CTF and set VAR->FIELD. If the length of string
1034    is zero, set VAR->FIELD to NULL.  */
1035
1036 #define SET_STRING_FIELD(EVENT, SCOPE, VAR, FIELD)                      \
1037   do                                                                    \
1038     {                                                                   \
1039       const char *p = bt_ctf_get_string (bt_ctf_get_field ((EVENT),     \
1040                                                            (SCOPE),     \
1041                                                            #FIELD));    \
1042                                                                         \
1043       if (strlen (p) > 0)                                               \
1044         (VAR)->FIELD = xstrdup (p);                                     \
1045       else                                                              \
1046         (VAR)->FIELD = NULL;                                            \
1047     }                                                                   \
1048   while (0)
1049
1050 /* Read the events "tp_def" one by one, extract its contents and fill
1051    in the list UPLOADED_TPS.  */
1052
1053 static void
1054 ctf_read_tp (struct uploaded_tp **uploaded_tps)
1055 {
1056   gdb_assert (ctf_iter != NULL);
1057
1058   while (1)
1059     {
1060       struct bt_ctf_event *event;
1061       const struct bt_definition *scope;
1062       uint32_t u32;
1063       int32_t int32;
1064       uint64_t u64;
1065       struct uploaded_tp *utp = NULL;
1066
1067       event = bt_ctf_iter_read_event (ctf_iter);
1068       scope = bt_ctf_get_top_level_scope (event,
1069                                           BT_STREAM_EVENT_HEADER);
1070       u32 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
1071                                                  "id"));
1072       if (u32 != CTF_EVENT_ID_TP_DEF)
1073         break;
1074
1075       scope = bt_ctf_get_top_level_scope (event,
1076                                           BT_EVENT_FIELDS);
1077       int32 = (int32_t) bt_ctf_get_int64 (bt_ctf_get_field (event,
1078                                                             scope,
1079                                                             "number"));
1080       u64 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
1081                                                  "addr"));
1082       utp = get_uploaded_tp (int32, u64,  uploaded_tps);
1083
1084       SET_INT32_FIELD (event, scope, utp, enabled);
1085       SET_INT32_FIELD (event, scope, utp, step);
1086       SET_INT32_FIELD (event, scope, utp, pass);
1087       SET_INT32_FIELD (event, scope, utp, hit_count);
1088       SET_ENUM_FIELD (event, scope, utp, enum bptype, type);
1089
1090       /* Read 'cmd_strings'.  */
1091       SET_ARRAY_FIELD (event, scope, utp, cmd_num, cmd_strings);
1092       /* Read 'actions'.  */
1093       SET_ARRAY_FIELD (event, scope, utp, action_num, actions);
1094       /* Read 'step_actions'.  */
1095       SET_ARRAY_FIELD (event, scope, utp, step_action_num,
1096                        step_actions);
1097
1098       SET_STRING_FIELD(event, scope, utp, at_string);
1099       SET_STRING_FIELD(event, scope, utp, cond_string);
1100
1101       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1102         break;
1103     }
1104 }
1105
1106 /* This is the implementation of target_ops method to_open.  Open CTF
1107    trace data, read trace status, trace state variables and tracepoint
1108    definitions from the first packet.  Set the start position at the
1109    second packet which contains events on trace blocks.  */
1110
1111 void
1112 ctf_target::open (const char *dirname, int from_tty)
1113 {
1114   struct bt_ctf_event *event;
1115   uint32_t event_id;
1116   const struct bt_definition *scope;
1117   struct uploaded_tsv *uploaded_tsvs = NULL;
1118   struct uploaded_tp *uploaded_tps = NULL;
1119
1120   if (!dirname)
1121     error (_("No CTF directory specified."));
1122
1123   ctf_open_dir (dirname);
1124
1125   target_preopen (from_tty);
1126
1127   /* Skip the first packet which about the trace status.  The first
1128      event is "frame".  */
1129   event = bt_ctf_iter_read_event (ctf_iter);
1130   scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
1131   event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
1132   if (event_id != CTF_EVENT_ID_FRAME)
1133     error (_("Wrong event id of the first event"));
1134   /* The second event is "status".  */
1135   bt_iter_next (bt_ctf_get_iter (ctf_iter));
1136   event = bt_ctf_iter_read_event (ctf_iter);
1137   scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
1138   event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
1139   if (event_id != CTF_EVENT_ID_STATUS)
1140     error (_("Wrong event id of the second event"));
1141   ctf_read_status (event, current_trace_status ());
1142
1143   ctf_read_tsv (&uploaded_tsvs);
1144
1145   ctf_read_tp (&uploaded_tps);
1146
1147   event = bt_ctf_iter_read_event (ctf_iter);
1148   /* EVENT can be NULL if we've already gone to the end of stream of
1149      events.  */
1150   if (event != NULL)
1151     {
1152       scope = bt_ctf_get_top_level_scope (event,
1153                                           BT_STREAM_EVENT_HEADER);
1154       event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event,
1155                                                       scope, "id"));
1156       if (event_id != CTF_EVENT_ID_FRAME)
1157         error (_("Wrong event id of the first event of the second packet"));
1158     }
1159
1160   start_pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1161   gdb_assert (start_pos->type == BT_SEEK_RESTORE);
1162
1163   trace_dirname = xstrdup (dirname);
1164   push_target (&ctf_ops);
1165
1166   inferior_appeared (current_inferior (), CTF_PID);
1167   inferior_ptid = pid_to_ptid (CTF_PID);
1168   add_thread_silent (inferior_ptid);
1169
1170   merge_uploaded_trace_state_variables (&uploaded_tsvs);
1171   merge_uploaded_tracepoints (&uploaded_tps);
1172
1173   post_create_inferior (&ctf_ops, from_tty);
1174 }
1175
1176 /* This is the implementation of target_ops method to_close.  Destroy
1177    CTF iterator and context.  */
1178
1179 void
1180 ctf_target::close ()
1181 {
1182   int pid;
1183
1184   ctf_destroy ();
1185   xfree (trace_dirname);
1186   trace_dirname = NULL;
1187
1188   pid = ptid_get_pid (inferior_ptid);
1189   inferior_ptid = null_ptid;    /* Avoid confusion from thread stuff.  */
1190   exit_inferior_silent (pid);
1191
1192   trace_reset_local_state ();
1193 }
1194
1195 /* This is the implementation of target_ops method to_files_info.
1196    Print the directory name of CTF trace data.  */
1197
1198 void
1199 ctf_target::files_info ()
1200 {
1201   printf_filtered ("\t`%s'\n", trace_dirname);
1202 }
1203
1204 /* This is the implementation of target_ops method to_fetch_registers.
1205    Iterate over events whose name is "register" in current frame,
1206    extract contents from events, and set REGCACHE with the contents.
1207    If no matched events are found, mark registers unavailable.  */
1208
1209 void
1210 ctf_target::fetch_registers (struct regcache *regcache, int regno)
1211 {
1212   struct gdbarch *gdbarch = regcache->arch ();
1213   struct bt_ctf_event *event = NULL;
1214   struct bt_iter_pos *pos;
1215
1216   /* An uninitialized reg size says we're not going to be
1217      successful at getting register blocks.  */
1218   if (trace_regblock_size == 0)
1219     return;
1220
1221   gdb_assert (ctf_iter != NULL);
1222   /* Save the current position.  */
1223   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1224   gdb_assert (pos->type == BT_SEEK_RESTORE);
1225
1226   while (1)
1227     {
1228       const char *name;
1229       struct bt_ctf_event *event1;
1230
1231       event1 = bt_ctf_iter_read_event (ctf_iter);
1232
1233       name = bt_ctf_event_name (event1);
1234
1235       if (name == NULL || strcmp (name, "frame") == 0)
1236         break;
1237       else if (strcmp (name, "register") == 0)
1238         {
1239           event = event1;
1240           break;
1241         }
1242
1243       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1244         break;
1245     }
1246
1247   /* Restore the position.  */
1248   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1249
1250   if (event != NULL)
1251     {
1252       int offset, regsize, regn;
1253       const struct bt_definition *scope
1254         = bt_ctf_get_top_level_scope (event,
1255                                       BT_EVENT_FIELDS);
1256       const struct bt_definition *array
1257         = bt_ctf_get_field (event, scope, "contents");
1258       gdb_byte *regs = (gdb_byte *) bt_ctf_get_char_array (array);
1259
1260       /* Assume the block is laid out in GDB register number order,
1261          each register with the size that it has in GDB.  */
1262       offset = 0;
1263       for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
1264         {
1265           regsize = register_size (gdbarch, regn);
1266           /* Make sure we stay within block bounds.  */
1267           if (offset + regsize >= trace_regblock_size)
1268             break;
1269           if (regcache_register_status (regcache, regn) == REG_UNKNOWN)
1270             {
1271               if (regno == regn)
1272                 {
1273                   regcache_raw_supply (regcache, regno, regs + offset);
1274                   break;
1275                 }
1276               else if (regno == -1)
1277                 {
1278                   regcache_raw_supply (regcache, regn, regs + offset);
1279                 }
1280             }
1281           offset += regsize;
1282         }
1283     }
1284   else
1285     tracefile_fetch_registers (regcache, regno);
1286 }
1287
1288 /* This is the implementation of target_ops method to_xfer_partial.
1289    Iterate over events whose name is "memory" in
1290    current frame, extract the address and length from events.  If
1291    OFFSET is within the range, read the contents from events to
1292    READBUF.  */
1293
1294 enum target_xfer_status
1295 ctf_target::xfer_partial (enum target_object object,
1296                           const char *annex, gdb_byte *readbuf,
1297                           const gdb_byte *writebuf, ULONGEST offset,
1298                           ULONGEST len, ULONGEST *xfered_len)
1299 {
1300   /* We're only doing regular memory for now.  */
1301   if (object != TARGET_OBJECT_MEMORY)
1302     return TARGET_XFER_E_IO;
1303
1304   if (readbuf == NULL)
1305     error (_("ctf_xfer_partial: trace file is read-only"));
1306
1307   if (get_traceframe_number () != -1)
1308     {
1309       struct bt_iter_pos *pos;
1310       enum target_xfer_status res;
1311       /* Records the lowest available address of all blocks that
1312          intersects the requested range.  */
1313       ULONGEST low_addr_available = 0;
1314
1315       gdb_assert (ctf_iter != NULL);
1316       /* Save the current position.  */
1317       pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1318       gdb_assert (pos->type == BT_SEEK_RESTORE);
1319
1320       /* Iterate through the traceframe's blocks, looking for
1321          memory.  */
1322       while (1)
1323         {
1324           ULONGEST amt;
1325           uint64_t maddr;
1326           uint16_t mlen;
1327           const struct bt_definition *scope;
1328           const struct bt_definition *def;
1329           struct bt_ctf_event *event
1330             = bt_ctf_iter_read_event (ctf_iter);
1331           const char *name = bt_ctf_event_name (event);
1332
1333           if (name == NULL || strcmp (name, "frame") == 0)
1334             break;
1335           else if (strcmp (name, "memory") != 0)
1336             {
1337               if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1338                 break;
1339
1340               continue;
1341             }
1342
1343           scope = bt_ctf_get_top_level_scope (event,
1344                                               BT_EVENT_FIELDS);
1345
1346           def = bt_ctf_get_field (event, scope, "address");
1347           maddr = bt_ctf_get_uint64 (def);
1348           def = bt_ctf_get_field (event, scope, "length");
1349           mlen = (uint16_t) bt_ctf_get_uint64 (def);
1350
1351           /* If the block includes the first part of the desired
1352              range, return as much it has; GDB will re-request the
1353              remainder, which might be in a different block of this
1354              trace frame.  */
1355           if (maddr <= offset && offset < (maddr + mlen))
1356             {
1357               const struct bt_definition *array
1358                 = bt_ctf_get_field (event, scope, "contents");
1359               gdb_byte *contents;
1360               int k;
1361
1362               contents = (gdb_byte *) xmalloc (mlen);
1363
1364               for (k = 0; k < mlen; k++)
1365                 {
1366                   const struct bt_definition *element
1367                     = bt_ctf_get_index (event, array, k);
1368
1369                   contents[k] = (gdb_byte) bt_ctf_get_uint64 (element);
1370                 }
1371
1372               amt = (maddr + mlen) - offset;
1373               if (amt > len)
1374                 amt = len;
1375
1376               memcpy (readbuf, &contents[offset - maddr], amt);
1377
1378               xfree (contents);
1379
1380               /* Restore the position.  */
1381               bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1382
1383               if (amt == 0)
1384                 return TARGET_XFER_EOF;
1385               else
1386                 {
1387                   *xfered_len = amt;
1388                   return TARGET_XFER_OK;
1389                 }
1390             }
1391
1392           if (offset < maddr && maddr < (offset + len))
1393             if (low_addr_available == 0 || low_addr_available > maddr)
1394               low_addr_available = maddr;
1395
1396           if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1397             break;
1398         }
1399
1400       /* Restore the position.  */
1401       bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1402
1403       /* Requested memory is unavailable in the context of traceframes,
1404          and this address falls within a read-only section, fallback
1405          to reading from executable, up to LOW_ADDR_AVAILABLE  */
1406       if (offset < low_addr_available)
1407         len = std::min (len, low_addr_available - offset);
1408       res = exec_read_partial_read_only (readbuf, offset, len, xfered_len);
1409
1410       if (res == TARGET_XFER_OK)
1411         return TARGET_XFER_OK;
1412       else
1413         {
1414           /* No use trying further, we know some memory starting
1415              at MEMADDR isn't available.  */
1416           *xfered_len = len;
1417           return TARGET_XFER_UNAVAILABLE;
1418         }
1419     }
1420   else
1421     {
1422       /* Fallback to reading from read-only sections.  */
1423       return section_table_read_available_memory (readbuf, offset, len, xfered_len);
1424     }
1425 }
1426
1427 /* This is the implementation of target_ops method
1428    to_get_trace_state_variable_value.
1429    Iterate over events whose name is "tsv" in current frame.  When the
1430    trace variable is found, set the value of it to *VAL and return
1431    true, otherwise return false.  */
1432
1433 int
1434 ctf_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
1435 {
1436   struct bt_iter_pos *pos;
1437   int found = 0;
1438
1439   gdb_assert (ctf_iter != NULL);
1440   /* Save the current position.  */
1441   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1442   gdb_assert (pos->type == BT_SEEK_RESTORE);
1443
1444   /* Iterate through the traceframe's blocks, looking for 'V'
1445      block.  */
1446   while (1)
1447     {
1448       struct bt_ctf_event *event
1449         = bt_ctf_iter_read_event (ctf_iter);
1450       const char *name = bt_ctf_event_name (event);
1451
1452       if (name == NULL || strcmp (name, "frame") == 0)
1453         break;
1454       else if (strcmp (name, "tsv") == 0)
1455         {
1456           const struct bt_definition *scope;
1457           const struct bt_definition *def;
1458
1459           scope = bt_ctf_get_top_level_scope (event,
1460                                               BT_EVENT_FIELDS);
1461
1462           def = bt_ctf_get_field (event, scope, "num");
1463           if (tsvnum == (int32_t) bt_ctf_get_uint64 (def))
1464             {
1465               def = bt_ctf_get_field (event, scope, "val");
1466               *val = bt_ctf_get_uint64 (def);
1467
1468               found = 1;
1469             }
1470         }
1471
1472       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1473         break;
1474     }
1475
1476   /* Restore the position.  */
1477   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1478
1479   return found;
1480 }
1481
1482 /* Return the tracepoint number in "frame" event.  */
1483
1484 static int
1485 ctf_get_tpnum_from_frame_event (struct bt_ctf_event *event)
1486 {
1487   /* The packet context of events has a field "tpnum".  */
1488   const struct bt_definition *scope
1489     = bt_ctf_get_top_level_scope (event, BT_STREAM_PACKET_CONTEXT);
1490   uint64_t tpnum
1491     = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "tpnum"));
1492
1493   return (int) tpnum;
1494 }
1495
1496 /* Return the address at which the current frame was collected.  */
1497
1498 static CORE_ADDR
1499 ctf_get_traceframe_address (void)
1500 {
1501   struct bt_ctf_event *event = NULL;
1502   struct bt_iter_pos *pos;
1503   CORE_ADDR addr = 0;
1504
1505   gdb_assert (ctf_iter != NULL);
1506   pos  = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1507   gdb_assert (pos->type == BT_SEEK_RESTORE);
1508
1509   while (1)
1510     {
1511       const char *name;
1512       struct bt_ctf_event *event1;
1513
1514       event1 = bt_ctf_iter_read_event (ctf_iter);
1515
1516       name = bt_ctf_event_name (event1);
1517
1518       if (name == NULL)
1519         break;
1520       else if (strcmp (name, "frame") == 0)
1521         {
1522           event = event1;
1523           break;
1524         }
1525
1526       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1527         break;
1528     }
1529
1530   if (event != NULL)
1531     {
1532       int tpnum = ctf_get_tpnum_from_frame_event (event);
1533       struct tracepoint *tp
1534         = get_tracepoint_by_number_on_target (tpnum);
1535
1536       if (tp && tp->loc)
1537         addr = tp->loc->address;
1538     }
1539
1540   /* Restore the position.  */
1541   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1542
1543   return addr;
1544 }
1545
1546 /* This is the implementation of target_ops method to_trace_find.
1547    Iterate the events whose name is "frame", extract the tracepoint
1548    number in it.  Return traceframe number when matched.  */
1549
1550 int
1551 ctf_target::trace_find (enum trace_find_type type, int num,
1552                         CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
1553 {
1554   int tfnum = 0;
1555   int found = 0;
1556
1557   if (num == -1)
1558     {
1559       if (tpp != NULL)
1560         *tpp = -1;
1561       return -1;
1562     }
1563
1564   gdb_assert (ctf_iter != NULL);
1565   /* Set iterator back to the start.  */
1566   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), start_pos);
1567
1568   while (1)
1569     {
1570       struct bt_ctf_event *event;
1571       const char *name;
1572
1573       event = bt_ctf_iter_read_event (ctf_iter);
1574
1575       name = bt_ctf_event_name (event);
1576
1577       if (event == NULL || name == NULL)
1578         break;
1579
1580       if (strcmp (name, "frame") == 0)
1581         {
1582           CORE_ADDR tfaddr;
1583
1584           if (type == tfind_number)
1585             {
1586               /* Looking for a specific trace frame.  */
1587               if (tfnum == num)
1588                 found = 1;
1589             }
1590           else
1591             {
1592               /* Start from the _next_ trace frame.  */
1593               if (tfnum > get_traceframe_number ())
1594                 {
1595                   switch (type)
1596                     {
1597                     case tfind_tp:
1598                       {
1599                         struct tracepoint *tp = get_tracepoint (num);
1600
1601                         if (tp != NULL
1602                             && (tp->number_on_target
1603                                 == ctf_get_tpnum_from_frame_event (event)))
1604                           found = 1;
1605                         break;
1606                       }
1607                     case tfind_pc:
1608                       tfaddr = ctf_get_traceframe_address ();
1609                       if (tfaddr == addr1)
1610                         found = 1;
1611                       break;
1612                     case tfind_range:
1613                       tfaddr = ctf_get_traceframe_address ();
1614                       if (addr1 <= tfaddr && tfaddr <= addr2)
1615                         found = 1;
1616                       break;
1617                     case tfind_outside:
1618                       tfaddr = ctf_get_traceframe_address ();
1619                       if (!(addr1 <= tfaddr && tfaddr <= addr2))
1620                         found = 1;
1621                       break;
1622                     default:
1623                       internal_error (__FILE__, __LINE__, _("unknown tfind type"));
1624                     }
1625                 }
1626             }
1627           if (found)
1628             {
1629               if (tpp != NULL)
1630                 *tpp = ctf_get_tpnum_from_frame_event (event);
1631
1632               /* Skip the event "frame".  */
1633               bt_iter_next (bt_ctf_get_iter (ctf_iter));
1634
1635               return tfnum;
1636             }
1637           tfnum++;
1638         }
1639
1640       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1641         break;
1642     }
1643
1644   return -1;
1645 }
1646
1647 /* This is the implementation of target_ops method to_traceframe_info.
1648    Iterate the events whose name is "memory", in current
1649    frame, extract memory range information, and return them in
1650    traceframe_info.  */
1651
1652 traceframe_info_up
1653 ctf_target::traceframe_info ()
1654 {
1655   traceframe_info_up info (new struct traceframe_info);
1656   const char *name;
1657   struct bt_iter_pos *pos;
1658
1659   gdb_assert (ctf_iter != NULL);
1660   /* Save the current position.  */
1661   pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
1662   gdb_assert (pos->type == BT_SEEK_RESTORE);
1663
1664   do
1665     {
1666       struct bt_ctf_event *event
1667         = bt_ctf_iter_read_event (ctf_iter);
1668
1669       name = bt_ctf_event_name (event);
1670
1671       if (name == NULL || strcmp (name, "register") == 0
1672           || strcmp (name, "frame") == 0)
1673         ;
1674       else if (strcmp (name, "memory") == 0)
1675         {
1676           const struct bt_definition *scope
1677             = bt_ctf_get_top_level_scope (event,
1678                                           BT_EVENT_FIELDS);
1679           const struct bt_definition *def;
1680
1681           def = bt_ctf_get_field (event, scope, "address");
1682           CORE_ADDR start = bt_ctf_get_uint64 (def);
1683
1684           def = bt_ctf_get_field (event, scope, "length");
1685           int length = (uint16_t) bt_ctf_get_uint64 (def);
1686
1687           info->memory.emplace_back (start, length);
1688         }
1689       else if (strcmp (name, "tsv") == 0)
1690         {
1691           int vnum;
1692           const struct bt_definition *scope
1693             = bt_ctf_get_top_level_scope (event,
1694                                           BT_EVENT_FIELDS);
1695           const struct bt_definition *def;
1696
1697           def = bt_ctf_get_field (event, scope, "num");
1698           vnum = (int) bt_ctf_get_uint64 (def);
1699           info->tvars.push_back (vnum);
1700         }
1701       else
1702         {
1703           warning (_("Unhandled trace block type (%s) "
1704                      "while building trace frame info."),
1705                    name);
1706         }
1707
1708       if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
1709         break;
1710     }
1711   while (name != NULL && strcmp (name, "frame") != 0);
1712
1713   /* Restore the position.  */
1714   bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
1715
1716   return info;
1717 }
1718
1719 #endif
1720
1721 /* module initialization */
1722
1723 void
1724 _initialize_ctf (void)
1725 {
1726 #if HAVE_LIBBABELTRACE
1727   add_target_with_completer (&ctf_ops, filename_completer);
1728 #endif
1729 }