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