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