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