]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/tracepoint.c
c0f1eae334340e70c2fb9073a5259f8b8fa69613
[thirdparty/binutils-gdb.git] / gdb / tracepoint.c
1 /* Tracing functionality for remote targets in custom GDB protocol
2
3 Copyright (C) 1997-2025 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 "arch-utils.h"
21 #include "event-top.h"
22 #include "symtab.h"
23 #include "frame.h"
24 #include "gdbtypes.h"
25 #include "expression.h"
26 #include "cli/cli-cmds.h"
27 #include "value.h"
28 #include "target.h"
29 #include "target-dcache.h"
30 #include "language.h"
31 #include "inferior.h"
32 #include "breakpoint.h"
33 #include "tracepoint.h"
34 #include "linespec.h"
35 #include "regcache.h"
36 #include "completer.h"
37 #include "block.h"
38 #include "dictionary.h"
39 #include "observable.h"
40 #include "user-regs.h"
41 #include "valprint.h"
42 #include "gdbcore.h"
43 #include "objfiles.h"
44 #include "filenames.h"
45 #include "gdbthread.h"
46 #include "stack.h"
47 #include "remote.h"
48 #include "source.h"
49 #include "ax.h"
50 #include "ax-gdb.h"
51 #include "memrange.h"
52 #include "cli/cli-utils.h"
53 #include "probe.h"
54 #include "gdbsupport/filestuff.h"
55 #include "gdbsupport/rsp-low.h"
56 #include "tracefile.h"
57 #include "location.h"
58 #include <algorithm>
59 #include "cli/cli-style.h"
60 #include "expop.h"
61 #include "gdbsupport/buildargv.h"
62 #include "interps.h"
63
64 #include <unistd.h>
65
66 /* Maximum length of an agent aexpression.
67 This accounts for the fact that packets are limited to 400 bytes
68 (which includes everything -- including the checksum), and assumes
69 the worst case of maximum length for each of the pieces of a
70 continuation packet.
71
72 NOTE: expressions get bin2hex'ed otherwise this would be twice as
73 large. (400 - 31)/2 == 184 */
74 #define MAX_AGENT_EXPR_LEN 184
75
76 /*
77 Tracepoint.c:
78
79 This module defines the following debugger commands:
80 trace : set a tracepoint on a function, line, or address.
81 info trace : list all debugger-defined tracepoints.
82 delete trace : delete one or more tracepoints.
83 enable trace : enable one or more tracepoints.
84 disable trace : disable one or more tracepoints.
85 actions : specify actions to be taken at a tracepoint.
86 passcount : specify a pass count for a tracepoint.
87 tstart : start a trace experiment.
88 tstop : stop a trace experiment.
89 tstatus : query the status of a trace experiment.
90 tfind : find a trace frame in the trace buffer.
91 tdump : print everything collected at the current tracepoint.
92 save-tracepoints : write tracepoint setup into a file.
93
94 This module defines the following user-visible debugger variables:
95 $trace_frame : sequence number of trace frame currently being debugged.
96 $trace_line : source line of trace frame currently being debugged.
97 $trace_file : source file of trace frame currently being debugged.
98 $tracepoint : tracepoint number of trace frame currently being debugged.
99 */
100
101
102 /* ======= Important global variables: ======= */
103
104 /* The list of all trace state variables. We don't retain pointers to
105 any of these for any reason - API is by name or number only - so it
106 works to have a vector of objects. */
107
108 static std::vector<trace_state_variable> tvariables;
109
110 /* The next integer to assign to a variable. */
111
112 static int next_tsv_number = 1;
113
114 /* Number of last traceframe collected. */
115 static int traceframe_number;
116
117 /* Tracepoint for last traceframe collected. */
118 static int tracepoint_number;
119
120 /* The traceframe info of the current traceframe. NULL if we haven't
121 yet attempted to fetch it, or if the target does not support
122 fetching this object, or if we're not inspecting a traceframe
123 presently. */
124 static traceframe_info_up current_traceframe_info;
125
126 /* Tracing command lists. */
127 static struct cmd_list_element *tfindlist;
128
129 /* List of expressions to collect by default at each tracepoint hit. */
130 std::string default_collect;
131
132 static bool disconnected_tracing;
133
134 /* This variable controls whether we ask the target for a linear or
135 circular trace buffer. */
136
137 static bool circular_trace_buffer;
138
139 /* This variable is the requested trace buffer size, or -1 to indicate
140 that we don't care and leave it up to the target to set a size. */
141
142 static int trace_buffer_size = -1;
143
144 /* Textual notes applying to the current and/or future trace runs. */
145
146 static std::string trace_user;
147
148 /* Textual notes applying to the current and/or future trace runs. */
149
150 static std::string trace_notes;
151
152 /* Textual notes applying to the stopping of a trace. */
153
154 static std::string trace_stop_notes;
155
156 /* support routines */
157
158 struct collection_list;
159
160 static counted_command_line all_tracepoint_actions (tracepoint *);
161
162 static struct trace_status trace_status;
163
164 const char *stop_reason_names[] = {
165 "tunknown",
166 "tnotrun",
167 "tstop",
168 "tfull",
169 "tdisconnected",
170 "tpasscount",
171 "terror"
172 };
173
174 struct trace_status *
175 current_trace_status (void)
176 {
177 return &trace_status;
178 }
179
180 /* Free and clear the traceframe info cache of the current
181 traceframe. */
182
183 static void
184 clear_traceframe_info (void)
185 {
186 current_traceframe_info = NULL;
187 }
188
189 /* Set traceframe number to NUM. */
190 static void
191 set_traceframe_num (int num)
192 {
193 traceframe_number = num;
194 set_internalvar_integer (lookup_internalvar ("trace_frame"), num);
195 }
196
197 /* Set tracepoint number to NUM. */
198 static void
199 set_tracepoint_num (int num)
200 {
201 tracepoint_number = num;
202 set_internalvar_integer (lookup_internalvar ("tracepoint"), num);
203 }
204
205 /* Set externally visible debug variables for querying/printing
206 the traceframe context (line, function, file). */
207
208 static void
209 set_traceframe_context (const frame_info_ptr &trace_frame)
210 {
211 CORE_ADDR trace_pc;
212 struct symbol *traceframe_fun;
213 symtab_and_line traceframe_sal;
214
215 /* Save as globals for internal use. */
216 if (trace_frame != NULL
217 && get_frame_pc_if_available (trace_frame, &trace_pc))
218 {
219 traceframe_sal = find_pc_line (trace_pc, 0);
220 traceframe_fun = find_pc_function (trace_pc);
221
222 /* Save linenumber as "$trace_line", a debugger variable visible to
223 users. */
224 set_internalvar_integer (lookup_internalvar ("trace_line"),
225 traceframe_sal.line);
226 }
227 else
228 {
229 traceframe_fun = NULL;
230 set_internalvar_integer (lookup_internalvar ("trace_line"), -1);
231 }
232
233 /* Save func name as "$trace_func", a debugger variable visible to
234 users. */
235 if (traceframe_fun == NULL
236 || traceframe_fun->linkage_name () == NULL)
237 clear_internalvar (lookup_internalvar ("trace_func"));
238 else
239 set_internalvar_string (lookup_internalvar ("trace_func"),
240 traceframe_fun->linkage_name ());
241
242 /* Save file name as "$trace_file", a debugger variable visible to
243 users. */
244 if (traceframe_sal.symtab == NULL)
245 clear_internalvar (lookup_internalvar ("trace_file"));
246 else
247 set_internalvar_string (lookup_internalvar ("trace_file"),
248 symtab_to_filename_for_display (traceframe_sal.symtab));
249 }
250
251 /* Create a new trace state variable with the given name. */
252
253 struct trace_state_variable *
254 create_trace_state_variable (const char *name)
255 {
256 return &tvariables.emplace_back (name, next_tsv_number++);
257 }
258
259 /* Look for a trace state variable of the given name. */
260
261 struct trace_state_variable *
262 find_trace_state_variable (const char *name)
263 {
264 for (trace_state_variable &tsv : tvariables)
265 if (tsv.name == name)
266 return &tsv;
267
268 return NULL;
269 }
270
271 /* Look for a trace state variable of the given number. Return NULL if
272 not found. */
273
274 struct trace_state_variable *
275 find_trace_state_variable_by_number (int number)
276 {
277 for (trace_state_variable &tsv : tvariables)
278 if (tsv.number == number)
279 return &tsv;
280
281 return NULL;
282 }
283
284 static void
285 delete_trace_state_variable (const char *name)
286 {
287 for (auto it = tvariables.begin (); it != tvariables.end (); it++)
288 if (it->name == name)
289 {
290 interps_notify_tsv_deleted (&*it);
291 tvariables.erase (it);
292 return;
293 }
294
295 warning (_("No trace variable named \"$%s\", not deleting"), name);
296 }
297
298 /* Throws an error if NAME is not valid syntax for a trace state
299 variable's name. */
300
301 void
302 validate_trace_state_variable_name (const char *name)
303 {
304 const char *p;
305
306 if (*name == '\0')
307 error (_("Must supply a non-empty variable name"));
308
309 /* All digits in the name is reserved for value history
310 references. */
311 for (p = name; isdigit (*p); p++)
312 ;
313 if (*p == '\0')
314 error (_("$%s is not a valid trace state variable name"), name);
315
316 for (p = name; isalnum (*p) || *p == '_'; p++)
317 ;
318 if (*p != '\0')
319 error (_("$%s is not a valid trace state variable name"), name);
320 }
321
322 /* The 'tvariable' command collects a name and optional expression to
323 evaluate into an initial value. */
324
325 static void
326 trace_variable_command (const char *args, int from_tty)
327 {
328 LONGEST initval = 0;
329 struct trace_state_variable *tsv;
330 const char *name_start, *p;
331
332 if (!args || !*args)
333 error_no_arg (_("Syntax is $NAME [ = EXPR ]"));
334
335 /* Only allow two syntaxes; "$name" and "$name=value". */
336 p = skip_spaces (args);
337
338 if (*p++ != '$')
339 error (_("Name of trace variable should start with '$'"));
340
341 name_start = p;
342 while (isalnum (*p) || *p == '_')
343 p++;
344 std::string name (name_start, p - name_start);
345
346 p = skip_spaces (p);
347 if (*p != '=' && *p != '\0')
348 error (_("Syntax must be $NAME [ = EXPR ]"));
349
350 validate_trace_state_variable_name (name.c_str ());
351
352 if (*p == '=')
353 initval = value_as_long (parse_and_eval (++p));
354
355 /* If the variable already exists, just change its initial value. */
356 tsv = find_trace_state_variable (name.c_str ());
357 if (tsv)
358 {
359 if (tsv->initial_value != initval)
360 {
361 tsv->initial_value = initval;
362 interps_notify_tsv_modified (tsv);
363 }
364 gdb_printf (_("Trace state variable $%s "
365 "now has initial value %s.\n"),
366 tsv->name.c_str (), plongest (tsv->initial_value));
367 return;
368 }
369
370 /* Create a new variable. */
371 tsv = create_trace_state_variable (name.c_str ());
372 tsv->initial_value = initval;
373
374 interps_notify_tsv_created (tsv);
375
376 gdb_printf (_("Trace state variable $%s "
377 "created, with initial value %s.\n"),
378 tsv->name.c_str (), plongest (tsv->initial_value));
379 }
380
381 static void
382 delete_trace_variable_command (const char *args, int from_tty)
383 {
384 if (args == NULL)
385 {
386 if (query (_("Delete all trace state variables? ")))
387 tvariables.clear ();
388 dont_repeat ();
389 interps_notify_tsv_deleted (nullptr);
390 return;
391 }
392
393 gdb_argv argv (args);
394
395 for (char *arg : argv)
396 {
397 if (*arg == '$')
398 delete_trace_state_variable (arg + 1);
399 else
400 warning (_("Name \"%s\" not prefixed with '$', ignoring"), arg);
401 }
402
403 dont_repeat ();
404 }
405
406 void
407 tvariables_info_1 (void)
408 {
409 struct ui_out *uiout = current_uiout;
410
411 /* Try to acquire values from the target. */
412 for (trace_state_variable &tsv : tvariables)
413 tsv.value_known
414 = target_get_trace_state_variable_value (tsv.number, &tsv.value);
415
416 {
417 ui_out_emit_table table_emitter (uiout, 3, tvariables.size (),
418 "trace-variables");
419 uiout->table_header (15, ui_left, "name", "Name");
420 uiout->table_header (11, ui_left, "initial", "Initial");
421 uiout->table_header (11, ui_left, "current", "Current");
422
423 uiout->table_body ();
424
425 for (const trace_state_variable &tsv : tvariables)
426 {
427 const char *c;
428
429 ui_out_emit_tuple tuple_emitter (uiout, "variable");
430
431 uiout->field_string ("name", std::string ("$") + tsv.name);
432 uiout->field_string ("initial", plongest (tsv.initial_value));
433
434 ui_file_style style;
435 if (tsv.value_known)
436 c = plongest (tsv.value);
437 else if (uiout->is_mi_like_p ())
438 /* For MI, we prefer not to use magic string constants, but rather
439 omit the field completely. The difference between unknown and
440 undefined does not seem important enough to represent. */
441 c = NULL;
442 else if (current_trace_status ()->running || traceframe_number >= 0)
443 {
444 /* The value is/was defined, but we don't have it. */
445 c = "<unknown>";
446 style = metadata_style.style ();
447 }
448 else
449 {
450 /* It is not meaningful to ask about the value. */
451 c = "<undefined>";
452 style = metadata_style.style ();
453 }
454 if (c)
455 uiout->field_string ("current", c, style);
456 uiout->text ("\n");
457 }
458 }
459
460 if (tvariables.empty ())
461 uiout->text (_("No trace state variables.\n"));
462 }
463
464 /* List all the trace state variables. */
465
466 static void
467 info_tvariables_command (const char *args, int from_tty)
468 {
469 tvariables_info_1 ();
470 }
471
472 /* Stash definitions of tsvs into the given file. */
473
474 void
475 save_trace_state_variables (struct ui_file *fp)
476 {
477 for (const trace_state_variable &tsv : tvariables)
478 {
479 gdb_printf (fp, "tvariable $%s", tsv.name.c_str ());
480 if (tsv.initial_value)
481 gdb_printf (fp, " = %s", plongest (tsv.initial_value));
482 gdb_printf (fp, "\n");
483 }
484 }
485
486 /* ACTIONS functions: */
487
488 /* The three functions:
489 collect_pseudocommand,
490 while_stepping_pseudocommand, and
491 end_actions_pseudocommand
492 are placeholders for "commands" that are actually ONLY to be used
493 within a tracepoint action list. If the actual function is ever called,
494 it means that somebody issued the "command" at the top level,
495 which is always an error. */
496
497 static void
498 end_actions_pseudocommand (const char *args, int from_tty)
499 {
500 error (_("This command cannot be used at the top level."));
501 }
502
503 static void
504 while_stepping_pseudocommand (const char *args, int from_tty)
505 {
506 error (_("This command can only be used in a tracepoint actions list."));
507 }
508
509 static void
510 collect_pseudocommand (const char *args, int from_tty)
511 {
512 error (_("This command can only be used in a tracepoint actions list."));
513 }
514
515 static void
516 teval_pseudocommand (const char *args, int from_tty)
517 {
518 error (_("This command can only be used in a tracepoint actions list."));
519 }
520
521 /* Parse any collection options, such as /s for strings. */
522
523 const char *
524 decode_agent_options (const char *exp, int *trace_string)
525 {
526 struct value_print_options opts;
527
528 *trace_string = 0;
529
530 if (*exp != '/')
531 return exp;
532
533 /* Call this to borrow the print elements default for collection
534 size. */
535 get_user_print_options (&opts);
536
537 exp++;
538 if (*exp == 's')
539 {
540 if (target_supports_string_tracing ())
541 {
542 /* Allow an optional decimal number giving an explicit maximum
543 string length, defaulting it to the "print characters" value;
544 so "collect/s80 mystr" gets at most 80 bytes of string. */
545 *trace_string = get_print_max_chars (&opts);
546 exp++;
547 if (*exp >= '0' && *exp <= '9')
548 *trace_string = atoi (exp);
549 while (*exp >= '0' && *exp <= '9')
550 exp++;
551 }
552 else
553 error (_("Target does not support \"/s\" option for string tracing."));
554 }
555 else
556 error (_("Undefined collection format \"%c\"."), *exp);
557
558 exp = skip_spaces (exp);
559
560 return exp;
561 }
562
563 /* Enter a list of actions for a tracepoint. */
564 static void
565 actions_command (const char *args, int from_tty)
566 {
567 struct tracepoint *t;
568
569 t = get_tracepoint_by_number (&args, NULL);
570 if (t)
571 {
572 std::string tmpbuf =
573 string_printf ("Enter actions for tracepoint %d, one per line.",
574 t->number);
575
576 counted_command_line l = read_command_lines (tmpbuf.c_str (),
577 from_tty, 1,
578 [=] (const char *line)
579 {
580 validate_actionline (line, t);
581 });
582 breakpoint_set_commands (t, std::move (l));
583 }
584 /* else just return */
585 }
586
587 /* Report the results of checking the agent expression, as errors or
588 internal errors. */
589
590 static void
591 report_agent_reqs_errors (struct agent_expr *aexpr)
592 {
593 /* All of the "flaws" are serious bytecode generation issues that
594 should never occur. */
595 if (aexpr->flaw != agent_flaw_none)
596 internal_error (_("expression is malformed"));
597
598 /* If analysis shows a stack underflow, GDB must have done something
599 badly wrong in its bytecode generation. */
600 if (aexpr->min_height < 0)
601 internal_error (_("expression has min height < 0"));
602
603 /* Issue this error if the stack is predicted to get too deep. The
604 limit is rather arbitrary; a better scheme might be for the
605 target to report how much stack it will have available. The
606 depth roughly corresponds to parenthesization, so a limit of 20
607 amounts to 20 levels of expression nesting, which is actually
608 a pretty big hairy expression. */
609 if (aexpr->max_height > 20)
610 error (_("Expression is too complicated."));
611 }
612
613 /* Call ax_reqs on AEXPR and raise an error if something is wrong. */
614
615 static void
616 finalize_tracepoint_aexpr (struct agent_expr *aexpr)
617 {
618 ax_reqs (aexpr);
619
620 if (aexpr->buf.size () > MAX_AGENT_EXPR_LEN)
621 error (_("Expression is too complicated."));
622
623 report_agent_reqs_errors (aexpr);
624 }
625
626 /* worker function */
627 void
628 validate_actionline (const char *line, tracepoint *t)
629 {
630 struct cmd_list_element *c;
631 const char *tmp_p;
632 const char *p;
633
634 /* If EOF is typed, *line is NULL. */
635 if (line == NULL)
636 return;
637
638 p = skip_spaces (line);
639
640 /* Symbol lookup etc. */
641 if (*p == '\0') /* empty line: just prompt for another line. */
642 return;
643
644 if (*p == '#') /* comment line */
645 return;
646
647 c = lookup_cmd (&p, cmdlist, "", NULL, -1, 1);
648 if (c == 0)
649 error (_("`%s' is not a tracepoint action, or is ambiguous."), p);
650
651 if (cmd_simple_func_eq (c, collect_pseudocommand))
652 {
653 int trace_string = 0;
654
655 if (*p == '/')
656 p = decode_agent_options (p, &trace_string);
657
658 do
659 { /* Repeat over a comma-separated list. */
660 QUIT; /* Allow user to bail out with ^C. */
661 p = skip_spaces (p);
662
663 if (*p == '$') /* Look for special pseudo-symbols. */
664 {
665 if (0 == strncasecmp ("reg", p + 1, 3)
666 || 0 == strncasecmp ("arg", p + 1, 3)
667 || 0 == strncasecmp ("loc", p + 1, 3)
668 || 0 == strncasecmp ("_ret", p + 1, 4)
669 || 0 == strncasecmp ("_sdata", p + 1, 6))
670 {
671 p = strchr (p, ',');
672 continue;
673 }
674 /* else fall through, treat p as an expression and parse it! */
675 }
676 tmp_p = p;
677 for (bp_location &loc : t->locations ())
678 {
679 p = tmp_p;
680 expression_up exp = parse_exp_1 (&p, loc.address,
681 block_for_pc (loc.address),
682 PARSER_COMMA_TERMINATES);
683
684 if (exp->first_opcode () == OP_VAR_VALUE)
685 {
686 symbol *sym;
687 expr::var_value_operation *vvop
688 = (gdb::checked_static_cast<expr::var_value_operation *>
689 (exp->op.get ()));
690 sym = vvop->get_symbol ();
691
692 if (sym->aclass () == LOC_CONST)
693 {
694 error (_("constant `%s' (value %s) "
695 "will not be collected."),
696 sym->print_name (),
697 plongest (sym->value_longest ()));
698 }
699 else if (sym->aclass () == LOC_OPTIMIZED_OUT)
700 {
701 error (_("`%s' is optimized away "
702 "and cannot be collected."),
703 sym->print_name ());
704 }
705 }
706
707 /* We have something to collect, make sure that the expr to
708 bytecode translator can handle it and that it's not too
709 long. */
710 agent_expr_up aexpr = gen_trace_for_expr (loc.address,
711 exp.get (),
712 trace_string);
713
714 finalize_tracepoint_aexpr (aexpr.get ());
715 }
716 }
717 while (p && *p++ == ',');
718 }
719
720 else if (cmd_simple_func_eq (c, teval_pseudocommand))
721 {
722 do
723 { /* Repeat over a comma-separated list. */
724 QUIT; /* Allow user to bail out with ^C. */
725 p = skip_spaces (p);
726
727 tmp_p = p;
728 for (bp_location &loc : t->locations ())
729 {
730 p = tmp_p;
731
732 /* Only expressions are allowed for this action. */
733 expression_up exp = parse_exp_1 (&p, loc.address,
734 block_for_pc (loc.address),
735 PARSER_COMMA_TERMINATES);
736
737 /* We have something to evaluate, make sure that the expr to
738 bytecode translator can handle it and that it's not too
739 long. */
740 agent_expr_up aexpr = gen_eval_for_expr (loc.address, exp.get ());
741
742 finalize_tracepoint_aexpr (aexpr.get ());
743 }
744 }
745 while (p && *p++ == ',');
746 }
747
748 else if (cmd_simple_func_eq (c, while_stepping_pseudocommand))
749 {
750 char *endp;
751
752 p = skip_spaces (p);
753 t->step_count = strtol (p, &endp, 0);
754 if (endp == p || t->step_count == 0)
755 error (_("while-stepping step count `%s' is malformed."), line);
756 p = endp;
757 }
758
759 else if (cmd_simple_func_eq (c, end_actions_pseudocommand))
760 ;
761
762 else
763 error (_("`%s' is not a supported tracepoint action."), line);
764 }
765
766 enum {
767 memrange_absolute = -1
768 };
769
770 /* MEMRANGE functions: */
771
772 /* Compare memranges for std::sort. */
773
774 static bool
775 memrange_comp (const memrange &a, const memrange &b)
776 {
777 if (a.type == b.type)
778 {
779 if (a.type == memrange_absolute)
780 return (bfd_vma) a.start < (bfd_vma) b.start;
781 else
782 return a.start < b.start;
783 }
784
785 return a.type < b.type;
786 }
787
788 /* Sort the memrange list using std::sort, and merge adjacent memranges. */
789
790 static void
791 memrange_sortmerge (std::vector<memrange> &memranges)
792 {
793 if (!memranges.empty ())
794 {
795 int a, b;
796
797 std::sort (memranges.begin (), memranges.end (), memrange_comp);
798
799 for (a = 0, b = 1; b < memranges.size (); b++)
800 {
801 /* If memrange b overlaps or is adjacent to memrange a,
802 merge them. */
803 if (memranges[a].type == memranges[b].type
804 && memranges[b].start <= memranges[a].end)
805 {
806 if (memranges[b].end > memranges[a].end)
807 memranges[a].end = memranges[b].end;
808 continue; /* next b, same a */
809 }
810 a++; /* next a */
811 if (a != b)
812 memranges[a] = memranges[b];
813 }
814 memranges.resize (a + 1);
815 }
816 }
817
818 /* Add remote register number REGNO to the collection list mask. */
819
820 void
821 collection_list::add_remote_register (unsigned int regno)
822 {
823 if (info_verbose)
824 gdb_printf ("collect register %d\n", regno);
825
826 m_regs_mask.at (regno / 8) |= 1 << (regno % 8);
827 }
828
829 /* Add all the registers from the mask in AEXPR to the mask in the
830 collection list. Registers in the AEXPR mask are already remote
831 register numbers. */
832
833 void
834 collection_list::add_ax_registers (struct agent_expr *aexpr)
835 {
836 for (int ndx1 = 0; ndx1 < aexpr->reg_mask.size (); ndx1++)
837 {
838 QUIT; /* Allow user to bail out with ^C. */
839 if (aexpr->reg_mask[ndx1])
840 {
841 /* It's used -- record it. */
842 add_remote_register (ndx1);
843 }
844 }
845 }
846
847 /* If REGNO is raw, add its corresponding remote register number to
848 the mask. If REGNO is a pseudo-register, figure out the necessary
849 registers using a temporary agent expression, and add it to the
850 list if it needs more than just a mask. */
851
852 void
853 collection_list::add_local_register (struct gdbarch *gdbarch,
854 unsigned int regno,
855 CORE_ADDR scope)
856 {
857 if (regno < gdbarch_num_regs (gdbarch))
858 {
859 int remote_regno = gdbarch_remote_register_number (gdbarch, regno);
860
861 if (remote_regno < 0)
862 error (_("Can't collect register %d"), regno);
863
864 add_remote_register (remote_regno);
865 }
866 else
867 {
868 agent_expr_up aexpr (new agent_expr (gdbarch, scope));
869
870 ax_reg_mask (aexpr.get (), regno);
871
872 finalize_tracepoint_aexpr (aexpr.get ());
873
874 add_ax_registers (aexpr.get ());
875
876 /* Usually ax_reg_mask for a pseudo-regiser only sets the
877 corresponding raw registers in the ax mask, but if this isn't
878 the case add the expression that is generated to the
879 collection list. */
880 if (aexpr->buf.size () > 0)
881 add_aexpr (std::move (aexpr));
882 }
883 }
884
885 /* Add a memrange to a collection list. */
886
887 void
888 collection_list::add_memrange (struct gdbarch *gdbarch,
889 int type, bfd_signed_vma base,
890 unsigned long len, CORE_ADDR scope)
891 {
892 if (info_verbose)
893 gdb_printf ("(%d,%s,%ld)\n", type, paddress (gdbarch, base), len);
894
895 /* type: memrange_absolute == memory, other n == basereg */
896 /* base: addr if memory, offset if reg relative. */
897 /* len: we actually save end (base + len) for convenience */
898 m_memranges.emplace_back (type, base, base + len);
899
900 if (type != memrange_absolute) /* Better collect the base register! */
901 add_local_register (gdbarch, type, scope);
902 }
903
904 /* Add a symbol to a collection list. */
905
906 void
907 collection_list::collect_symbol (struct symbol *sym,
908 struct gdbarch *gdbarch,
909 long frame_regno, long frame_offset,
910 CORE_ADDR scope,
911 int trace_string)
912 {
913 unsigned long len;
914 unsigned int reg;
915 bfd_signed_vma offset;
916 int treat_as_expr = 0;
917
918 len = check_typedef (sym->type ())->length ();
919 switch (sym->aclass ())
920 {
921 default:
922 gdb_printf ("%s: don't know symbol class %d\n",
923 sym->print_name (), sym->aclass ());
924 break;
925 case LOC_CONST:
926 gdb_printf ("constant %s (value %s) will not be collected.\n",
927 sym->print_name (), plongest (sym->value_longest ()));
928 break;
929 case LOC_STATIC:
930 offset = sym->value_address ();
931 if (info_verbose)
932 {
933 gdb_printf ("LOC_STATIC %s: collect %ld bytes at %s.\n",
934 sym->print_name (), len,
935 paddress (gdbarch, offset));
936 }
937 /* A struct may be a C++ class with static fields, go to general
938 expression handling. */
939 if (sym->type ()->code () == TYPE_CODE_STRUCT)
940 treat_as_expr = 1;
941 else
942 add_memrange (gdbarch, memrange_absolute, offset, len, scope);
943 break;
944 case LOC_REGISTER:
945 reg = sym->register_ops ()->register_number (sym, gdbarch);
946 if (info_verbose)
947 gdb_printf ("LOC_REG[parm] %s: ", sym->print_name ());
948 add_local_register (gdbarch, reg, scope);
949 /* Check for doubles stored in two registers. */
950 /* FIXME: how about larger types stored in 3 or more regs? */
951 if (sym->type ()->code () == TYPE_CODE_FLT &&
952 len > register_size (gdbarch, reg))
953 add_local_register (gdbarch, reg + 1, scope);
954 break;
955 case LOC_REF_ARG:
956 gdb_printf ("Sorry, don't know how to do LOC_REF_ARG yet.\n");
957 gdb_printf (" (will not collect %s)\n", sym->print_name ());
958 break;
959 case LOC_ARG:
960 reg = frame_regno;
961 offset = frame_offset + sym->value_longest ();
962 if (info_verbose)
963 {
964 gdb_printf ("LOC_LOCAL %s: Collect %ld bytes at offset %s"
965 " from frame ptr reg %d\n", sym->print_name (), len,
966 paddress (gdbarch, offset), reg);
967 }
968 add_memrange (gdbarch, reg, offset, len, scope);
969 break;
970 case LOC_REGPARM_ADDR:
971 reg = sym->value_longest ();
972 offset = 0;
973 if (info_verbose)
974 {
975 gdb_printf ("LOC_REGPARM_ADDR %s: Collect %ld bytes at offset %s"
976 " from reg %d\n", sym->print_name (), len,
977 paddress (gdbarch, offset), reg);
978 }
979 add_memrange (gdbarch, reg, offset, len, scope);
980 break;
981 case LOC_LOCAL:
982 reg = frame_regno;
983 offset = frame_offset + sym->value_longest ();
984 if (info_verbose)
985 {
986 gdb_printf ("LOC_LOCAL %s: Collect %ld bytes at offset %s"
987 " from frame ptr reg %d\n", sym->print_name (), len,
988 paddress (gdbarch, offset), reg);
989 }
990 add_memrange (gdbarch, reg, offset, len, scope);
991 break;
992
993 case LOC_UNRESOLVED:
994 treat_as_expr = 1;
995 break;
996
997 case LOC_OPTIMIZED_OUT:
998 gdb_printf ("%s has been optimized out of existence.\n",
999 sym->print_name ());
1000 break;
1001
1002 case LOC_COMPUTED:
1003 treat_as_expr = 1;
1004 break;
1005 }
1006
1007 /* Expressions are the most general case. */
1008 if (treat_as_expr)
1009 {
1010 agent_expr_up aexpr = gen_trace_for_var (scope, gdbarch,
1011 sym, trace_string);
1012
1013 /* It can happen that the symbol is recorded as a computed
1014 location, but it's been optimized away and doesn't actually
1015 have a location expression. */
1016 if (!aexpr)
1017 {
1018 gdb_printf ("%s has been optimized out of existence.\n",
1019 sym->print_name ());
1020 return;
1021 }
1022
1023 finalize_tracepoint_aexpr (aexpr.get ());
1024
1025 /* Take care of the registers. */
1026 add_ax_registers (aexpr.get ());
1027
1028 add_aexpr (std::move (aexpr));
1029 }
1030 }
1031
1032 void
1033 collection_list::add_wholly_collected (const char *print_name)
1034 {
1035 m_wholly_collected.push_back (print_name);
1036 }
1037
1038 /* Add all locals (or args) symbols to collection list. */
1039
1040 void
1041 collection_list::add_local_symbols (struct gdbarch *gdbarch, CORE_ADDR pc,
1042 long frame_regno, long frame_offset, int type,
1043 int trace_string)
1044 {
1045 const struct block *block;
1046 int count = 0;
1047
1048 auto do_collect_symbol = [&] (const char *print_name,
1049 struct symbol *sym)
1050 {
1051 collect_symbol (sym, gdbarch, frame_regno,
1052 frame_offset, pc, trace_string);
1053 count++;
1054 add_wholly_collected (print_name);
1055 };
1056
1057 if (type == 'L')
1058 {
1059 block = block_for_pc (pc);
1060 if (block == NULL)
1061 {
1062 warning (_("Can't collect locals; "
1063 "no symbol table info available.\n"));
1064 return;
1065 }
1066
1067 iterate_over_block_local_vars (block, do_collect_symbol);
1068 if (count == 0)
1069 warning (_("No locals found in scope."));
1070 }
1071 else
1072 {
1073 CORE_ADDR fn_pc = get_pc_function_start (pc);
1074 block = block_for_pc (fn_pc);
1075 if (block == NULL)
1076 {
1077 warning (_("Can't collect args; no symbol table info available."));
1078 return;
1079 }
1080
1081 iterate_over_block_arg_vars (block, do_collect_symbol);
1082 if (count == 0)
1083 warning (_("No args found in scope."));
1084 }
1085 }
1086
1087 void
1088 collection_list::add_static_trace_data ()
1089 {
1090 if (info_verbose)
1091 gdb_printf ("collect static trace data\n");
1092 m_strace_data = true;
1093 }
1094
1095 collection_list::collection_list ()
1096 : m_strace_data (false)
1097 {
1098 int max_remote_regno = 0;
1099 for (int i = 0; i < gdbarch_num_regs (current_inferior ()->arch ()); i++)
1100 {
1101 int remote_regno = (gdbarch_remote_register_number
1102 (current_inferior ()->arch (), i));
1103
1104 if (remote_regno >= 0 && remote_regno > max_remote_regno)
1105 max_remote_regno = remote_regno;
1106 }
1107
1108 m_regs_mask.resize ((max_remote_regno / 8) + 1);
1109
1110 m_memranges.reserve (128);
1111 m_aexprs.reserve (128);
1112 }
1113
1114 /* Reduce a collection list to string form (for gdb protocol). */
1115
1116 std::vector<std::string>
1117 collection_list::stringify ()
1118 {
1119 gdb::char_vector temp_buf (2048);
1120
1121 int count;
1122 char *end;
1123 long i;
1124 std::vector<std::string> str_list;
1125
1126 if (m_strace_data)
1127 {
1128 if (info_verbose)
1129 gdb_printf ("\nCollecting static trace data\n");
1130 end = temp_buf.data ();
1131 *end++ = 'L';
1132 str_list.emplace_back (temp_buf.data (), end - temp_buf.data ());
1133 }
1134
1135 for (i = m_regs_mask.size () - 1; i > 0; i--)
1136 if (m_regs_mask[i] != 0) /* Skip leading zeroes in regs_mask. */
1137 break;
1138 if (m_regs_mask[i] != 0) /* Prepare to send regs_mask to the stub. */
1139 {
1140 if (info_verbose)
1141 gdb_printf ("\nCollecting registers (mask): 0x");
1142
1143 /* One char for 'R', one for the null terminator and two per
1144 mask byte. */
1145 std::size_t new_size = (i + 1) * 2 + 2;
1146 if (new_size > temp_buf.size ())
1147 temp_buf.resize (new_size);
1148
1149 end = temp_buf.data ();
1150 *end++ = 'R';
1151 for (; i >= 0; i--)
1152 {
1153 QUIT; /* Allow user to bail out with ^C. */
1154 if (info_verbose)
1155 gdb_printf ("%02X", m_regs_mask[i]);
1156
1157 end = pack_hex_byte (end, m_regs_mask[i]);
1158 }
1159 *end = '\0';
1160
1161 str_list.emplace_back (temp_buf.data ());
1162 }
1163 if (info_verbose)
1164 gdb_printf ("\n");
1165 if (!m_memranges.empty () && info_verbose)
1166 gdb_printf ("Collecting memranges: \n");
1167 for (i = 0, count = 0, end = temp_buf.data ();
1168 i < m_memranges.size (); i++)
1169 {
1170 QUIT; /* Allow user to bail out with ^C. */
1171 if (info_verbose)
1172 {
1173 gdb_printf ("(%d, %s, %ld)\n",
1174 m_memranges[i].type,
1175 paddress (current_inferior ()->arch (),
1176 m_memranges[i].start),
1177 (long) (m_memranges[i].end
1178 - m_memranges[i].start));
1179 }
1180 if (count + 27 > MAX_AGENT_EXPR_LEN)
1181 {
1182 str_list.emplace_back (temp_buf.data (), count);
1183 count = 0;
1184 end = temp_buf.data ();
1185 }
1186
1187 {
1188 bfd_signed_vma length
1189 = m_memranges[i].end - m_memranges[i].start;
1190
1191 /* The "%X" conversion specifier expects an unsigned argument,
1192 so passing -1 (memrange_absolute) to it directly gives you
1193 "FFFFFFFF" (or more, depending on sizeof (unsigned)).
1194 Special-case it. */
1195 if (m_memranges[i].type == memrange_absolute)
1196 sprintf (end, "M-1,%s,%lX", phex_nz (m_memranges[i].start, 0),
1197 (long) length);
1198 else
1199 sprintf (end, "M%X,%s,%lX", m_memranges[i].type,
1200 phex_nz (m_memranges[i].start, 0), (long) length);
1201 }
1202
1203 count += strlen (end);
1204 end = temp_buf.data () + count;
1205 }
1206
1207 for (i = 0; i < m_aexprs.size (); i++)
1208 {
1209 QUIT; /* Allow user to bail out with ^C. */
1210 if ((count + 10 + 2 * m_aexprs[i]->buf.size ()) > MAX_AGENT_EXPR_LEN)
1211 {
1212 str_list.emplace_back (temp_buf.data (), count);
1213 count = 0;
1214 end = temp_buf.data ();
1215 }
1216 sprintf (end, "X%08X,", (int) m_aexprs[i]->buf.size ());
1217 end += 10; /* 'X' + 8 hex digits + ',' */
1218 count += 10;
1219
1220 end += 2 * bin2hex (m_aexprs[i]->buf.data (), end,
1221 m_aexprs[i]->buf.size ());
1222 count += 2 * m_aexprs[i]->buf.size ();
1223 }
1224
1225 if (count != 0)
1226 {
1227 str_list.emplace_back (temp_buf.data (), count);
1228 count = 0;
1229 end = temp_buf.data ();
1230 }
1231
1232 return str_list;
1233 }
1234
1235 /* Add the expression STR to M_COMPUTED. */
1236
1237 void
1238 collection_list::append_exp (std::string &&str)
1239 {
1240 m_computed.push_back (std::move (str));
1241 }
1242
1243 void
1244 collection_list::finish ()
1245 {
1246 memrange_sortmerge (m_memranges);
1247 }
1248
1249 static void
1250 encode_actions_1 (struct command_line *action,
1251 struct bp_location *tloc,
1252 int frame_reg,
1253 LONGEST frame_offset,
1254 struct collection_list *collect,
1255 struct collection_list *stepping_list)
1256 {
1257 const char *action_exp;
1258 int i;
1259 struct value *tempval;
1260 struct cmd_list_element *cmd;
1261
1262 for (; action; action = action->next)
1263 {
1264 QUIT; /* Allow user to bail out with ^C. */
1265 action_exp = action->line;
1266 action_exp = skip_spaces (action_exp);
1267
1268 cmd = lookup_cmd (&action_exp, cmdlist, "", NULL, -1, 1);
1269 if (cmd == 0)
1270 error (_("Bad action list item: %s"), action_exp);
1271
1272 if (cmd_simple_func_eq (cmd, collect_pseudocommand))
1273 {
1274 int trace_string = 0;
1275
1276 if (*action_exp == '/')
1277 action_exp = decode_agent_options (action_exp, &trace_string);
1278
1279 do
1280 { /* Repeat over a comma-separated list. */
1281 QUIT; /* Allow user to bail out with ^C. */
1282 action_exp = skip_spaces (action_exp);
1283 gdbarch *arch = current_inferior ()->arch ();
1284
1285 if (0 == strncasecmp ("$reg", action_exp, 4))
1286 {
1287 for (i = 0; i < gdbarch_num_regs (arch);
1288 i++)
1289 {
1290 int remote_regno = (gdbarch_remote_register_number
1291 (arch, i));
1292
1293 /* Ignore arch regnos without a corresponding
1294 remote regno. This can happen for regnos not
1295 in the tdesc. */
1296 if (remote_regno >= 0)
1297 collect->add_remote_register (remote_regno);
1298 }
1299 action_exp = strchr (action_exp, ','); /* more? */
1300 }
1301 else if (0 == strncasecmp ("$arg", action_exp, 4))
1302 {
1303 collect->add_local_symbols (arch,
1304 tloc->address,
1305 frame_reg,
1306 frame_offset,
1307 'A',
1308 trace_string);
1309 action_exp = strchr (action_exp, ','); /* more? */
1310 }
1311 else if (0 == strncasecmp ("$loc", action_exp, 4))
1312 {
1313 collect->add_local_symbols (arch,
1314 tloc->address,
1315 frame_reg,
1316 frame_offset,
1317 'L',
1318 trace_string);
1319 action_exp = strchr (action_exp, ','); /* more? */
1320 }
1321 else if (0 == strncasecmp ("$_ret", action_exp, 5))
1322 {
1323 agent_expr_up aexpr
1324 = gen_trace_for_return_address (tloc->address,
1325 arch, trace_string);
1326
1327 finalize_tracepoint_aexpr (aexpr.get ());
1328
1329 /* take care of the registers */
1330 collect->add_ax_registers (aexpr.get ());
1331
1332 collect->add_aexpr (std::move (aexpr));
1333 action_exp = strchr (action_exp, ','); /* more? */
1334 }
1335 else if (0 == strncasecmp ("$_sdata", action_exp, 7))
1336 {
1337 collect->add_static_trace_data ();
1338 action_exp = strchr (action_exp, ','); /* more? */
1339 }
1340 else
1341 {
1342 unsigned long addr;
1343
1344 const char *exp_start = action_exp;
1345 expression_up exp = parse_exp_1 (&action_exp, tloc->address,
1346 block_for_pc (tloc->address),
1347 PARSER_COMMA_TERMINATES);
1348
1349 switch (exp->first_opcode ())
1350 {
1351 case OP_REGISTER:
1352 {
1353 expr::register_operation *regop
1354 = (gdb::checked_static_cast<expr::register_operation *>
1355 (exp->op.get ()));
1356 const char *name = regop->get_name ();
1357
1358 i = user_reg_map_name_to_regnum (arch,
1359 name, strlen (name));
1360 if (i == -1)
1361 internal_error (_("Register $%s not available"),
1362 name);
1363 if (info_verbose)
1364 gdb_printf ("OP_REGISTER: ");
1365 collect->add_local_register (arch, i, tloc->address);
1366 break;
1367 }
1368
1369 case UNOP_MEMVAL:
1370 {
1371 /* Safe because we know it's a simple expression. */
1372 tempval = exp->evaluate ();
1373 addr = tempval->address ();
1374 expr::unop_memval_operation *memop
1375 = (gdb::checked_static_cast<expr::unop_memval_operation *>
1376 (exp->op.get ()));
1377 struct type *type = memop->get_type ();
1378 /* Initialize the TYPE_LENGTH if it is a typedef. */
1379 check_typedef (type);
1380 collect->add_memrange (arch,
1381 memrange_absolute, addr,
1382 type->length (),
1383 tloc->address);
1384 collect->append_exp (std::string (exp_start,
1385 action_exp));
1386 }
1387 break;
1388
1389 case OP_VAR_VALUE:
1390 {
1391 expr::var_value_operation *vvo
1392 = (gdb::checked_static_cast<expr::var_value_operation *>
1393 (exp->op.get ()));
1394 struct symbol *sym = vvo->get_symbol ();
1395 const char *name = sym->natural_name ();
1396
1397 collect->collect_symbol (sym,
1398 arch,
1399 frame_reg,
1400 frame_offset,
1401 tloc->address,
1402 trace_string);
1403 collect->add_wholly_collected (name);
1404 }
1405 break;
1406
1407 default: /* Full-fledged expression. */
1408 agent_expr_up aexpr = gen_trace_for_expr (tloc->address,
1409 exp.get (),
1410 trace_string);
1411
1412 finalize_tracepoint_aexpr (aexpr.get ());
1413
1414 /* Take care of the registers. */
1415 collect->add_ax_registers (aexpr.get ());
1416
1417 collect->add_aexpr (std::move (aexpr));
1418 collect->append_exp (std::string (exp_start,
1419 action_exp));
1420 break;
1421 } /* switch */
1422 } /* do */
1423 }
1424 while (action_exp && *action_exp++ == ',');
1425 } /* if */
1426 else if (cmd_simple_func_eq (cmd, teval_pseudocommand))
1427 {
1428 do
1429 { /* Repeat over a comma-separated list. */
1430 QUIT; /* Allow user to bail out with ^C. */
1431 action_exp = skip_spaces (action_exp);
1432
1433 {
1434 expression_up exp = parse_exp_1 (&action_exp, tloc->address,
1435 block_for_pc (tloc->address),
1436 PARSER_COMMA_TERMINATES);
1437
1438 agent_expr_up aexpr = gen_eval_for_expr (tloc->address,
1439 exp.get ());
1440
1441 finalize_tracepoint_aexpr (aexpr.get ());
1442
1443 /* Even though we're not officially collecting, add
1444 to the collect list anyway. */
1445 collect->add_aexpr (std::move (aexpr));
1446 } /* do */
1447 }
1448 while (action_exp && *action_exp++ == ',');
1449 } /* if */
1450 else if (cmd_simple_func_eq (cmd, while_stepping_pseudocommand))
1451 {
1452 /* We check against nested while-stepping when setting
1453 breakpoint action, so no way to run into nested
1454 here. */
1455 gdb_assert (stepping_list);
1456
1457 encode_actions_1 (action->body_list_0.get (), tloc, frame_reg,
1458 frame_offset, stepping_list, NULL);
1459 }
1460 else
1461 error (_("Invalid tracepoint command '%s'"), action->line);
1462 } /* for */
1463 }
1464
1465 /* Encode actions of tracepoint TLOC->owner and fill TRACEPOINT_LIST
1466 and STEPPING_LIST. */
1467
1468 void
1469 encode_actions (struct bp_location *tloc,
1470 struct collection_list *tracepoint_list,
1471 struct collection_list *stepping_list)
1472 {
1473 int frame_reg;
1474 LONGEST frame_offset;
1475
1476 gdbarch_virtual_frame_pointer (tloc->gdbarch,
1477 tloc->address, &frame_reg, &frame_offset);
1478
1479 tracepoint *t = gdb::checked_static_cast<tracepoint *> (tloc->owner);
1480 counted_command_line actions = all_tracepoint_actions (t);
1481 encode_actions_1 (actions.get (), tloc, frame_reg, frame_offset,
1482 tracepoint_list, stepping_list);
1483 encode_actions_1 (breakpoint_commands (tloc->owner), tloc,
1484 frame_reg, frame_offset, tracepoint_list, stepping_list);
1485
1486 tracepoint_list->finish ();
1487 stepping_list->finish ();
1488 }
1489
1490 /* Render all actions into gdb protocol. */
1491
1492 void
1493 encode_actions_rsp (struct bp_location *tloc,
1494 std::vector<std::string> *tdp_actions,
1495 std::vector<std::string> *stepping_actions)
1496 {
1497 struct collection_list tracepoint_list, stepping_list;
1498
1499 encode_actions (tloc, &tracepoint_list, &stepping_list);
1500
1501 *tdp_actions = tracepoint_list.stringify ();
1502 *stepping_actions = stepping_list.stringify ();
1503 }
1504
1505 void
1506 collection_list::add_aexpr (agent_expr_up aexpr)
1507 {
1508 m_aexprs.push_back (std::move (aexpr));
1509 }
1510
1511 static void
1512 process_tracepoint_on_disconnect (void)
1513 {
1514 int has_pending_p = 0;
1515
1516 /* Check whether we still have pending tracepoint. If we have, warn the
1517 user that pending tracepoint will no longer work. */
1518 for (breakpoint &b : all_tracepoints ())
1519 {
1520 if (!b.has_locations ())
1521 {
1522 has_pending_p = 1;
1523 break;
1524 }
1525 else
1526 {
1527 for (bp_location &loc1 : b.locations ())
1528 {
1529 if (loc1.shlib_disabled)
1530 {
1531 has_pending_p = 1;
1532 break;
1533 }
1534 }
1535
1536 if (has_pending_p)
1537 break;
1538 }
1539 }
1540
1541 if (has_pending_p)
1542 warning (_("Pending tracepoints will not be resolved while"
1543 " GDB is disconnected\n"));
1544 }
1545
1546 /* Reset local state of tracing. */
1547
1548 void
1549 trace_reset_local_state (void)
1550 {
1551 set_traceframe_num (-1);
1552 set_tracepoint_num (-1);
1553 set_traceframe_context (NULL);
1554 clear_traceframe_info ();
1555 }
1556
1557 void
1558 start_tracing (const char *notes)
1559 {
1560 int any_enabled = 0, num_to_download = 0;
1561 int ret;
1562
1563 auto tracepoint_range = all_tracepoints ();
1564
1565 /* No point in tracing without any tracepoints... */
1566 if (tracepoint_range.begin () == tracepoint_range.end ())
1567 error (_("No tracepoints defined, not starting trace"));
1568
1569 for (breakpoint &b : tracepoint_range)
1570 {
1571 if (b.enable_state == bp_enabled)
1572 any_enabled = 1;
1573
1574 if ((b.type == bp_fast_tracepoint
1575 ? may_insert_fast_tracepoints
1576 : may_insert_tracepoints))
1577 ++num_to_download;
1578 else
1579 warning (_("May not insert %stracepoints, skipping tracepoint %d"),
1580 (b.type == bp_fast_tracepoint ? "fast " : ""), b.number);
1581 }
1582
1583 if (!any_enabled)
1584 {
1585 if (target_supports_enable_disable_tracepoint ())
1586 warning (_("No tracepoints enabled"));
1587 else
1588 {
1589 /* No point in tracing with only disabled tracepoints that
1590 cannot be re-enabled. */
1591 error (_("No tracepoints enabled, not starting trace"));
1592 }
1593 }
1594
1595 if (num_to_download <= 0)
1596 error (_("No tracepoints that may be downloaded, not starting trace"));
1597
1598 target_trace_init ();
1599
1600 for (breakpoint &b : tracepoint_range)
1601 {
1602 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
1603 int bp_location_downloaded = 0;
1604
1605 /* Clear `inserted' flag. */
1606 for (bp_location &loc : b.locations ())
1607 loc.inserted = 0;
1608
1609 if ((b.type == bp_fast_tracepoint
1610 ? !may_insert_fast_tracepoints
1611 : !may_insert_tracepoints))
1612 continue;
1613
1614 t.number_on_target = 0;
1615
1616 for (bp_location &loc : b.locations ())
1617 {
1618 /* Since tracepoint locations are never duplicated, `inserted'
1619 flag should be zero. */
1620 gdb_assert (!loc.inserted);
1621
1622 target_download_tracepoint (&loc);
1623
1624 loc.inserted = 1;
1625 bp_location_downloaded = 1;
1626 }
1627
1628 t.number_on_target = b.number;
1629
1630 for (bp_location &loc : b.locations ())
1631 if (loc.probe.prob != NULL)
1632 loc.probe.prob->set_semaphore (loc.probe.objfile, loc.gdbarch);
1633
1634 if (bp_location_downloaded)
1635 notify_breakpoint_modified (&b);
1636 }
1637
1638 /* Send down all the trace state variables too. */
1639 for (const trace_state_variable &tsv : tvariables)
1640 target_download_trace_state_variable (tsv);
1641
1642 /* Tell target to treat text-like sections as transparent. */
1643 target_trace_set_readonly_regions ();
1644 /* Set some mode flags. */
1645 target_set_disconnected_tracing (disconnected_tracing);
1646 target_set_circular_trace_buffer (circular_trace_buffer);
1647 target_set_trace_buffer_size (trace_buffer_size);
1648
1649 if (!notes)
1650 notes = trace_notes.c_str ();
1651
1652 ret = target_set_trace_notes (trace_user.c_str (), notes, NULL);
1653
1654 if (!ret && (!trace_user.empty () || notes))
1655 warning (_("Target does not support trace user/notes, info ignored"));
1656
1657 /* Now insert traps and begin collecting data. */
1658 target_trace_start ();
1659
1660 /* Reset our local state. */
1661 trace_reset_local_state ();
1662 current_trace_status()->running = 1;
1663 }
1664
1665 /* The tstart command requests the target to start a new trace run.
1666 The command passes any arguments it has to the target verbatim, as
1667 an optional "trace note". This is useful as for instance a warning
1668 to other users if the trace runs disconnected, and you don't want
1669 anybody else messing with the target. */
1670
1671 static void
1672 tstart_command (const char *args, int from_tty)
1673 {
1674 dont_repeat (); /* Like "run", dangerous to repeat accidentally. */
1675
1676 if (current_trace_status ()->running)
1677 {
1678 if (from_tty
1679 && !query (_("A trace is running already. Start a new run? ")))
1680 error (_("New trace run not started."));
1681 }
1682
1683 start_tracing (args);
1684 }
1685
1686 /* The tstop command stops the tracing run. The command passes any
1687 supplied arguments to the target verbatim as a "stop note"; if the
1688 target supports trace notes, then it will be reported back as part
1689 of the trace run's status. */
1690
1691 static void
1692 tstop_command (const char *args, int from_tty)
1693 {
1694 if (!current_trace_status ()->running)
1695 error (_("Trace is not running."));
1696
1697 stop_tracing (args);
1698 }
1699
1700 void
1701 stop_tracing (const char *note)
1702 {
1703 int ret;
1704
1705 target_trace_stop ();
1706
1707 for (breakpoint &t : all_tracepoints ())
1708 {
1709 if ((t.type == bp_fast_tracepoint
1710 ? !may_insert_fast_tracepoints
1711 : !may_insert_tracepoints))
1712 continue;
1713
1714 for (bp_location &loc : t.locations ())
1715 {
1716 /* GDB can be totally absent in some disconnected trace scenarios,
1717 but we don't really care if this semaphore goes out of sync.
1718 That's why we are decrementing it here, but not taking care
1719 in other places. */
1720 if (loc.probe.prob != NULL)
1721 loc.probe.prob->clear_semaphore (loc.probe.objfile, loc.gdbarch);
1722 }
1723 }
1724
1725 if (!note)
1726 note = trace_stop_notes.c_str ();
1727
1728 ret = target_set_trace_notes (NULL, NULL, note);
1729
1730 if (!ret && note)
1731 warning (_("Target does not support trace notes, note ignored"));
1732
1733 /* Should change in response to reply? */
1734 current_trace_status ()->running = 0;
1735 }
1736
1737 /* tstatus command */
1738 static void
1739 tstatus_command (const char *args, int from_tty)
1740 {
1741 struct trace_status *ts = current_trace_status ();
1742 int status;
1743
1744 status = target_get_trace_status (ts);
1745
1746 if (status == -1)
1747 {
1748 if (ts->filename != NULL)
1749 gdb_printf (_("Using a trace file.\n"));
1750 else
1751 {
1752 gdb_printf (_("Trace can not be run on this target.\n"));
1753 return;
1754 }
1755 }
1756
1757 if (!ts->running_known)
1758 {
1759 gdb_printf (_("Run/stop status is unknown.\n"));
1760 }
1761 else if (ts->running)
1762 {
1763 gdb_printf (_("Trace is running on the target.\n"));
1764 }
1765 else
1766 {
1767 switch (ts->stop_reason)
1768 {
1769 case trace_never_run:
1770 gdb_printf (_("No trace has been run on the target.\n"));
1771 break;
1772 case trace_stop_command:
1773 if (ts->stop_desc)
1774 gdb_printf (_("Trace stopped by a tstop command (%s).\n"),
1775 ts->stop_desc);
1776 else
1777 gdb_printf (_("Trace stopped by a tstop command.\n"));
1778 break;
1779 case trace_buffer_full:
1780 gdb_printf (_("Trace stopped because the buffer was full.\n"));
1781 break;
1782 case trace_disconnected:
1783 gdb_printf (_("Trace stopped because of disconnection.\n"));
1784 break;
1785 case tracepoint_passcount:
1786 gdb_printf (_("Trace stopped by tracepoint %d.\n"),
1787 ts->stopping_tracepoint);
1788 break;
1789 case tracepoint_error:
1790 if (ts->stopping_tracepoint)
1791 gdb_printf (_("Trace stopped by an "
1792 "error (%s, tracepoint %d).\n"),
1793 ts->stop_desc, ts->stopping_tracepoint);
1794 else
1795 gdb_printf (_("Trace stopped by an error (%s).\n"),
1796 ts->stop_desc);
1797 break;
1798 case trace_stop_reason_unknown:
1799 gdb_printf (_("Trace stopped for an unknown reason.\n"));
1800 break;
1801 default:
1802 gdb_printf (_("Trace stopped for some other reason (%d).\n"),
1803 ts->stop_reason);
1804 break;
1805 }
1806 }
1807
1808 if (ts->traceframes_created >= 0
1809 && ts->traceframe_count != ts->traceframes_created)
1810 {
1811 gdb_printf (_("Buffer contains %d trace "
1812 "frames (of %d created total).\n"),
1813 ts->traceframe_count, ts->traceframes_created);
1814 }
1815 else if (ts->traceframe_count >= 0)
1816 {
1817 gdb_printf (_("Collected %d trace frames.\n"),
1818 ts->traceframe_count);
1819 }
1820
1821 if (ts->buffer_free >= 0)
1822 {
1823 if (ts->buffer_size >= 0)
1824 {
1825 gdb_printf (_("Trace buffer has %d bytes of %d bytes free"),
1826 ts->buffer_free, ts->buffer_size);
1827 if (ts->buffer_size > 0)
1828 gdb_printf (_(" (%d%% full)"),
1829 ((int) ((((long long) (ts->buffer_size
1830 - ts->buffer_free)) * 100)
1831 / ts->buffer_size)));
1832 gdb_printf (_(".\n"));
1833 }
1834 else
1835 gdb_printf (_("Trace buffer has %d bytes free.\n"),
1836 ts->buffer_free);
1837 }
1838
1839 if (ts->disconnected_tracing)
1840 gdb_printf (_("Trace will continue if GDB disconnects.\n"));
1841 else
1842 gdb_printf (_("Trace will stop if GDB disconnects.\n"));
1843
1844 if (ts->circular_buffer)
1845 gdb_printf (_("Trace buffer is circular.\n"));
1846
1847 if (ts->user_name && strlen (ts->user_name) > 0)
1848 gdb_printf (_("Trace user is %s.\n"), ts->user_name);
1849
1850 if (ts->notes && strlen (ts->notes) > 0)
1851 gdb_printf (_("Trace notes: %s.\n"), ts->notes);
1852
1853 /* Now report on what we're doing with tfind. */
1854 if (traceframe_number >= 0)
1855 gdb_printf (_("Looking at trace frame %d, tracepoint %d.\n"),
1856 traceframe_number, tracepoint_number);
1857 else
1858 gdb_printf (_("Not looking at any trace frame.\n"));
1859
1860 /* Report start/stop times if supplied. */
1861 if (ts->start_time)
1862 {
1863 if (ts->stop_time)
1864 {
1865 LONGEST run_time = ts->stop_time - ts->start_time;
1866
1867 /* Reporting a run time is more readable than two long numbers. */
1868 gdb_printf (_("Trace started at %ld.%06ld secs, stopped %ld.%06ld secs later.\n"),
1869 (long int) (ts->start_time / 1000000),
1870 (long int) (ts->start_time % 1000000),
1871 (long int) (run_time / 1000000),
1872 (long int) (run_time % 1000000));
1873 }
1874 else
1875 gdb_printf (_("Trace started at %ld.%06ld secs.\n"),
1876 (long int) (ts->start_time / 1000000),
1877 (long int) (ts->start_time % 1000000));
1878 }
1879 else if (ts->stop_time)
1880 gdb_printf (_("Trace stopped at %ld.%06ld secs.\n"),
1881 (long int) (ts->stop_time / 1000000),
1882 (long int) (ts->stop_time % 1000000));
1883
1884 /* Now report any per-tracepoint status available. */
1885 for (breakpoint &b : all_tracepoints ())
1886 {
1887 tracepoint *t = gdb::checked_static_cast<tracepoint *> (&b);
1888 target_get_tracepoint_status (t, nullptr);
1889 }
1890 }
1891
1892 /* Report the trace status to uiout, in a way suitable for MI, and not
1893 suitable for CLI. If ON_STOP is true, suppress a few fields that
1894 are not meaningful in the -trace-stop response.
1895
1896 The implementation is essentially parallel to trace_status_command, but
1897 merging them will result in unreadable code. */
1898 void
1899 trace_status_mi (int on_stop)
1900 {
1901 struct ui_out *uiout = current_uiout;
1902 struct trace_status *ts = current_trace_status ();
1903 int status;
1904
1905 status = target_get_trace_status (ts);
1906
1907 if (status == -1 && ts->filename == NULL)
1908 {
1909 uiout->field_string ("supported", "0");
1910 return;
1911 }
1912
1913 if (ts->filename != NULL)
1914 uiout->field_string ("supported", "file");
1915 else if (!on_stop)
1916 uiout->field_string ("supported", "1");
1917
1918 if (ts->filename != NULL)
1919 uiout->field_string ("trace-file", ts->filename);
1920
1921 gdb_assert (ts->running_known);
1922
1923 if (ts->running)
1924 {
1925 uiout->field_string ("running", "1");
1926
1927 /* Unlike CLI, do not show the state of 'disconnected-tracing' variable.
1928 Given that the frontend gets the status either on -trace-stop, or from
1929 -trace-status after re-connection, it does not seem like this
1930 information is necessary for anything. It is not necessary for either
1931 figuring the vital state of the target nor for navigation of trace
1932 frames. If the frontend wants to show the current state is some
1933 configure dialog, it can request the value when such dialog is
1934 invoked by the user. */
1935 }
1936 else
1937 {
1938 const char *stop_reason = NULL;
1939 int stopping_tracepoint = -1;
1940
1941 if (!on_stop)
1942 uiout->field_string ("running", "0");
1943
1944 if (ts->stop_reason != trace_stop_reason_unknown)
1945 {
1946 switch (ts->stop_reason)
1947 {
1948 case trace_stop_command:
1949 stop_reason = "request";
1950 break;
1951 case trace_buffer_full:
1952 stop_reason = "overflow";
1953 break;
1954 case trace_disconnected:
1955 stop_reason = "disconnection";
1956 break;
1957 case tracepoint_passcount:
1958 stop_reason = "passcount";
1959 stopping_tracepoint = ts->stopping_tracepoint;
1960 break;
1961 case tracepoint_error:
1962 stop_reason = "error";
1963 stopping_tracepoint = ts->stopping_tracepoint;
1964 break;
1965 }
1966
1967 if (stop_reason)
1968 {
1969 uiout->field_string ("stop-reason", stop_reason);
1970 if (stopping_tracepoint != -1)
1971 uiout->field_signed ("stopping-tracepoint",
1972 stopping_tracepoint);
1973 if (ts->stop_reason == tracepoint_error)
1974 uiout->field_string ("error-description",
1975 ts->stop_desc);
1976 }
1977 }
1978 }
1979
1980 if (ts->traceframe_count != -1)
1981 uiout->field_signed ("frames", ts->traceframe_count);
1982 if (ts->traceframes_created != -1)
1983 uiout->field_signed ("frames-created", ts->traceframes_created);
1984 if (ts->buffer_size != -1)
1985 uiout->field_signed ("buffer-size", ts->buffer_size);
1986 if (ts->buffer_free != -1)
1987 uiout->field_signed ("buffer-free", ts->buffer_free);
1988
1989 uiout->field_signed ("disconnected", ts->disconnected_tracing);
1990 uiout->field_signed ("circular", ts->circular_buffer);
1991
1992 uiout->field_string ("user-name", ts->user_name);
1993 uiout->field_string ("notes", ts->notes);
1994
1995 {
1996 char buf[100];
1997
1998 xsnprintf (buf, sizeof buf, "%ld.%06ld",
1999 (long int) (ts->start_time / 1000000),
2000 (long int) (ts->start_time % 1000000));
2001 uiout->field_string ("start-time", buf);
2002 xsnprintf (buf, sizeof buf, "%ld.%06ld",
2003 (long int) (ts->stop_time / 1000000),
2004 (long int) (ts->stop_time % 1000000));
2005 uiout->field_string ("stop-time", buf);
2006 }
2007 }
2008
2009 /* Check if a trace run is ongoing. If so, and FROM_TTY, query the
2010 user if she really wants to detach. */
2011
2012 void
2013 query_if_trace_running (int from_tty)
2014 {
2015 if (!from_tty)
2016 return;
2017
2018 /* It can happen that the target that was tracing went away on its
2019 own, and we didn't notice. Get a status update, and if the
2020 current target doesn't even do tracing, then assume it's not
2021 running anymore. */
2022 if (target_get_trace_status (current_trace_status ()) < 0)
2023 current_trace_status ()->running = 0;
2024
2025 /* If running interactively, give the user the option to cancel and
2026 then decide what to do differently with the run. Scripts are
2027 just going to disconnect and let the target deal with it,
2028 according to how it's been instructed previously via
2029 disconnected-tracing. */
2030 if (current_trace_status ()->running)
2031 {
2032 process_tracepoint_on_disconnect ();
2033
2034 if (current_trace_status ()->disconnected_tracing)
2035 {
2036 if (!query (_("Trace is running and will "
2037 "continue after detach; detach anyway? ")))
2038 error (_("Not confirmed."));
2039 }
2040 else
2041 {
2042 if (!query (_("Trace is running but will "
2043 "stop on detach; detach anyway? ")))
2044 error (_("Not confirmed."));
2045 }
2046 }
2047 }
2048
2049 /* This function handles the details of what to do about an ongoing
2050 tracing run if the user has asked to detach or otherwise disconnect
2051 from the target. */
2052
2053 void
2054 disconnect_tracing (void)
2055 {
2056 /* Also we want to be out of tfind mode, otherwise things can get
2057 confusing upon reconnection. Just use these calls instead of
2058 full tfind_1 behavior because we're in the middle of detaching,
2059 and there's no point to updating current stack frame etc. */
2060 trace_reset_local_state ();
2061 }
2062
2063 /* Worker function for the various flavors of the tfind command. */
2064 void
2065 tfind_1 (enum trace_find_type type, int num,
2066 CORE_ADDR addr1, CORE_ADDR addr2,
2067 int from_tty)
2068 {
2069 int target_frameno = -1, target_tracept = -1;
2070 struct frame_id old_frame_id = null_frame_id;
2071 struct tracepoint *tp;
2072 struct ui_out *uiout = current_uiout;
2073
2074 /* Only try to get the current stack frame if we have a chance of
2075 succeeding. In particular, if we're trying to get a first trace
2076 frame while all threads are running, it's not going to succeed,
2077 so leave it with a default value and let the frame comparison
2078 below (correctly) decide to print out the source location of the
2079 trace frame. */
2080 if (!(type == tfind_number && num == -1)
2081 && (has_stack_frames () || traceframe_number >= 0))
2082 old_frame_id = get_frame_id (get_current_frame ());
2083
2084 target_frameno = target_trace_find (type, num, addr1, addr2,
2085 &target_tracept);
2086
2087 if (type == tfind_number
2088 && num == -1
2089 && target_frameno == -1)
2090 {
2091 /* We told the target to get out of tfind mode, and it did. */
2092 }
2093 else if (target_frameno == -1)
2094 {
2095 /* A request for a non-existent trace frame has failed.
2096 Our response will be different, depending on FROM_TTY:
2097
2098 If FROM_TTY is true, meaning that this command was
2099 typed interactively by the user, then give an error
2100 and DO NOT change the state of traceframe_number etc.
2101
2102 However if FROM_TTY is false, meaning that we're either
2103 in a script, a loop, or a user-defined command, then
2104 DON'T give an error, but DO change the state of
2105 traceframe_number etc. to invalid.
2106
2107 The rationale is that if you typed the command, you
2108 might just have committed a typo or something, and you'd
2109 like to NOT lose your current debugging state. However
2110 if you're in a user-defined command or especially in a
2111 loop, then you need a way to detect that the command
2112 failed WITHOUT aborting. This allows you to write
2113 scripts that search through the trace buffer until the end,
2114 and then continue on to do something else. */
2115
2116 if (from_tty)
2117 error (_("Target failed to find requested trace frame."));
2118 else
2119 {
2120 if (info_verbose)
2121 gdb_printf ("End of trace buffer.\n");
2122 #if 0 /* dubious now? */
2123 /* The following will not recurse, since it's
2124 special-cased. */
2125 tfind_command ("-1", from_tty);
2126 #endif
2127 }
2128 }
2129
2130 tp = get_tracepoint_by_number_on_target (target_tracept);
2131
2132 reinit_frame_cache ();
2133 target_dcache_invalidate (current_program_space->aspace);
2134
2135 set_tracepoint_num (tp ? tp->number : target_tracept);
2136
2137 if (target_frameno != get_traceframe_number ())
2138 interps_notify_traceframe_changed (target_frameno, tracepoint_number);
2139
2140 set_current_traceframe (target_frameno);
2141
2142 if (target_frameno == -1)
2143 set_traceframe_context (NULL);
2144 else
2145 set_traceframe_context (get_current_frame ());
2146
2147 if (traceframe_number >= 0)
2148 {
2149 /* Use different branches for MI and CLI to make CLI messages
2150 i18n-eable. */
2151 if (uiout->is_mi_like_p ())
2152 {
2153 uiout->field_string ("found", "1");
2154 uiout->field_signed ("tracepoint", tracepoint_number);
2155 uiout->field_signed ("traceframe", traceframe_number);
2156 }
2157 else
2158 {
2159 gdb_printf (_("Found trace frame %d, tracepoint %d\n"),
2160 traceframe_number, tracepoint_number);
2161 }
2162 }
2163 else
2164 {
2165 if (uiout->is_mi_like_p ())
2166 uiout->field_string ("found", "0");
2167 else if (type == tfind_number && num == -1)
2168 gdb_printf (_("No longer looking at any trace frame\n"));
2169 else /* This case may never occur, check. */
2170 gdb_printf (_("No trace frame found\n"));
2171 }
2172
2173 /* If we're in nonstop mode and getting out of looking at trace
2174 frames, there won't be any current frame to go back to and
2175 display. */
2176 if (from_tty
2177 && (has_stack_frames () || traceframe_number >= 0))
2178 {
2179 enum print_what print_what;
2180
2181 /* NOTE: in imitation of the step command, try to determine
2182 whether we have made a transition from one function to
2183 another. If so, we'll print the "stack frame" (ie. the new
2184 function and it's arguments) -- otherwise we'll just show the
2185 new source line. */
2186
2187 if (old_frame_id == get_frame_id (get_current_frame ()))
2188 print_what = SRC_LINE;
2189 else
2190 print_what = SRC_AND_LOC;
2191
2192 print_stack_frame (get_selected_frame (NULL), 1, print_what, 1);
2193 do_displays ();
2194 }
2195 }
2196
2197 /* Error on looking at traceframes while trace is running. */
2198
2199 void
2200 check_trace_running (struct trace_status *status)
2201 {
2202 if (status->running && status->filename == NULL)
2203 error (_("May not look at trace frames while trace is running."));
2204 }
2205
2206 /* trace_find_command takes a trace frame number n,
2207 sends "QTFrame:<n>" to the target,
2208 and accepts a reply that may contain several optional pieces
2209 of information: a frame number, a tracepoint number, and an
2210 indication of whether this is a trap frame or a stepping frame.
2211
2212 The minimal response is just "OK" (which indicates that the
2213 target does not give us a frame number or a tracepoint number).
2214 Instead of that, the target may send us a string containing
2215 any combination of:
2216 F<hexnum> (gives the selected frame number)
2217 T<hexnum> (gives the selected tracepoint number)
2218 */
2219
2220 /* tfind command */
2221 static void
2222 tfind_command_1 (const char *args, int from_tty)
2223 { /* This should only be called with a numeric argument. */
2224 int frameno = -1;
2225
2226 check_trace_running (current_trace_status ());
2227
2228 if (args == 0 || *args == 0)
2229 { /* TFIND with no args means find NEXT trace frame. */
2230 if (traceframe_number == -1)
2231 frameno = 0; /* "next" is first one. */
2232 else
2233 frameno = traceframe_number + 1;
2234 }
2235 else if (0 == strcmp (args, "-"))
2236 {
2237 if (traceframe_number == -1)
2238 error (_("not debugging trace buffer"));
2239 else if (from_tty && traceframe_number == 0)
2240 error (_("already at start of trace buffer"));
2241
2242 frameno = traceframe_number - 1;
2243 }
2244 /* A hack to work around eval's need for fp to have been collected. */
2245 else if (0 == strcmp (args, "-1"))
2246 frameno = -1;
2247 else
2248 frameno = parse_and_eval_long (args);
2249
2250 if (frameno < -1)
2251 error (_("invalid input (%d is less than zero)"), frameno);
2252
2253 tfind_1 (tfind_number, frameno, 0, 0, from_tty);
2254 }
2255
2256 static void
2257 tfind_command (const char *args, int from_tty)
2258 {
2259 tfind_command_1 (args, from_tty);
2260 }
2261
2262 /* tfind end */
2263 static void
2264 tfind_end_command (const char *args, int from_tty)
2265 {
2266 tfind_command_1 ("-1", from_tty);
2267 }
2268
2269 /* tfind start */
2270 static void
2271 tfind_start_command (const char *args, int from_tty)
2272 {
2273 tfind_command_1 ("0", from_tty);
2274 }
2275
2276 /* tfind pc command */
2277 static void
2278 tfind_pc_command (const char *args, int from_tty)
2279 {
2280 CORE_ADDR pc;
2281
2282 check_trace_running (current_trace_status ());
2283
2284 if (args == 0 || *args == 0)
2285 pc = regcache_read_pc (get_thread_regcache (inferior_thread ()));
2286 else
2287 pc = parse_and_eval_address (args);
2288
2289 tfind_1 (tfind_pc, 0, pc, 0, from_tty);
2290 }
2291
2292 /* tfind tracepoint command */
2293 static void
2294 tfind_tracepoint_command (const char *args, int from_tty)
2295 {
2296 int tdp;
2297 struct tracepoint *tp;
2298
2299 check_trace_running (current_trace_status ());
2300
2301 if (args == 0 || *args == 0)
2302 {
2303 if (tracepoint_number == -1)
2304 error (_("No current tracepoint -- please supply an argument."));
2305 else
2306 tdp = tracepoint_number; /* Default is current TDP. */
2307 }
2308 else
2309 tdp = parse_and_eval_long (args);
2310
2311 /* If we have the tracepoint on hand, use the number that the
2312 target knows about (which may be different if we disconnected
2313 and reconnected). */
2314 tp = get_tracepoint (tdp);
2315 if (tp)
2316 tdp = tp->number_on_target;
2317
2318 tfind_1 (tfind_tp, tdp, 0, 0, from_tty);
2319 }
2320
2321 /* TFIND LINE command:
2322
2323 This command will take a sourceline for argument, just like BREAK
2324 or TRACE (ie. anything that "decode_line_1" can handle).
2325
2326 With no argument, this command will find the next trace frame
2327 corresponding to a source line OTHER THAN THE CURRENT ONE. */
2328
2329 static void
2330 tfind_line_command (const char *args, int from_tty)
2331 {
2332 check_trace_running (current_trace_status ());
2333
2334 symtab_and_line sal;
2335 if (args == 0 || *args == 0)
2336 {
2337 sal = find_pc_line (get_frame_pc (get_current_frame ()), 0);
2338 }
2339 else
2340 {
2341 std::vector<symtab_and_line> sals
2342 = decode_line_with_current_source (args, DECODE_LINE_FUNFIRSTLINE);
2343 sal = sals[0];
2344 }
2345
2346 if (sal.symtab == 0)
2347 error (_("No line number information available."));
2348
2349 CORE_ADDR start_pc, end_pc;
2350 if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
2351 {
2352 if (start_pc == end_pc)
2353 {
2354 gdb_printf ("Line %ps of \"%s\"",
2355 styled_string (line_number_style.style (),
2356 pulongest (sal.line)),
2357 symtab_to_filename_for_display (sal.symtab));
2358 gdb_stdout->wrap_here (2);
2359 gdb_printf (" is at address ");
2360 print_address (get_current_arch (), start_pc, gdb_stdout);
2361 gdb_stdout->wrap_here (2);
2362 gdb_printf (" but contains no code.\n");
2363 sal = find_pc_line (start_pc, 0);
2364 if (sal.line > 0
2365 && find_line_pc_range (sal, &start_pc, &end_pc)
2366 && start_pc != end_pc)
2367 gdb_printf ("Attempting to find line %ps instead.\n",
2368 styled_string (line_number_style.style (),
2369 pulongest (sal.line)));
2370 else
2371 error (_("Cannot find a good line."));
2372 }
2373 }
2374 else
2375 {
2376 /* Is there any case in which we get here, and have an address
2377 which the user would want to see? If we have debugging
2378 symbols and no line numbers? */
2379 error (_("Line number %d is out of range for \"%s\"."),
2380 sal.line, symtab_to_filename_for_display (sal.symtab));
2381 }
2382
2383 /* Find within range of stated line. */
2384 if (args && *args)
2385 tfind_1 (tfind_range, 0, start_pc, end_pc - 1, from_tty);
2386 else
2387 tfind_1 (tfind_outside, 0, start_pc, end_pc - 1, from_tty);
2388 }
2389
2390 /* tfind range command */
2391 static void
2392 tfind_range_command (const char *args, int from_tty)
2393 {
2394 static CORE_ADDR start, stop;
2395 const char *tmp;
2396
2397 check_trace_running (current_trace_status ());
2398
2399 if (args == 0 || *args == 0)
2400 { /* XXX FIXME: what should default behavior be? */
2401 gdb_printf ("Usage: tfind range STARTADDR, ENDADDR\n");
2402 return;
2403 }
2404
2405 if (0 != (tmp = strchr (args, ',')))
2406 {
2407 std::string start_addr (args, tmp);
2408 ++tmp;
2409 tmp = skip_spaces (tmp);
2410 start = parse_and_eval_address (start_addr.c_str ());
2411 stop = parse_and_eval_address (tmp);
2412 }
2413 else
2414 { /* No explicit end address? */
2415 start = parse_and_eval_address (args);
2416 stop = start + 1; /* ??? */
2417 }
2418
2419 tfind_1 (tfind_range, 0, start, stop, from_tty);
2420 }
2421
2422 /* tfind outside command */
2423 static void
2424 tfind_outside_command (const char *args, int from_tty)
2425 {
2426 CORE_ADDR start, stop;
2427 const char *tmp;
2428
2429 if (current_trace_status ()->running
2430 && current_trace_status ()->filename == NULL)
2431 error (_("May not look at trace frames while trace is running."));
2432
2433 if (args == 0 || *args == 0)
2434 { /* XXX FIXME: what should default behavior be? */
2435 gdb_printf ("Usage: tfind outside STARTADDR, ENDADDR\n");
2436 return;
2437 }
2438
2439 if (0 != (tmp = strchr (args, ',')))
2440 {
2441 std::string start_addr (args, tmp);
2442 ++tmp;
2443 tmp = skip_spaces (tmp);
2444 start = parse_and_eval_address (start_addr.c_str ());
2445 stop = parse_and_eval_address (tmp);
2446 }
2447 else
2448 { /* No explicit end address? */
2449 start = parse_and_eval_address (args);
2450 stop = start + 1; /* ??? */
2451 }
2452
2453 tfind_1 (tfind_outside, 0, start, stop, from_tty);
2454 }
2455
2456 /* info scope command: list the locals for a scope. */
2457 static void
2458 info_scope_command (const char *args_in, int from_tty)
2459 {
2460 const struct block *block;
2461 const char *symname;
2462 const char *save_args = args_in;
2463 int j, count = 0;
2464 struct gdbarch *gdbarch;
2465 int regno;
2466 const char *args = args_in;
2467
2468 if (args == 0 || *args == 0)
2469 error (_("requires an argument (function, "
2470 "line or *addr) to define a scope"));
2471
2472 location_spec_up locspec = string_to_location_spec (&args,
2473 current_language);
2474 std::vector<symtab_and_line> sals
2475 = decode_line_1 (locspec.get (), DECODE_LINE_FUNFIRSTLINE,
2476 NULL, NULL, 0);
2477 if (sals.empty ())
2478 {
2479 /* Presumably decode_line_1 has already warned. */
2480 return;
2481 }
2482
2483 /* Resolve line numbers to PC. */
2484 resolve_sal_pc (&sals[0]);
2485 block = block_for_pc (sals[0].pc);
2486
2487 while (block != 0)
2488 {
2489 QUIT; /* Allow user to bail out with ^C. */
2490 for (struct symbol *sym : block_iterator_range (block))
2491 {
2492 QUIT; /* Allow user to bail out with ^C. */
2493 if (count == 0)
2494 gdb_printf ("Scope for %s:\n", save_args);
2495 count++;
2496
2497 symname = sym->print_name ();
2498 if (symname == NULL || *symname == '\0')
2499 continue; /* Probably botched, certainly useless. */
2500
2501 gdbarch = sym->arch ();
2502
2503 gdb_printf ("Symbol %s is ", symname);
2504
2505 if (const symbol_computed_ops *computed_ops = sym->computed_ops ();
2506 computed_ops != nullptr)
2507 computed_ops->describe_location (sym, block->entry_pc (),
2508 gdb_stdout);
2509 else
2510 {
2511 switch (sym->aclass ())
2512 {
2513 default:
2514 case LOC_UNDEF: /* Messed up symbol? */
2515 gdb_printf ("a bogus symbol, class %d.\n",
2516 sym->aclass ());
2517 count--; /* Don't count this one. */
2518 continue;
2519 case LOC_CONST:
2520 gdb_printf ("a constant with value %s (%s)",
2521 plongest (sym->value_longest ()),
2522 hex_string (sym->value_longest ()));
2523 break;
2524 case LOC_CONST_BYTES:
2525 gdb_printf ("constant bytes: ");
2526 if (sym->type ())
2527 for (j = 0; j < sym->type ()->length (); j++)
2528 gdb_printf (" %02x", (unsigned) sym->value_bytes ()[j]);
2529 break;
2530 case LOC_STATIC:
2531 gdb_printf ("in static storage at address ");
2532 gdb_printf ("%s", paddress (gdbarch, sym->value_address ()));
2533 break;
2534 case LOC_REGISTER:
2535 /* GDBARCH is the architecture associated with the objfile
2536 the symbol is defined in; the target architecture may be
2537 different, and may provide additional registers. However,
2538 we do not know the target architecture at this point.
2539 We assume the objfile architecture will contain all the
2540 standard registers that occur in debug info in that
2541 objfile. */
2542 regno = sym->register_ops ()->register_number (sym, gdbarch);
2543
2544 if (sym->is_argument ())
2545 gdb_printf ("an argument in register $%s",
2546 gdbarch_register_name (gdbarch, regno));
2547 else
2548 gdb_printf ("a local variable in register $%s",
2549 gdbarch_register_name (gdbarch, regno));
2550 break;
2551 case LOC_ARG:
2552 gdb_printf ("an argument at stack/frame offset %s",
2553 plongest (sym->value_longest ()));
2554 break;
2555 case LOC_LOCAL:
2556 gdb_printf ("a local variable at frame offset %s",
2557 plongest (sym->value_longest ()));
2558 break;
2559 case LOC_REF_ARG:
2560 gdb_printf ("a reference argument at offset %s",
2561 plongest (sym->value_longest ()));
2562 break;
2563 case LOC_REGPARM_ADDR:
2564 /* Note comment at LOC_REGISTER. */
2565 regno = sym->register_ops ()->register_number (sym, gdbarch);
2566 gdb_printf ("the address of an argument, in register $%s",
2567 gdbarch_register_name (gdbarch, regno));
2568 break;
2569 case LOC_TYPEDEF:
2570 gdb_printf ("a typedef.\n");
2571 continue;
2572 case LOC_LABEL:
2573 gdb_printf ("a label at address ");
2574 gdb_printf ("%s", paddress (gdbarch, sym->value_address ()));
2575 break;
2576 case LOC_BLOCK:
2577 gdb_printf ("a function at address ");
2578 gdb_printf ("%s",
2579 paddress (gdbarch,
2580 sym->value_block ()->entry_pc ()));
2581 break;
2582 case LOC_UNRESOLVED:
2583 {
2584 bound_minimal_symbol msym
2585 = lookup_minimal_symbol (current_program_space,
2586 sym->linkage_name ());
2587 if (msym.minsym == NULL)
2588 gdb_printf ("Unresolved Static");
2589 else
2590 {
2591 gdb_printf ("static storage at address ");
2592 gdb_printf ("%s",
2593 paddress (gdbarch, msym.value_address ()));
2594 }
2595 break;
2596 }
2597 case LOC_OPTIMIZED_OUT:
2598 gdb_printf ("optimized out.\n");
2599 continue;
2600 case LOC_COMPUTED:
2601 gdb_assert_not_reached ("LOC_COMPUTED variable missing a method");
2602 }
2603 }
2604 if (sym->type ())
2605 {
2606 struct type *t = check_typedef (sym->type ());
2607
2608 gdb_printf (", length %s.\n", pulongest (t->length ()));
2609 }
2610 }
2611 if (block->function ())
2612 break;
2613 else
2614 block = block->superblock ();
2615 }
2616 if (count <= 0)
2617 gdb_printf ("Scope for %s contains no locals or arguments.\n",
2618 save_args);
2619 }
2620
2621 /* Helper for trace_dump_command. Dump the action list starting at
2622 ACTION. STEPPING_ACTIONS is true if we're iterating over the
2623 actions of the body of a while-stepping action. STEPPING_FRAME is
2624 set if the current traceframe was determined to be a while-stepping
2625 traceframe. */
2626
2627 static void
2628 trace_dump_actions (struct command_line *action,
2629 int stepping_actions, int stepping_frame,
2630 int from_tty)
2631 {
2632 const char *action_exp, *next_comma;
2633
2634 for (; action != NULL; action = action->next)
2635 {
2636 struct cmd_list_element *cmd;
2637
2638 QUIT; /* Allow user to bail out with ^C. */
2639 action_exp = action->line;
2640 action_exp = skip_spaces (action_exp);
2641
2642 /* The collection actions to be done while stepping are
2643 bracketed by the commands "while-stepping" and "end". */
2644
2645 if (*action_exp == '#') /* comment line */
2646 continue;
2647
2648 cmd = lookup_cmd (&action_exp, cmdlist, "", NULL, -1, 1);
2649 if (cmd == 0)
2650 error (_("Bad action list item: %s"), action_exp);
2651
2652 if (cmd_simple_func_eq (cmd, while_stepping_pseudocommand))
2653 {
2654 gdb_assert (action->body_list_1 == nullptr);
2655 trace_dump_actions (action->body_list_0.get (),
2656 1, stepping_frame, from_tty);
2657 }
2658 else if (cmd_simple_func_eq (cmd, collect_pseudocommand))
2659 {
2660 /* Display the collected data.
2661 For the trap frame, display only what was collected at
2662 the trap. Likewise for stepping frames, display only
2663 what was collected while stepping. This means that the
2664 two boolean variables, STEPPING_FRAME and
2665 STEPPING_ACTIONS should be equal. */
2666 if (stepping_frame == stepping_actions)
2667 {
2668 int trace_string = 0;
2669
2670 if (*action_exp == '/')
2671 action_exp = decode_agent_options (action_exp, &trace_string);
2672
2673 do
2674 { /* Repeat over a comma-separated list. */
2675 QUIT; /* Allow user to bail out with ^C. */
2676 if (*action_exp == ',')
2677 action_exp++;
2678 action_exp = skip_spaces (action_exp);
2679
2680 next_comma = strchr (action_exp, ',');
2681
2682 if (0 == strncasecmp (action_exp, "$reg", 4))
2683 registers_info (NULL, from_tty);
2684 else if (0 == strncasecmp (action_exp, "$_ret", 5))
2685 ;
2686 else if (0 == strncasecmp (action_exp, "$loc", 4))
2687 info_locals_command (NULL, from_tty);
2688 else if (0 == strncasecmp (action_exp, "$arg", 4))
2689 info_args_command (NULL, from_tty);
2690 else
2691 { /* variable */
2692 std::string contents;
2693 const char *exp = action_exp;
2694 if (next_comma != NULL)
2695 {
2696 size_t len = next_comma - action_exp;
2697 contents = std::string (action_exp, len);
2698 exp = contents.c_str ();
2699 }
2700
2701 gdb_printf ("%s = ", exp);
2702 output_command (exp, from_tty);
2703 gdb_printf ("\n");
2704 }
2705 action_exp = next_comma;
2706 }
2707 while (action_exp && *action_exp == ',');
2708 }
2709 }
2710 }
2711 }
2712
2713 /* Return bp_location of the tracepoint associated with the current
2714 traceframe. Set *STEPPING_FRAME_P to 1 if the current traceframe
2715 is a stepping traceframe. */
2716
2717 struct bp_location *
2718 get_traceframe_location (int *stepping_frame_p)
2719 {
2720 struct tracepoint *t;
2721 struct regcache *regcache;
2722
2723 if (tracepoint_number == -1)
2724 error (_("No current trace frame."));
2725
2726 t = get_tracepoint (tracepoint_number);
2727
2728 if (t == NULL)
2729 error (_("No known tracepoint matches 'current' tracepoint #%d."),
2730 tracepoint_number);
2731
2732 /* The current frame is a trap frame if the frame PC is equal to the
2733 tracepoint PC. If not, then the current frame was collected
2734 during single-stepping. */
2735 regcache = get_thread_regcache (inferior_thread ());
2736
2737 /* If the traceframe's address matches any of the tracepoint's
2738 locations, assume it is a direct hit rather than a while-stepping
2739 frame. (FIXME this is not reliable, should record each frame's
2740 type.) */
2741 for (bp_location &tloc : t->locations ())
2742 if (tloc.address == regcache_read_pc (regcache))
2743 {
2744 *stepping_frame_p = 0;
2745 return &tloc;
2746 }
2747
2748 /* If this is a stepping frame, we don't know which location
2749 triggered. The first is as good (or bad) a guess as any... */
2750 *stepping_frame_p = 1;
2751 return &t->first_loc ();
2752 }
2753
2754 /* Return the default collect actions of a tracepoint T. */
2755
2756 static counted_command_line
2757 all_tracepoint_actions (tracepoint *t)
2758 {
2759 counted_command_line actions (nullptr, command_lines_deleter ());
2760
2761 /* If there are default expressions to collect, make up a collect
2762 action and prepend to the action list to encode. Note that since
2763 validation is per-tracepoint (local var "xyz" might be valid for
2764 one tracepoint and not another, etc), we make up the action on
2765 the fly, and don't cache it. */
2766 if (!default_collect.empty ())
2767 {
2768 gdb::unique_xmalloc_ptr<char> default_collect_line
2769 = xstrprintf ("collect %s", default_collect.c_str ());
2770
2771 validate_actionline (default_collect_line.get (), t);
2772 actions.reset (new struct command_line (simple_control,
2773 default_collect_line.release ()),
2774 command_lines_deleter ());
2775 }
2776
2777 return actions;
2778 }
2779
2780 /* The tdump command. */
2781
2782 static void
2783 tdump_command (const char *args, int from_tty)
2784 {
2785 int stepping_frame = 0;
2786 struct bp_location *loc;
2787
2788 /* This throws an error is not inspecting a trace frame. */
2789 loc = get_traceframe_location (&stepping_frame);
2790
2791 gdb_printf ("Data collected at tracepoint %d, trace frame %d:\n",
2792 tracepoint_number, traceframe_number);
2793
2794 /* This command only makes sense for the current frame, not the
2795 selected frame. */
2796 scoped_restore_current_thread restore_thread;
2797
2798 select_frame (get_current_frame ());
2799
2800 tracepoint *t = gdb::checked_static_cast<tracepoint *> (loc->owner);
2801 counted_command_line actions = all_tracepoint_actions (t);
2802
2803 trace_dump_actions (actions.get (), 0, stepping_frame, from_tty);
2804 trace_dump_actions (breakpoint_commands (loc->owner), 0, stepping_frame,
2805 from_tty);
2806 }
2807
2808 /* Encode a piece of a tracepoint's source-level definition in a form
2809 that is suitable for both protocol and saving in files. */
2810 /* This version does not do multiple encodes for long strings; it should
2811 return an offset to the next piece to encode. FIXME */
2812
2813 int
2814 encode_source_string (int tpnum, ULONGEST addr,
2815 const char *srctype, const char *src,
2816 char *buf, int buf_size)
2817 {
2818 if (80 + strlen (srctype) > buf_size)
2819 error (_("Buffer too small for source encoding"));
2820 sprintf (buf, "%x:%s:%s:%x:%x:",
2821 tpnum, phex_nz (addr),
2822 srctype, 0, (int) strlen (src));
2823 if (strlen (buf) + strlen (src) * 2 >= buf_size)
2824 error (_("Source string too long for buffer"));
2825 bin2hex ((gdb_byte *) src, buf + strlen (buf), strlen (src));
2826 return -1;
2827 }
2828
2829 /* Tell the target what to do with an ongoing tracing run if GDB
2830 disconnects for some reason. */
2831
2832 static void
2833 set_disconnected_tracing (const char *args, int from_tty,
2834 struct cmd_list_element *c)
2835 {
2836 target_set_disconnected_tracing (disconnected_tracing);
2837 }
2838
2839 static void
2840 set_circular_trace_buffer (const char *args, int from_tty,
2841 struct cmd_list_element *c)
2842 {
2843 target_set_circular_trace_buffer (circular_trace_buffer);
2844 }
2845
2846 static void
2847 set_trace_buffer_size (const char *args, int from_tty,
2848 struct cmd_list_element *c)
2849 {
2850 target_set_trace_buffer_size (trace_buffer_size);
2851 }
2852
2853 static void
2854 set_trace_user (const char *args, int from_tty,
2855 struct cmd_list_element *c)
2856 {
2857 int ret;
2858
2859 ret = target_set_trace_notes (trace_user.c_str (), NULL, NULL);
2860
2861 if (!ret)
2862 warning (_("Target does not support trace notes, user ignored"));
2863 }
2864
2865 static void
2866 set_trace_notes (const char *args, int from_tty,
2867 struct cmd_list_element *c)
2868 {
2869 int ret;
2870
2871 ret = target_set_trace_notes (NULL, trace_notes.c_str (), NULL);
2872
2873 if (!ret)
2874 warning (_("Target does not support trace notes, note ignored"));
2875 }
2876
2877 static void
2878 set_trace_stop_notes (const char *args, int from_tty,
2879 struct cmd_list_element *c)
2880 {
2881 int ret;
2882
2883 ret = target_set_trace_notes (NULL, NULL, trace_stop_notes.c_str ());
2884
2885 if (!ret)
2886 warning (_("Target does not support trace notes, stop note ignored"));
2887 }
2888
2889 int
2890 get_traceframe_number (void)
2891 {
2892 return traceframe_number;
2893 }
2894
2895 int
2896 get_tracepoint_number (void)
2897 {
2898 return tracepoint_number;
2899 }
2900
2901 /* Make the traceframe NUM be the current trace frame. Does nothing
2902 if NUM is already current. */
2903
2904 void
2905 set_current_traceframe (int num)
2906 {
2907 int newnum;
2908
2909 if (traceframe_number == num)
2910 {
2911 /* Nothing to do. */
2912 return;
2913 }
2914
2915 newnum = target_trace_find (tfind_number, num, 0, 0, NULL);
2916
2917 if (newnum != num)
2918 warning (_("could not change traceframe"));
2919
2920 set_traceframe_num (newnum);
2921
2922 /* Changing the traceframe changes our view of registers and of the
2923 frame chain. */
2924 registers_changed ();
2925
2926 clear_traceframe_info ();
2927 }
2928
2929 scoped_restore_current_traceframe::scoped_restore_current_traceframe ()
2930 : m_traceframe_number (traceframe_number)
2931 {}
2932
2933 /* Given a number and address, return an uploaded tracepoint with that
2934 number, creating if necessary. */
2935
2936 struct uploaded_tp *
2937 get_uploaded_tp (int num, ULONGEST addr, struct uploaded_tp **utpp)
2938 {
2939 struct uploaded_tp *utp;
2940
2941 for (utp = *utpp; utp; utp = utp->next)
2942 if (utp->number == num && utp->addr == addr)
2943 return utp;
2944
2945 utp = new uploaded_tp;
2946 utp->number = num;
2947 utp->addr = addr;
2948 utp->next = *utpp;
2949 *utpp = utp;
2950
2951 return utp;
2952 }
2953
2954 void
2955 free_uploaded_tps (struct uploaded_tp **utpp)
2956 {
2957 struct uploaded_tp *next_one;
2958
2959 while (*utpp)
2960 {
2961 next_one = (*utpp)->next;
2962 delete *utpp;
2963 *utpp = next_one;
2964 }
2965 }
2966
2967 /* Given a number and address, return an uploaded tracepoint with that
2968 number, creating if necessary. */
2969
2970 struct uploaded_tsv *
2971 get_uploaded_tsv (int num, struct uploaded_tsv **utsvp)
2972 {
2973 struct uploaded_tsv *utsv;
2974
2975 for (utsv = *utsvp; utsv; utsv = utsv->next)
2976 if (utsv->number == num)
2977 return utsv;
2978
2979 utsv = XCNEW (struct uploaded_tsv);
2980 utsv->number = num;
2981 utsv->next = *utsvp;
2982 *utsvp = utsv;
2983
2984 return utsv;
2985 }
2986
2987 void
2988 free_uploaded_tsvs (struct uploaded_tsv **utsvp)
2989 {
2990 struct uploaded_tsv *next_one;
2991
2992 while (*utsvp)
2993 {
2994 next_one = (*utsvp)->next;
2995 xfree (*utsvp);
2996 *utsvp = next_one;
2997 }
2998 }
2999
3000 /* FIXME this function is heuristic and will miss the cases where the
3001 conditional is semantically identical but differs in whitespace,
3002 such as "x == 0" vs "x==0". */
3003
3004 static int
3005 cond_string_is_same (char *str1, char *str2)
3006 {
3007 if (str1 == NULL || str2 == NULL)
3008 return (str1 == str2);
3009
3010 return (strcmp (str1, str2) == 0);
3011 }
3012
3013 /* Look for an existing tracepoint that seems similar enough to the
3014 uploaded one. Enablement isn't compared, because the user can
3015 toggle that freely, and may have done so in anticipation of the
3016 next trace run. Return the location of matched tracepoint. */
3017
3018 static struct bp_location *
3019 find_matching_tracepoint_location (struct uploaded_tp *utp)
3020 {
3021 for (breakpoint &b : all_tracepoints ())
3022 {
3023 tracepoint &t = gdb::checked_static_cast<tracepoint &> (b);
3024
3025 if (b.type == utp->type
3026 && t.step_count == utp->step
3027 && t.pass_count == utp->pass
3028 && cond_string_is_same (t.cond_string.get (),
3029 utp->cond_string.get ())
3030 /* FIXME also test actions. */
3031 )
3032 {
3033 /* Scan the locations for an address match. */
3034 for (bp_location &loc : b.locations ())
3035 if (loc.address == utp->addr)
3036 return &loc;
3037 }
3038 }
3039 return NULL;
3040 }
3041
3042 /* Given a list of tracepoints uploaded from a target, attempt to
3043 match them up with existing tracepoints, and create new ones if not
3044 found. */
3045
3046 void
3047 merge_uploaded_tracepoints (struct uploaded_tp **uploaded_tps)
3048 {
3049 struct uploaded_tp *utp;
3050 /* A set of tracepoints which are modified. */
3051 std::vector<breakpoint *> modified_tp;
3052
3053 /* Look for GDB tracepoints that match up with our uploaded versions. */
3054 for (utp = *uploaded_tps; utp; utp = utp->next)
3055 {
3056 struct bp_location *loc;
3057 struct tracepoint *t;
3058
3059 loc = find_matching_tracepoint_location (utp);
3060 if (loc)
3061 {
3062 int found = 0;
3063
3064 /* Mark this location as already inserted. */
3065 loc->inserted = 1;
3066 t = gdb::checked_static_cast<tracepoint *> (loc->owner);
3067 gdb_printf (_("Assuming tracepoint %d is same "
3068 "as target's tracepoint %d at %s.\n"),
3069 loc->owner->number, utp->number,
3070 paddress (loc->gdbarch, utp->addr));
3071
3072 /* The tracepoint LOC->owner was modified (the location LOC
3073 was marked as inserted in the target). Save it in
3074 MODIFIED_TP if not there yet. The 'breakpoint-modified'
3075 observers will be notified later once for each tracepoint
3076 saved in MODIFIED_TP. */
3077 for (breakpoint *b : modified_tp)
3078 if (b == loc->owner)
3079 {
3080 found = 1;
3081 break;
3082 }
3083 if (!found)
3084 modified_tp.push_back (loc->owner);
3085 }
3086 else
3087 {
3088 t = create_tracepoint_from_upload (utp);
3089 if (t)
3090 gdb_printf (_("Created tracepoint %d for "
3091 "target's tracepoint %d at %s.\n"),
3092 t->number, utp->number,
3093 paddress (get_current_arch (), utp->addr));
3094 else
3095 gdb_printf (_("Failed to create tracepoint for target's "
3096 "tracepoint %d at %s, skipping it.\n"),
3097 utp->number,
3098 paddress (get_current_arch (), utp->addr));
3099 }
3100 /* Whether found or created, record the number used by the
3101 target, to help with mapping target tracepoints back to their
3102 counterparts here. */
3103 if (t)
3104 t->number_on_target = utp->number;
3105 }
3106
3107 /* Notify 'breakpoint-modified' observer that at least one of B's
3108 locations was changed. */
3109 for (breakpoint *b : modified_tp)
3110 notify_breakpoint_modified (b);
3111
3112 free_uploaded_tps (uploaded_tps);
3113 }
3114
3115 /* Trace state variables don't have much to identify them beyond their
3116 name, so just use that to detect matches. */
3117
3118 static struct trace_state_variable *
3119 find_matching_tsv (struct uploaded_tsv *utsv)
3120 {
3121 if (!utsv->name)
3122 return NULL;
3123
3124 return find_trace_state_variable (utsv->name);
3125 }
3126
3127 static struct trace_state_variable *
3128 create_tsv_from_upload (struct uploaded_tsv *utsv)
3129 {
3130 const char *namebase;
3131 std::string buf;
3132 int try_num = 0;
3133 struct trace_state_variable *tsv;
3134
3135 if (utsv->name)
3136 {
3137 namebase = utsv->name;
3138 buf = namebase;
3139 }
3140 else
3141 {
3142 namebase = "__tsv";
3143 buf = string_printf ("%s_%d", namebase, try_num++);
3144 }
3145
3146 /* Fish for a name that is not in use. */
3147 /* (should check against all internal vars?) */
3148 while (find_trace_state_variable (buf.c_str ()))
3149 buf = string_printf ("%s_%d", namebase, try_num++);
3150
3151 /* We have an available name, create the variable. */
3152 tsv = create_trace_state_variable (buf.c_str ());
3153 tsv->initial_value = utsv->initial_value;
3154 tsv->builtin = utsv->builtin;
3155
3156 interps_notify_tsv_created (tsv);
3157
3158 return tsv;
3159 }
3160
3161 /* Given a list of uploaded trace state variables, try to match them
3162 up with existing variables, or create additional ones. */
3163
3164 void
3165 merge_uploaded_trace_state_variables (struct uploaded_tsv **uploaded_tsvs)
3166 {
3167 struct uploaded_tsv *utsv;
3168 int highest;
3169
3170 /* Most likely some numbers will have to be reassigned as part of
3171 the merge, so clear them all in anticipation. */
3172 for (trace_state_variable &tsv : tvariables)
3173 tsv.number = 0;
3174
3175 for (utsv = *uploaded_tsvs; utsv; utsv = utsv->next)
3176 {
3177 struct trace_state_variable *tsv = find_matching_tsv (utsv);
3178 if (tsv)
3179 {
3180 if (info_verbose)
3181 gdb_printf (_("Assuming trace state variable $%s "
3182 "is same as target's variable %d.\n"),
3183 tsv->name.c_str (), utsv->number);
3184 }
3185 else
3186 {
3187 tsv = create_tsv_from_upload (utsv);
3188 if (info_verbose)
3189 gdb_printf (_("Created trace state variable "
3190 "$%s for target's variable %d.\n"),
3191 tsv->name.c_str (), utsv->number);
3192 }
3193 /* Give precedence to numberings that come from the target. */
3194 if (tsv)
3195 tsv->number = utsv->number;
3196 }
3197
3198 /* Renumber everything that didn't get a target-assigned number. */
3199 highest = 0;
3200 for (const trace_state_variable &tsv : tvariables)
3201 highest = std::max (tsv.number, highest);
3202
3203 ++highest;
3204 for (trace_state_variable &tsv : tvariables)
3205 if (tsv.number == 0)
3206 tsv.number = highest++;
3207
3208 free_uploaded_tsvs (uploaded_tsvs);
3209 }
3210
3211 /* Parse the part of trace status syntax that is shared between
3212 the remote protocol and the trace file reader. */
3213
3214 void
3215 parse_trace_status (const char *line, struct trace_status *ts)
3216 {
3217 const char *p = line, *p1, *p2, *p3, *p_temp;
3218 int end;
3219 ULONGEST val;
3220
3221 ts->running_known = 1;
3222 ts->running = (*p++ == '1');
3223 ts->stop_reason = trace_stop_reason_unknown;
3224 xfree (ts->stop_desc);
3225 ts->stop_desc = NULL;
3226 ts->traceframe_count = -1;
3227 ts->traceframes_created = -1;
3228 ts->buffer_free = -1;
3229 ts->buffer_size = -1;
3230 ts->disconnected_tracing = 0;
3231 ts->circular_buffer = 0;
3232 xfree (ts->user_name);
3233 ts->user_name = NULL;
3234 xfree (ts->notes);
3235 ts->notes = NULL;
3236 ts->start_time = ts->stop_time = 0;
3237
3238 while (*p++)
3239 {
3240 p1 = strchr (p, ':');
3241 if (p1 == NULL)
3242 error (_("Malformed trace status, at %s\n\
3243 Status line: '%s'\n"), p, line);
3244 p3 = strchr (p, ';');
3245 if (p3 == NULL)
3246 p3 = p + strlen (p);
3247 if (strncmp (p, stop_reason_names[trace_buffer_full], p1 - p) == 0)
3248 {
3249 p = unpack_varlen_hex (++p1, &val);
3250 ts->stop_reason = trace_buffer_full;
3251 }
3252 else if (strncmp (p, stop_reason_names[trace_never_run], p1 - p) == 0)
3253 {
3254 p = unpack_varlen_hex (++p1, &val);
3255 ts->stop_reason = trace_never_run;
3256 }
3257 else if (strncmp (p, stop_reason_names[tracepoint_passcount],
3258 p1 - p) == 0)
3259 {
3260 p = unpack_varlen_hex (++p1, &val);
3261 ts->stop_reason = tracepoint_passcount;
3262 ts->stopping_tracepoint = val;
3263 }
3264 else if (strncmp (p, stop_reason_names[trace_stop_command], p1 - p) == 0)
3265 {
3266 p2 = strchr (++p1, ':');
3267 if (!p2 || p2 > p3)
3268 {
3269 /*older style*/
3270 p2 = p1;
3271 }
3272 else if (p2 != p1)
3273 {
3274 ts->stop_desc = (char *) xmalloc (strlen (line));
3275 end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
3276 ts->stop_desc[end] = '\0';
3277 }
3278 else
3279 ts->stop_desc = xstrdup ("");
3280
3281 p = unpack_varlen_hex (++p2, &val);
3282 ts->stop_reason = trace_stop_command;
3283 }
3284 else if (strncmp (p, stop_reason_names[trace_disconnected], p1 - p) == 0)
3285 {
3286 p = unpack_varlen_hex (++p1, &val);
3287 ts->stop_reason = trace_disconnected;
3288 }
3289 else if (strncmp (p, stop_reason_names[tracepoint_error], p1 - p) == 0)
3290 {
3291 p2 = strchr (++p1, ':');
3292 if (p2 != p1)
3293 {
3294 ts->stop_desc = (char *) xmalloc ((p2 - p1) / 2 + 1);
3295 end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
3296 ts->stop_desc[end] = '\0';
3297 }
3298 else
3299 ts->stop_desc = xstrdup ("");
3300
3301 p = unpack_varlen_hex (++p2, &val);
3302 ts->stopping_tracepoint = val;
3303 ts->stop_reason = tracepoint_error;
3304 }
3305 else if (strncmp (p, "tframes", p1 - p) == 0)
3306 {
3307 p = unpack_varlen_hex (++p1, &val);
3308 ts->traceframe_count = val;
3309 }
3310 else if (strncmp (p, "tcreated", p1 - p) == 0)
3311 {
3312 p = unpack_varlen_hex (++p1, &val);
3313 ts->traceframes_created = val;
3314 }
3315 else if (strncmp (p, "tfree", p1 - p) == 0)
3316 {
3317 p = unpack_varlen_hex (++p1, &val);
3318 ts->buffer_free = val;
3319 }
3320 else if (strncmp (p, "tsize", p1 - p) == 0)
3321 {
3322 p = unpack_varlen_hex (++p1, &val);
3323 ts->buffer_size = val;
3324 }
3325 else if (strncmp (p, "disconn", p1 - p) == 0)
3326 {
3327 p = unpack_varlen_hex (++p1, &val);
3328 ts->disconnected_tracing = val;
3329 }
3330 else if (strncmp (p, "circular", p1 - p) == 0)
3331 {
3332 p = unpack_varlen_hex (++p1, &val);
3333 ts->circular_buffer = val;
3334 }
3335 else if (strncmp (p, "starttime", p1 - p) == 0)
3336 {
3337 p = unpack_varlen_hex (++p1, &val);
3338 ts->start_time = val;
3339 }
3340 else if (strncmp (p, "stoptime", p1 - p) == 0)
3341 {
3342 p = unpack_varlen_hex (++p1, &val);
3343 ts->stop_time = val;
3344 }
3345 else if (strncmp (p, "username", p1 - p) == 0)
3346 {
3347 ++p1;
3348 ts->user_name = (char *) xmalloc (strlen (p) / 2);
3349 end = hex2bin (p1, (gdb_byte *) ts->user_name, (p3 - p1) / 2);
3350 ts->user_name[end] = '\0';
3351 p = p3;
3352 }
3353 else if (strncmp (p, "notes", p1 - p) == 0)
3354 {
3355 ++p1;
3356 ts->notes = (char *) xmalloc (strlen (p) / 2);
3357 end = hex2bin (p1, (gdb_byte *) ts->notes, (p3 - p1) / 2);
3358 ts->notes[end] = '\0';
3359 p = p3;
3360 }
3361 else
3362 {
3363 /* Silently skip unknown optional info. */
3364 p_temp = strchr (p1 + 1, ';');
3365 if (p_temp)
3366 p = p_temp;
3367 else
3368 /* Must be at the end. */
3369 break;
3370 }
3371 }
3372 }
3373
3374 void
3375 parse_tracepoint_status (const char *p, tracepoint *tp,
3376 struct uploaded_tp *utp)
3377 {
3378 ULONGEST uval;
3379
3380 p = unpack_varlen_hex (p, &uval);
3381 if (tp)
3382 tp->hit_count += uval;
3383 else
3384 utp->hit_count += uval;
3385 p = unpack_varlen_hex (p + 1, &uval);
3386 if (tp)
3387 tp->traceframe_usage += uval;
3388 else
3389 utp->traceframe_usage += uval;
3390 /* Ignore any extra, allowing for future extensions. */
3391 }
3392
3393 /* Given a line of text defining a part of a tracepoint, parse it into
3394 an "uploaded tracepoint". */
3395
3396 void
3397 parse_tracepoint_definition (const char *line, struct uploaded_tp **utpp)
3398 {
3399 const char *p;
3400 char piece;
3401 ULONGEST num, addr, step, pass, orig_size, xlen, start;
3402 int enabled, end;
3403 enum bptype type;
3404 const char *srctype;
3405 char *buf;
3406 struct uploaded_tp *utp = NULL;
3407
3408 p = line;
3409 /* Both tracepoint and action definitions start with the same number
3410 and address sequence. */
3411 piece = *p++;
3412 p = unpack_varlen_hex (p, &num);
3413 p++; /* skip a colon */
3414 p = unpack_varlen_hex (p, &addr);
3415 p++; /* skip a colon */
3416 if (piece == 'T')
3417 {
3418 gdb::unique_xmalloc_ptr<char[]> cond;
3419
3420 enabled = (*p++ == 'E');
3421 p++; /* skip a colon */
3422 p = unpack_varlen_hex (p, &step);
3423 p++; /* skip a colon */
3424 p = unpack_varlen_hex (p, &pass);
3425 type = bp_tracepoint;
3426 /* Thumb through optional fields. */
3427 while (*p == ':')
3428 {
3429 p++; /* skip a colon */
3430 if (*p == 'F')
3431 {
3432 type = bp_fast_tracepoint;
3433 p++;
3434 p = unpack_varlen_hex (p, &orig_size);
3435 }
3436 else if (*p == 'S')
3437 {
3438 type = bp_static_tracepoint;
3439 p++;
3440 }
3441 else if (*p == 'X')
3442 {
3443 p++;
3444 p = unpack_varlen_hex (p, &xlen);
3445 p++; /* skip a comma */
3446 cond.reset ((char *) xmalloc (2 * xlen + 1));
3447 strncpy (&cond[0], p, 2 * xlen);
3448 cond[2 * xlen] = '\0';
3449 p += 2 * xlen;
3450 }
3451 else
3452 warning (_("Unrecognized char '%c' in tracepoint "
3453 "definition, skipping rest"), *p);
3454 }
3455 utp = get_uploaded_tp (num, addr, utpp);
3456 utp->type = type;
3457 utp->enabled = enabled;
3458 utp->step = step;
3459 utp->pass = pass;
3460 utp->cond = std::move (cond);
3461 }
3462 else if (piece == 'A')
3463 {
3464 utp = get_uploaded_tp (num, addr, utpp);
3465 utp->actions.emplace_back (xstrdup (p));
3466 }
3467 else if (piece == 'S')
3468 {
3469 utp = get_uploaded_tp (num, addr, utpp);
3470 utp->step_actions.emplace_back (xstrdup (p));
3471 }
3472 else if (piece == 'Z')
3473 {
3474 /* Parse a chunk of source form definition. */
3475 utp = get_uploaded_tp (num, addr, utpp);
3476 srctype = p;
3477 p = strchr (p, ':');
3478 p++; /* skip a colon */
3479 p = unpack_varlen_hex (p, &start);
3480 p++; /* skip a colon */
3481 p = unpack_varlen_hex (p, &xlen);
3482 p++; /* skip a colon */
3483
3484 buf = (char *) alloca (strlen (line));
3485
3486 end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
3487 buf[end] = '\0';
3488
3489 if (startswith (srctype, "at:"))
3490 utp->at_string.reset (xstrdup (buf));
3491 else if (startswith (srctype, "cond:"))
3492 utp->cond_string.reset (xstrdup (buf));
3493 else if (startswith (srctype, "cmd:"))
3494 utp->cmd_strings.emplace_back (xstrdup (buf));
3495 }
3496 else if (piece == 'V')
3497 {
3498 utp = get_uploaded_tp (num, addr, utpp);
3499
3500 parse_tracepoint_status (p, NULL, utp);
3501 }
3502 else
3503 {
3504 /* Don't error out, the target might be sending us optional
3505 info that we don't care about. */
3506 warning (_("Unrecognized tracepoint piece '%c', ignoring"), piece);
3507 }
3508 }
3509
3510 /* Convert a textual description of a trace state variable into an
3511 uploaded object. */
3512
3513 void
3514 parse_tsv_definition (const char *line, struct uploaded_tsv **utsvp)
3515 {
3516 const char *p;
3517 char *buf;
3518 ULONGEST num, initval, builtin;
3519 int end;
3520 struct uploaded_tsv *utsv = NULL;
3521
3522 buf = (char *) alloca (strlen (line));
3523
3524 p = line;
3525 p = unpack_varlen_hex (p, &num);
3526 p++; /* skip a colon */
3527 p = unpack_varlen_hex (p, &initval);
3528 p++; /* skip a colon */
3529 p = unpack_varlen_hex (p, &builtin);
3530 p++; /* skip a colon */
3531 end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
3532 buf[end] = '\0';
3533
3534 utsv = get_uploaded_tsv (num, utsvp);
3535 utsv->initial_value = initval;
3536 utsv->builtin = builtin;
3537 utsv->name = xstrdup (buf);
3538 }
3539
3540 /* Given a line of text defining a static tracepoint marker, parse it
3541 into a "static tracepoint marker" object. Throws an error is
3542 parsing fails. If PP is non-null, it points to one past the end of
3543 the parsed marker definition. */
3544
3545 void
3546 parse_static_tracepoint_marker_definition (const char *line, const char **pp,
3547 static_tracepoint_marker *marker)
3548 {
3549 const char *p, *endp;
3550 ULONGEST addr;
3551
3552 p = line;
3553 p = unpack_varlen_hex (p, &addr);
3554 p++; /* skip a colon */
3555
3556 marker->gdbarch = current_inferior ()->arch ();
3557 marker->address = (CORE_ADDR) addr;
3558
3559 endp = strchr (p, ':');
3560 if (endp == NULL)
3561 error (_("bad marker definition: %s"), line);
3562
3563 marker->str_id = hex2str (p, (endp - p) / 2);
3564
3565 p = endp;
3566 p++; /* skip a colon */
3567
3568 /* This definition may be followed by another one, separated by a comma. */
3569 int hex_len;
3570 endp = strchr (p, ',');
3571 if (endp != nullptr)
3572 hex_len = endp - p;
3573 else
3574 hex_len = strlen (p);
3575
3576 marker->extra = hex2str (p, hex_len / 2);
3577
3578 if (pp != nullptr)
3579 *pp = p + hex_len;
3580 }
3581
3582 /* Print MARKER to gdb_stdout. */
3583
3584 static void
3585 print_one_static_tracepoint_marker (int count,
3586 const static_tracepoint_marker &marker)
3587 {
3588 struct symbol *sym;
3589
3590 struct ui_out *uiout = current_uiout;
3591
3592 symtab_and_line sal;
3593 sal.pc = marker.address;
3594
3595 std::vector<breakpoint *> tracepoints
3596 = static_tracepoints_here (marker.address);
3597
3598 ui_out_emit_tuple tuple_emitter (uiout, "marker");
3599
3600 /* A counter field to help readability. This is not a stable
3601 identifier! */
3602 uiout->field_signed ("count", count);
3603
3604 uiout->field_string ("marker-id", marker.str_id);
3605
3606 uiout->field_fmt ("enabled", "%c",
3607 !tracepoints.empty () ? 'y' : 'n');
3608 uiout->spaces (2);
3609
3610 int wrap_indent = 35;
3611 if (gdbarch_addr_bit (marker.gdbarch) <= 32)
3612 wrap_indent += 11;
3613 else
3614 wrap_indent += 19;
3615
3616 const char *extra_field_indent = " ";
3617
3618 uiout->field_core_addr ("addr", marker.gdbarch, marker.address);
3619
3620 sal = find_pc_line (marker.address, 0);
3621 sym = find_pc_sect_function (marker.address, NULL);
3622 if (sym)
3623 {
3624 uiout->text ("in ");
3625 uiout->field_string ("func", sym->print_name (),
3626 function_name_style.style ());
3627 uiout->wrap_hint (wrap_indent);
3628 uiout->text (" at ");
3629 }
3630 else
3631 uiout->field_skip ("func");
3632
3633 if (sal.symtab != NULL)
3634 {
3635 uiout->field_string ("file",
3636 symtab_to_filename_for_display (sal.symtab),
3637 file_name_style.style ());
3638 uiout->text (":");
3639
3640 if (uiout->is_mi_like_p ())
3641 {
3642 const char *fullname = symtab_to_fullname (sal.symtab);
3643
3644 uiout->field_string ("fullname", fullname);
3645 }
3646 else
3647 uiout->field_skip ("fullname");
3648
3649 uiout->field_signed ("line", sal.line, line_number_style.style ());
3650 }
3651 else
3652 {
3653 uiout->field_skip ("fullname");
3654 uiout->field_skip ("line");
3655 }
3656
3657 uiout->text ("\n");
3658 uiout->text (extra_field_indent);
3659 uiout->text (_("Data: \""));
3660 uiout->field_string ("extra-data", marker.extra);
3661 uiout->text ("\"\n");
3662
3663 if (!tracepoints.empty ())
3664 {
3665 int ix;
3666
3667 {
3668 ui_out_emit_tuple inner_tuple_emitter (uiout, "tracepoints-at");
3669
3670 uiout->text (extra_field_indent);
3671 uiout->text (_("Probed by static tracepoints: "));
3672 for (ix = 0; ix < tracepoints.size (); ix++)
3673 {
3674 if (ix > 0)
3675 uiout->text (", ");
3676 uiout->text ("#");
3677 uiout->field_signed ("tracepoint-id", tracepoints[ix]->number);
3678 }
3679 }
3680
3681 if (uiout->is_mi_like_p ())
3682 uiout->field_signed ("number-of-tracepoints", tracepoints.size ());
3683 else
3684 uiout->text ("\n");
3685 }
3686 }
3687
3688 static void
3689 info_static_tracepoint_markers_command (const char *arg, int from_tty)
3690 {
3691 struct ui_out *uiout = current_uiout;
3692 std::vector<static_tracepoint_marker> markers
3693 = target_static_tracepoint_markers_by_strid (NULL);
3694
3695 /* We don't have to check target_can_use_agent and agent's capability on
3696 static tracepoint here, in order to be compatible with older GDBserver.
3697 We don't check USE_AGENT is true or not, because static tracepoints
3698 don't work without in-process agent, so we don't bother users to type
3699 `set agent on' when to use static tracepoint. */
3700
3701 ui_out_emit_table table_emitter (uiout, 5, -1,
3702 "StaticTracepointMarkersTable");
3703
3704 uiout->table_header (7, ui_left, "counter", "Cnt");
3705
3706 uiout->table_header (40, ui_left, "marker-id", "ID");
3707
3708 uiout->table_header (3, ui_left, "enabled", "Enb");
3709 if (gdbarch_addr_bit (current_inferior ()->arch ()) <= 32)
3710 uiout->table_header (10, ui_left, "addr", "Address");
3711 else
3712 uiout->table_header (18, ui_left, "addr", "Address");
3713 uiout->table_header (40, ui_noalign, "what", "What");
3714
3715 uiout->table_body ();
3716
3717 for (int i = 0; i < markers.size (); i++)
3718 print_one_static_tracepoint_marker (i + 1, markers[i]);
3719 }
3720
3721 /* The $_sdata convenience variable is a bit special. We don't know
3722 for sure type of the value until we actually have a chance to fetch
3723 the data --- the size of the object depends on what has been
3724 collected. We solve this by making $_sdata be an internalvar that
3725 creates a new value on access. */
3726
3727 /* Return a new value with the correct type for the sdata object of
3728 the current trace frame. Return a void value if there's no object
3729 available. */
3730
3731 static struct value *
3732 sdata_make_value (struct gdbarch *gdbarch, struct internalvar *var,
3733 void *ignore)
3734 {
3735 /* We need to read the whole object before we know its size. */
3736 std::optional<gdb::byte_vector> buf
3737 = target_read_alloc (current_inferior ()->top_target (),
3738 TARGET_OBJECT_STATIC_TRACE_DATA,
3739 NULL);
3740 if (buf)
3741 {
3742 struct value *v;
3743 struct type *type;
3744
3745 type = init_vector_type (builtin_type (gdbarch)->builtin_true_char,
3746 buf->size ());
3747 v = value::allocate (type);
3748 memcpy (v->contents_raw ().data (), buf->data (), buf->size ());
3749 return v;
3750 }
3751 else
3752 return value::allocate (builtin_type (gdbarch)->builtin_void);
3753 }
3754
3755 #if !defined(HAVE_LIBEXPAT)
3756
3757 struct std::unique_ptr<traceframe_info>
3758 parse_traceframe_info (const char *tframe_info)
3759 {
3760 static int have_warned;
3761
3762 if (!have_warned)
3763 {
3764 have_warned = 1;
3765 warning (_("Can not parse XML trace frame info; XML support "
3766 "was disabled at compile time"));
3767 }
3768
3769 return NULL;
3770 }
3771
3772 #else /* HAVE_LIBEXPAT */
3773
3774 #include "xml-support.h"
3775
3776 /* Handle the start of a <memory> element. */
3777
3778 static void
3779 traceframe_info_start_memory (struct gdb_xml_parser *parser,
3780 const struct gdb_xml_element *element,
3781 void *user_data,
3782 std::vector<gdb_xml_value> &attributes)
3783 {
3784 struct traceframe_info *info = (struct traceframe_info *) user_data;
3785 ULONGEST *start_p, *length_p;
3786
3787 start_p
3788 = (ULONGEST *) xml_find_attribute (attributes, "start")->value.get ();
3789 length_p
3790 = (ULONGEST *) xml_find_attribute (attributes, "length")->value.get ();
3791
3792 info->memory.emplace_back (*start_p, *length_p);
3793 }
3794
3795 /* Handle the start of a <tvar> element. */
3796
3797 static void
3798 traceframe_info_start_tvar (struct gdb_xml_parser *parser,
3799 const struct gdb_xml_element *element,
3800 void *user_data,
3801 std::vector<gdb_xml_value> &attributes)
3802 {
3803 struct traceframe_info *info = (struct traceframe_info *) user_data;
3804 const char *id_attrib
3805 = (const char *) xml_find_attribute (attributes, "id")->value.get ();
3806 int id = gdb_xml_parse_ulongest (parser, id_attrib);
3807
3808 info->tvars.push_back (id);
3809 }
3810
3811 /* The allowed elements and attributes for an XML memory map. */
3812
3813 static const struct gdb_xml_attribute memory_attributes[] = {
3814 { "start", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
3815 { "length", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
3816 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3817 };
3818
3819 static const struct gdb_xml_attribute tvar_attributes[] = {
3820 { "id", GDB_XML_AF_NONE, NULL, NULL },
3821 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3822 };
3823
3824 static const struct gdb_xml_element traceframe_info_children[] = {
3825 { "memory", memory_attributes, NULL,
3826 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3827 traceframe_info_start_memory, NULL },
3828 { "tvar", tvar_attributes, NULL,
3829 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3830 traceframe_info_start_tvar, NULL },
3831 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3832 };
3833
3834 static const struct gdb_xml_element traceframe_info_elements[] = {
3835 { "traceframe-info", NULL, traceframe_info_children, GDB_XML_EF_NONE,
3836 NULL, NULL },
3837 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3838 };
3839
3840 /* Parse a traceframe-info XML document. */
3841
3842 traceframe_info_up
3843 parse_traceframe_info (const char *tframe_info)
3844 {
3845 traceframe_info_up result (new traceframe_info);
3846
3847 if (gdb_xml_parse_quick (_("trace frame info"),
3848 "traceframe-info.dtd", traceframe_info_elements,
3849 tframe_info, result.get ()) == 0)
3850 return result;
3851
3852 return NULL;
3853 }
3854
3855 #endif /* HAVE_LIBEXPAT */
3856
3857 /* Returns the traceframe_info object for the current traceframe.
3858 This is where we avoid re-fetching the object from the target if we
3859 already have it cached. */
3860
3861 struct traceframe_info *
3862 get_traceframe_info (void)
3863 {
3864 if (current_traceframe_info == NULL)
3865 current_traceframe_info = target_traceframe_info ();
3866
3867 return current_traceframe_info.get ();
3868 }
3869
3870 /* If the target supports the query, return in RESULT the set of
3871 collected memory in the current traceframe, found within the LEN
3872 bytes range starting at MEMADDR. Returns true if the target
3873 supports the query, otherwise returns false, and RESULT is left
3874 undefined. */
3875
3876 int
3877 traceframe_available_memory (std::vector<mem_range> *result,
3878 CORE_ADDR memaddr, ULONGEST len)
3879 {
3880 struct traceframe_info *info = get_traceframe_info ();
3881
3882 if (info != NULL)
3883 {
3884 result->clear ();
3885
3886 for (mem_range &r : info->memory)
3887 if (mem_ranges_overlap (r.start, r.length, memaddr, len))
3888 {
3889 ULONGEST lo1, hi1, lo2, hi2;
3890
3891 lo1 = memaddr;
3892 hi1 = memaddr + len;
3893
3894 lo2 = r.start;
3895 hi2 = r.start + r.length;
3896
3897 CORE_ADDR start = std::max (lo1, lo2);
3898 int length = std::min (hi1, hi2) - start;
3899
3900 result->emplace_back (start, length);
3901 }
3902
3903 normalize_mem_ranges (result);
3904 return 1;
3905 }
3906
3907 return 0;
3908 }
3909
3910 /* Implementation of `sdata' variable. */
3911
3912 static const struct internalvar_funcs sdata_funcs =
3913 {
3914 sdata_make_value,
3915 NULL
3916 };
3917
3918 /* See tracepoint.h. */
3919 cmd_list_element *while_stepping_cmd_element = nullptr;
3920
3921 /* module initialization */
3922 INIT_GDB_FILE (tracepoint)
3923 {
3924 struct cmd_list_element *c;
3925
3926 /* Explicitly create without lookup, since that tries to create a
3927 value with a void typed value, and when we get here, gdbarch
3928 isn't initialized yet. At this point, we're quite sure there
3929 isn't another convenience variable of the same name. */
3930 create_internalvar_type_lazy ("_sdata", &sdata_funcs, NULL);
3931
3932 traceframe_number = -1;
3933 tracepoint_number = -1;
3934
3935 add_info ("scope", info_scope_command,
3936 _("List the variables local to a scope."));
3937
3938 add_cmd ("tracepoints", class_trace,
3939 _("Tracing of program execution without stopping the program."),
3940 &cmdlist);
3941
3942 add_com ("tdump", class_trace, tdump_command,
3943 _("Print everything collected at the current tracepoint."));
3944
3945 c = add_com ("tvariable", class_trace, trace_variable_command,_("\
3946 Define a trace state variable.\n\
3947 Argument is a $-prefixed name, optionally followed\n\
3948 by '=' and an expression that sets the initial value\n\
3949 at the start of tracing."));
3950 set_cmd_completer (c, expression_completer);
3951
3952 add_cmd ("tvariable", class_trace, delete_trace_variable_command, _("\
3953 Delete one or more trace state variables.\n\
3954 Arguments are the names of the variables to delete.\n\
3955 If no arguments are supplied, delete all variables."), &deletelist);
3956 /* FIXME add a trace variable completer. */
3957
3958 add_info ("tvariables", info_tvariables_command, _("\
3959 Status of trace state variables and their values."));
3960
3961 add_info ("static-tracepoint-markers",
3962 info_static_tracepoint_markers_command, _("\
3963 List target static tracepoints markers."));
3964
3965 add_prefix_cmd ("tfind", class_trace, tfind_command, _("\
3966 Select a trace frame.\n\
3967 No argument means forward by one frame; '-' means backward by one frame."),
3968 &tfindlist, 1, &cmdlist);
3969
3970 add_cmd ("outside", class_trace, tfind_outside_command, _("\
3971 Select a trace frame whose PC is outside the given range (exclusive).\n\
3972 Usage: tfind outside ADDR1, ADDR2"),
3973 &tfindlist);
3974
3975 add_cmd ("range", class_trace, tfind_range_command, _("\
3976 Select a trace frame whose PC is in the given range (inclusive).\n\
3977 Usage: tfind range ADDR1, ADDR2"),
3978 &tfindlist);
3979
3980 add_cmd ("line", class_trace, tfind_line_command, _("\
3981 Select a trace frame by source line.\n\
3982 Argument can be a line number (with optional source file),\n\
3983 a function name, or '*' followed by an address.\n\
3984 Default argument is 'the next source line that was traced'."),
3985 &tfindlist);
3986
3987 add_cmd ("tracepoint", class_trace, tfind_tracepoint_command, _("\
3988 Select a trace frame by tracepoint number.\n\
3989 Default is the tracepoint for the current trace frame."),
3990 &tfindlist);
3991
3992 add_cmd ("pc", class_trace, tfind_pc_command, _("\
3993 Select a trace frame by PC.\n\
3994 Default is the current PC, or the PC of the current trace frame."),
3995 &tfindlist);
3996
3997 cmd_list_element *tfind_end_cmd
3998 = add_cmd ("end", class_trace, tfind_end_command, _("\
3999 De-select any trace frame and resume 'live' debugging."), &tfindlist);
4000
4001 add_alias_cmd ("none", tfind_end_cmd, class_trace, 0, &tfindlist);
4002
4003 add_cmd ("start", class_trace, tfind_start_command,
4004 _("Select the first trace frame in the trace buffer."),
4005 &tfindlist);
4006
4007 add_com ("tstatus", class_trace, tstatus_command,
4008 _("Display the status of the current trace data collection."));
4009
4010 add_com ("tstop", class_trace, tstop_command, _("\
4011 Stop trace data collection.\n\
4012 Usage: tstop [NOTES]...\n\
4013 Any arguments supplied are recorded with the trace as a stop reason and\n\
4014 reported by tstatus (if the target supports trace notes)."));
4015
4016 add_com ("tstart", class_trace, tstart_command, _("\
4017 Start trace data collection.\n\
4018 Usage: tstart [NOTES]...\n\
4019 Any arguments supplied are recorded with the trace as a note and\n\
4020 reported by tstatus (if the target supports trace notes)."));
4021
4022 add_com ("end", class_trace, end_actions_pseudocommand, _("\
4023 Ends a list of commands or actions.\n\
4024 Several GDB commands allow you to enter a list of commands or actions.\n\
4025 Entering \"end\" on a line by itself is the normal way to terminate\n\
4026 such a list.\n\n\
4027 Note: the \"end\" command cannot be used at the gdb prompt."));
4028
4029 while_stepping_cmd_element = add_com ("while-stepping", class_trace,
4030 while_stepping_pseudocommand, _("\
4031 Specify single-stepping behavior at a tracepoint.\n\
4032 Argument is number of instructions to trace in single-step mode\n\
4033 following the tracepoint. This command is normally followed by\n\
4034 one or more \"collect\" commands, to specify what to collect\n\
4035 while single-stepping.\n\n\
4036 Note: this command can only be used in a tracepoint \"actions\" list."));
4037
4038 add_com_alias ("ws", while_stepping_cmd_element, class_trace, 0);
4039 add_com_alias ("stepping", while_stepping_cmd_element, class_trace, 0);
4040
4041 add_com ("collect", class_trace, collect_pseudocommand, _("\
4042 Specify one or more data items to be collected at a tracepoint.\n\
4043 Accepts a comma-separated list of (one or more) expressions. GDB will\n\
4044 collect all data (variables, registers) referenced by that expression.\n\
4045 Also accepts the following special arguments:\n\
4046 $regs -- all registers.\n\
4047 $args -- all function arguments.\n\
4048 $locals -- all variables local to the block/function scope.\n\
4049 $_sdata -- static tracepoint data (ignored for non-static tracepoints).\n\
4050 Note: this command can only be used in a tracepoint \"actions\" list."));
4051
4052 add_com ("teval", class_trace, teval_pseudocommand, _("\
4053 Specify one or more expressions to be evaluated at a tracepoint.\n\
4054 Accepts a comma-separated list of (one or more) expressions.\n\
4055 The result of each evaluation will be discarded.\n\
4056 Note: this command can only be used in a tracepoint \"actions\" list."));
4057
4058 add_com ("actions", class_trace, actions_command, _("\
4059 Specify the actions to be taken at a tracepoint.\n\
4060 Tracepoint actions may include collecting of specified data,\n\
4061 single-stepping, or enabling/disabling other tracepoints,\n\
4062 depending on target's capabilities."));
4063
4064 add_setshow_string_cmd ("default-collect", class_trace,
4065 &default_collect, _("\
4066 Set the list of expressions to collect by default."), _("\
4067 Show the list of expressions to collect by default."), NULL,
4068 NULL, NULL,
4069 &setlist, &showlist);
4070
4071 add_setshow_boolean_cmd ("disconnected-tracing", no_class,
4072 &disconnected_tracing, _("\
4073 Set whether tracing continues after GDB disconnects."), _("\
4074 Show whether tracing continues after GDB disconnects."), _("\
4075 Use this to continue a tracing run even if GDB disconnects\n\
4076 or detaches from the target. You can reconnect later and look at\n\
4077 trace data collected in the meantime."),
4078 set_disconnected_tracing,
4079 NULL,
4080 &setlist,
4081 &showlist);
4082
4083 add_setshow_boolean_cmd ("circular-trace-buffer", no_class,
4084 &circular_trace_buffer, _("\
4085 Set target's use of circular trace buffer."), _("\
4086 Show target's use of circular trace buffer."), _("\
4087 Use this to make the trace buffer into a circular buffer,\n\
4088 which will discard traceframes (oldest first) instead of filling\n\
4089 up and stopping the trace run."),
4090 set_circular_trace_buffer,
4091 NULL,
4092 &setlist,
4093 &showlist);
4094
4095 add_setshow_zuinteger_unlimited_cmd ("trace-buffer-size", no_class,
4096 &trace_buffer_size, _("\
4097 Set requested size of trace buffer."), _("\
4098 Show requested size of trace buffer."), _("\
4099 Use this to choose a size for the trace buffer. Some targets\n\
4100 may have fixed or limited buffer sizes. Specifying \"unlimited\" or -1\n\
4101 disables any attempt to set the buffer size and lets the target choose."),
4102 set_trace_buffer_size, NULL,
4103 &setlist, &showlist);
4104
4105 add_setshow_string_cmd ("trace-user", class_trace,
4106 &trace_user, _("\
4107 Set the user name to use for current and future trace runs."), _("\
4108 Show the user name to use for current and future trace runs."), NULL,
4109 set_trace_user, NULL,
4110 &setlist, &showlist);
4111
4112 add_setshow_string_cmd ("trace-notes", class_trace,
4113 &trace_notes, _("\
4114 Set notes string to use for current and future trace runs."), _("\
4115 Show the notes string to use for current and future trace runs."), NULL,
4116 set_trace_notes, NULL,
4117 &setlist, &showlist);
4118
4119 add_setshow_string_cmd ("trace-stop-notes", class_trace,
4120 &trace_stop_notes, _("\
4121 Set notes string to use for future tstop commands."), _("\
4122 Show the notes string to use for future tstop commands."), NULL,
4123 set_trace_stop_notes, NULL,
4124 &setlist, &showlist);
4125 }