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