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