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