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