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