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