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