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