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