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