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