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