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