1 /* Trace file support in GDB.
2 
3    Copyright (C) 1997-2024 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "tracefile.h"
21 #include "extract-store-integer.h"
22 #include "tracectf.h"
23 #include "exec.h"
24 #include "regcache.h"
25 #include "gdbsupport/byte-vector.h"
26 #include "gdbarch.h"
27 #include "gdbsupport/buildargv.h"
28 #include "inferior.h"
29 
30 /* Helper macros.  */
31 
32 #define TRACE_WRITE_R_BLOCK(writer, buf, size)    \
33   writer->ops->frame_ops->write_r_block ((writer), (buf), (size))
34 #define TRACE_WRITE_M_BLOCK_HEADER(writer, addr, size)                  \
35   writer->ops->frame_ops->write_m_block_header ((writer), (addr), \
36                                                             (size))
37 #define TRACE_WRITE_M_BLOCK_MEMORY(writer, buf, size)         \
38   writer->ops->frame_ops->write_m_block_memory ((writer), (buf), \
39                                                             (size))
40 #define TRACE_WRITE_V_BLOCK(writer, num, val)     \
41   writer->ops->frame_ops->write_v_block ((writer), (num), (val))
42 
43 /* A unique pointer policy class for trace_file_writer.  */
44 
45 struct trace_file_writer_deleter
46 {
operatortrace_file_writer_deleter47   void operator() (struct trace_file_writer *writer)
48   {
49     writer->ops->dtor (writer);
50     xfree (writer);
51   }
52 };
53 
54 /* A unique_ptr specialization for trace_file_writer.  */
55 
56 typedef std::unique_ptr<trace_file_writer, trace_file_writer_deleter>
57     trace_file_writer_up;
58 
59 /* Save tracepoint data to file named FILENAME through WRITER.  WRITER
60    determines the trace file format.  If TARGET_DOES_SAVE is non-zero,
61    the save is performed on the target, otherwise GDB obtains all trace
62    data and saves it locally.  */
63 
64 static void
trace_save(const char * filename,struct trace_file_writer * writer,int target_does_save)65 trace_save (const char *filename, struct trace_file_writer *writer,
66               int target_does_save)
67 {
68   struct trace_status *ts = current_trace_status ();
69   struct uploaded_tp *uploaded_tps = NULL, *utp;
70   struct uploaded_tsv *uploaded_tsvs = NULL, *utsv;
71 
72   ULONGEST offset = 0;
73 #define MAX_TRACE_UPLOAD 2000
74   gdb::byte_vector buf (std::max (MAX_TRACE_UPLOAD, trace_regblock_size));
75   bfd_endian byte_order = gdbarch_byte_order (current_inferior ()->arch ());
76 
77   /* If the target is to save the data to a file on its own, then just
78      send the command and be done with it.  */
79   if (target_does_save)
80     {
81       if (!writer->ops->target_save (writer, filename))
82           error (_("Target failed to save trace data to '%s'."),
83                  filename);
84       return;
85     }
86 
87   /* Get the trace status first before opening the file, so if the
88      target is losing, we can get out without touching files.  Since
89      we're just calling this for side effects, we ignore the
90      result.  */
91   target_get_trace_status (ts);
92 
93   writer->ops->start (writer, filename);
94 
95   writer->ops->write_header (writer);
96 
97   /* Write descriptive info.  */
98 
99   /* Write out the size of a register block.  */
100   writer->ops->write_regblock_type (writer, trace_regblock_size);
101 
102   /* Write out the target description info.  */
103   writer->ops->write_tdesc (writer);
104 
105   /* Write out status of the tracing run (aka "tstatus" info).  */
106   writer->ops->write_status (writer, ts);
107 
108   /* Note that we want to upload tracepoints and save those, rather
109      than simply writing out the local ones, because the user may have
110      changed tracepoints in GDB in preparation for a future tracing
111      run, or maybe just mass-deleted all types of breakpoints as part
112      of cleaning up.  So as not to contaminate the session, leave the
113      data in its uploaded form, don't make into real tracepoints.  */
114 
115   /* Get trace state variables first, they may be checked when parsing
116      uploaded commands.  */
117 
118   target_upload_trace_state_variables (&uploaded_tsvs);
119 
120   for (utsv = uploaded_tsvs; utsv; utsv = utsv->next)
121     writer->ops->write_uploaded_tsv (writer, utsv);
122 
123   free_uploaded_tsvs (&uploaded_tsvs);
124 
125   target_upload_tracepoints (&uploaded_tps);
126 
127   for (utp = uploaded_tps; utp; utp = utp->next)
128     target_get_tracepoint_status (NULL, utp);
129 
130   for (utp = uploaded_tps; utp; utp = utp->next)
131     writer->ops->write_uploaded_tp (writer, utp);
132 
133   free_uploaded_tps (&uploaded_tps);
134 
135   /* Mark the end of the definition section.  */
136   writer->ops->write_definition_end (writer);
137 
138   /* Get and write the trace data proper.  */
139   while (1)
140     {
141       LONGEST gotten = 0;
142 
143       /* The writer supports writing the contents of trace buffer
144             directly to trace file.  Don't parse the contents of trace
145             buffer.  */
146       if (writer->ops->write_trace_buffer != NULL)
147           {
148             /* We ask for big blocks, in the hopes of efficiency, but
149                will take less if the target has packet size limitations
150                or some such.  */
151             gotten = target_get_raw_trace_data (buf.data (), offset,
152                                                         MAX_TRACE_UPLOAD);
153             if (gotten < 0)
154               error (_("Failure to get requested trace buffer data"));
155             /* No more data is forthcoming, we're done.  */
156             if (gotten == 0)
157               break;
158 
159             writer->ops->write_trace_buffer (writer, buf.data (), gotten);
160 
161             offset += gotten;
162           }
163       else
164           {
165             uint16_t tp_num;
166             uint32_t tf_size;
167             /* Parse the trace buffers according to how data are stored
168                in trace buffer in GDBserver.  */
169 
170             gotten = target_get_raw_trace_data (buf.data (), offset, 6);
171 
172             if (gotten == 0)
173               break;
174 
175             /* Read the first six bytes in, which is the tracepoint
176                number and trace frame size.  */
177             tp_num = (uint16_t)
178               extract_unsigned_integer (&((buf.data ())[0]), 2, byte_order);
179 
180             tf_size = (uint32_t)
181               extract_unsigned_integer (&((buf.data ())[2]), 4, byte_order);
182 
183             writer->ops->frame_ops->start (writer, tp_num);
184             gotten = 6;
185 
186             if (tf_size > 0)
187               {
188                 unsigned int block;
189 
190                 offset += 6;
191 
192                 for (block = 0; block < tf_size; )
193                     {
194                       gdb_byte block_type;
195 
196                       /* We'll fetch one block each time, in order to
197                          handle the extremely large 'M' block.  We first
198                          fetch one byte to get the type of the block.  */
199                       gotten = target_get_raw_trace_data (buf.data (),
200                                                                   offset, 1);
201                       if (gotten < 1)
202                         error (_("Failure to get requested trace buffer data"));
203 
204                       gotten = 1;
205                       block += 1;
206                       offset += 1;
207 
208                       block_type = buf[0];
209                       switch (block_type)
210                         {
211                         case 'R':
212                           gotten
213                               = target_get_raw_trace_data (buf.data (), offset,
214                                                                  trace_regblock_size);
215                           if (gotten < trace_regblock_size)
216                               error (_("Failure to get requested trace"
217                                          " buffer data"));
218 
219                           TRACE_WRITE_R_BLOCK (writer, buf.data (),
220                                                      trace_regblock_size);
221                           break;
222                         case 'M':
223                           {
224                               unsigned short mlen;
225                               ULONGEST addr;
226                               LONGEST t;
227                               int j;
228 
229                               t = target_get_raw_trace_data (buf.data (),
230                                                                    offset, 10);
231                               if (t < 10)
232                                 error (_("Failure to get requested trace"
233                                            " buffer data"));
234 
235                               offset += 10;
236                               block += 10;
237 
238                               gotten = 0;
239                               addr = (ULONGEST)
240                                 extract_unsigned_integer (buf.data (), 8,
241                                                                 byte_order);
242                               mlen = (unsigned short)
243                                 extract_unsigned_integer (&((buf.data ())[8]), 2,
244                                                                 byte_order);
245 
246                               TRACE_WRITE_M_BLOCK_HEADER (writer, addr,
247                                                                 mlen);
248 
249                               /* The memory contents in 'M' block may be
250                                  very large.  Fetch the data from the target
251                                  and write them into file one by one.  */
252                               for (j = 0; j < mlen; )
253                                 {
254                                   unsigned int read_length;
255 
256                                   if (mlen - j > MAX_TRACE_UPLOAD)
257                                     read_length = MAX_TRACE_UPLOAD;
258                                   else
259                                     read_length = mlen - j;
260 
261                                   t = target_get_raw_trace_data (buf.data (),
262                                                                          offset + j,
263                                                                          read_length);
264                                   if (t < read_length)
265                                     error (_("Failure to get requested"
266                                                " trace buffer data"));
267 
268                                   TRACE_WRITE_M_BLOCK_MEMORY (writer,
269                                                                       buf.data (),
270                                                                       read_length);
271 
272                                   j += read_length;
273                                   gotten += read_length;
274                                 }
275 
276                               break;
277                           }
278                         case 'V':
279                           {
280                               int vnum;
281                               LONGEST val;
282 
283                               gotten
284                                 = target_get_raw_trace_data (buf.data (),
285                                                                    offset, 12);
286                               if (gotten < 12)
287                                 error (_("Failure to get requested"
288                                            " trace buffer data"));
289 
290                               vnum  = (int) extract_signed_integer (buf.data (),
291                                                                             4,
292                                                                             byte_order);
293                               val
294                                 = extract_signed_integer (&((buf.data ())[4]),
295                                                                 8, byte_order);
296 
297                               TRACE_WRITE_V_BLOCK (writer, vnum, val);
298                           }
299                           break;
300                         default:
301                           error (_("Unknown block type '%c' (0x%x) in"
302                                      " trace frame"),
303                                    block_type, block_type);
304                         }
305 
306                       block += gotten;
307                       offset += gotten;
308                     }
309               }
310             else
311               offset += gotten;
312 
313             writer->ops->frame_ops->end (writer);
314           }
315     }
316 
317   writer->ops->end (writer);
318 }
319 
320 static void
tsave_command(const char * args,int from_tty)321 tsave_command (const char *args, int from_tty)
322 {
323   int target_does_save = 0;
324   char **argv;
325   char *filename = NULL;
326   int generate_ctf = 0;
327 
328   if (args == NULL)
329     error_no_arg (_("file in which to save trace data"));
330 
331   gdb_argv built_argv (args);
332   argv = built_argv.get ();
333 
334   for (; *argv; ++argv)
335     {
336       if (strcmp (*argv, "-r") == 0)
337           target_does_save = 1;
338       else if (strcmp (*argv, "-ctf") == 0)
339           generate_ctf = 1;
340       else if (**argv == '-')
341           error (_("unknown option `%s'"), *argv);
342       else
343           filename = *argv;
344     }
345 
346   if (!filename)
347     error_no_arg (_("file in which to save trace data"));
348 
349   if (generate_ctf)
350     trace_save_ctf (filename, target_does_save);
351   else
352     trace_save_tfile (filename, target_does_save);
353 
354   if (from_tty)
355     gdb_printf (_("Trace data saved to %s '%s'.\n"),
356                     generate_ctf ? "directory" : "file", filename);
357 }
358 
359 /* Save the trace data to file FILENAME of tfile format.  */
360 
361 void
trace_save_tfile(const char * filename,int target_does_save)362 trace_save_tfile (const char *filename, int target_does_save)
363 {
364   trace_file_writer_up writer (tfile_trace_file_writer_new ());
365   trace_save (filename, writer.get (), target_does_save);
366 }
367 
368 /* Save the trace data to dir DIRNAME of ctf format.  */
369 
370 void
trace_save_ctf(const char * dirname,int target_does_save)371 trace_save_ctf (const char *dirname, int target_does_save)
372 {
373   trace_file_writer_up writer (ctf_trace_file_writer_new ());
374   trace_save (dirname, writer.get (), target_does_save);
375 }
376 
377 /* Fetch register data from tracefile, shared for both tfile and
378    ctf.  */
379 
380 void
tracefile_fetch_registers(struct regcache * regcache,int regno)381 tracefile_fetch_registers (struct regcache *regcache, int regno)
382 {
383   struct gdbarch *gdbarch = regcache->arch ();
384   struct tracepoint *tp = get_tracepoint (get_tracepoint_number ());
385   int regn;
386 
387   /* We get here if no register data has been found.  Mark registers
388      as unavailable.  */
389   for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
390     regcache->raw_supply (regn, NULL);
391 
392   /* We can often usefully guess that the PC is going to be the same
393      as the address of the tracepoint.  */
394   if (tp == nullptr || !tp->has_locations ())
395     return;
396 
397   /* But don't try to guess if tracepoint is multi-location...  */
398   if (tp->has_multiple_locations ())
399     {
400       warning (_("Tracepoint %d has multiple "
401                      "locations, cannot infer $pc"),
402                  tp->number);
403       return;
404     }
405   /* ... or does while-stepping.  */
406   else if (tp->step_count > 0)
407     {
408       warning (_("Tracepoint %d does while-stepping, "
409                      "cannot infer $pc"),
410                  tp->number);
411       return;
412     }
413 
414   /* Guess what we can from the tracepoint location.  */
415   gdbarch_guess_tracepoint_registers (gdbarch, regcache,
416                                               tp->first_loc ().address);
417 }
418 
419 /* This is the implementation of target_ops method to_has_all_memory.  */
420 
421 bool
has_all_memory()422 tracefile_target::has_all_memory ()
423 {
424   return true;
425 }
426 
427 /* This is the implementation of target_ops method to_has_memory.  */
428 
429 bool
has_memory()430 tracefile_target::has_memory ()
431 {
432   return true;
433 }
434 
435 /* This is the implementation of target_ops method to_has_stack.
436    The target has a stack when GDB has already selected one trace
437    frame.  */
438 
439 bool
has_stack()440 tracefile_target::has_stack ()
441 {
442   return get_traceframe_number () != -1;
443 }
444 
445 /* This is the implementation of target_ops method to_has_registers.
446    The target has registers when GDB has already selected one trace
447    frame.  */
448 
449 bool
has_registers()450 tracefile_target::has_registers ()
451 {
452   return get_traceframe_number () != -1;
453 }
454 
455 /* This is the implementation of target_ops method to_thread_alive.
456    tracefile has one thread faked by GDB.  */
457 
458 bool
thread_alive(ptid_t ptid)459 tracefile_target::thread_alive (ptid_t ptid)
460 {
461   return true;
462 }
463 
464 /* This is the implementation of target_ops method to_get_trace_status.
465    The trace status for a file is that tracing can never be run.  */
466 
467 int
get_trace_status(struct trace_status * ts)468 tracefile_target::get_trace_status (struct trace_status *ts)
469 {
470   /* Other bits of trace status were collected as part of opening the
471      trace files, so nothing to do here.  */
472 
473   return -1;
474 }
475 
476 void _initialize_tracefile ();
477 void
_initialize_tracefile()478 _initialize_tracefile ()
479 {
480   add_com ("tsave", class_trace, tsave_command, _("\
481 Save the trace data to a file.\n\
482 Use the '-ctf' option to save the data to CTF format.\n\
483 Use the '-r' option to direct the target to save directly to the file,\n\
484 using its own filesystem."));
485 }
486