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