gdb/
[platform/upstream/binutils.git] / gdb / tracepoint.c
1 /* Tracing functionality for remote targets in custom GDB protocol
2
3    Copyright (C) 1997-2013 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 "language.h"
30 #include "gdb_string.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 "gdbcore.h"
48 #include "remote.h"
49 #include "source.h"
50 #include "ax.h"
51 #include "ax-gdb.h"
52 #include "memrange.h"
53 #include "exceptions.h"
54 #include "cli/cli-utils.h"
55 #include "probe.h"
56 #include "ctf.h"
57 #include "completer.h"
58 #include "filestuff.h"
59
60 /* readline include files */
61 #include "readline/readline.h"
62 #include "readline/history.h"
63
64 /* readline defines this.  */
65 #undef savestring
66
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
70
71 #ifndef O_LARGEFILE
72 #define O_LARGEFILE 0
73 #endif
74
75 /* Maximum length of an agent aexpression.
76    This accounts for the fact that packets are limited to 400 bytes
77    (which includes everything -- including the checksum), and assumes
78    the worst case of maximum length for each of the pieces of a
79    continuation packet.
80
81    NOTE: expressions get mem2hex'ed otherwise this would be twice as
82    large.  (400 - 31)/2 == 184 */
83 #define MAX_AGENT_EXPR_LEN      184
84
85 /* A hook used to notify the UI of tracepoint operations.  */
86
87 void (*deprecated_trace_find_hook) (char *arg, int from_tty);
88 void (*deprecated_trace_start_stop_hook) (int start, int from_tty);
89
90 extern void (*deprecated_readline_begin_hook) (char *, ...);
91 extern char *(*deprecated_readline_hook) (char *);
92 extern void (*deprecated_readline_end_hook) (void);
93
94 /* 
95    Tracepoint.c:
96
97    This module defines the following debugger commands:
98    trace            : set a tracepoint on a function, line, or address.
99    info trace       : list all debugger-defined tracepoints.
100    delete trace     : delete one or more tracepoints.
101    enable trace     : enable one or more tracepoints.
102    disable trace    : disable one or more tracepoints.
103    actions          : specify actions to be taken at a tracepoint.
104    passcount        : specify a pass count for a tracepoint.
105    tstart           : start a trace experiment.
106    tstop            : stop a trace experiment.
107    tstatus          : query the status of a trace experiment.
108    tfind            : find a trace frame in the trace buffer.
109    tdump            : print everything collected at the current tracepoint.
110    save-tracepoints : write tracepoint setup into a file.
111
112    This module defines the following user-visible debugger variables:
113    $trace_frame : sequence number of trace frame currently being debugged.
114    $trace_line  : source line of trace frame currently being debugged.
115    $trace_file  : source file of trace frame currently being debugged.
116    $tracepoint  : tracepoint number of trace frame currently being debugged.
117  */
118
119
120 /* ======= Important global variables: ======= */
121
122 /* The list of all trace state variables.  We don't retain pointers to
123    any of these for any reason - API is by name or number only - so it
124    works to have a vector of objects.  */
125
126 typedef struct trace_state_variable tsv_s;
127 DEF_VEC_O(tsv_s);
128
129 static VEC(tsv_s) *tvariables;
130
131 /* The next integer to assign to a variable.  */
132
133 static int next_tsv_number = 1;
134
135 /* Number of last traceframe collected.  */
136 static int traceframe_number;
137
138 /* Tracepoint for last traceframe collected.  */
139 static int tracepoint_number;
140
141 /* Symbol for function for last traceframe collected.  */
142 static struct symbol *traceframe_fun;
143
144 /* Symtab and line for last traceframe collected.  */
145 static struct symtab_and_line traceframe_sal;
146
147 /* The traceframe info of the current traceframe.  NULL if we haven't
148    yet attempted to fetch it, or if the target does not support
149    fetching this object, or if we're not inspecting a traceframe
150    presently.  */
151 static struct traceframe_info *traceframe_info;
152
153 /* Tracing command lists.  */
154 static struct cmd_list_element *tfindlist;
155
156 /* List of expressions to collect by default at each tracepoint hit.  */
157 char *default_collect = "";
158
159 static int disconnected_tracing;
160
161 /* This variable controls whether we ask the target for a linear or
162    circular trace buffer.  */
163
164 static int circular_trace_buffer;
165
166 /* This variable is the requested trace buffer size, or -1 to indicate
167    that we don't care and leave it up to the target to set a size.  */
168
169 static int trace_buffer_size = -1;
170
171 /* Textual notes applying to the current and/or future trace runs.  */
172
173 char *trace_user = NULL;
174
175 /* Textual notes applying to the current and/or future trace runs.  */
176
177 char *trace_notes = NULL;
178
179 /* Textual notes applying to the stopping of a trace.  */
180
181 char *trace_stop_notes = NULL;
182
183 /* ======= Important command functions: ======= */
184 static void trace_actions_command (char *, int);
185 static void trace_start_command (char *, int);
186 static void trace_stop_command (char *, int);
187 static void trace_status_command (char *, int);
188 static void trace_find_command (char *, int);
189 static void trace_find_pc_command (char *, int);
190 static void trace_find_tracepoint_command (char *, int);
191 static void trace_find_line_command (char *, int);
192 static void trace_find_range_command (char *, int);
193 static void trace_find_outside_command (char *, int);
194 static void trace_dump_command (char *, int);
195
196 /* support routines */
197
198 struct collection_list;
199 static void add_aexpr (struct collection_list *, struct agent_expr *);
200 static char *mem2hex (gdb_byte *, char *, int);
201 static void add_register (struct collection_list *collection,
202                           unsigned int regno);
203
204 static void free_uploaded_tps (struct uploaded_tp **utpp);
205 static void free_uploaded_tsvs (struct uploaded_tsv **utsvp);
206
207
208 extern void _initialize_tracepoint (void);
209
210 static struct trace_status trace_status;
211
212 char *stop_reason_names[] = {
213   "tunknown",
214   "tnotrun",
215   "tstop",
216   "tfull",
217   "tdisconnected",
218   "tpasscount",
219   "terror"
220 };
221
222 struct trace_status *
223 current_trace_status (void)
224 {
225   return &trace_status;
226 }
227
228 /* Destroy INFO.  */
229
230 static void
231 free_traceframe_info (struct traceframe_info *info)
232 {
233   if (info != NULL)
234     {
235       VEC_free (mem_range_s, info->memory);
236
237       xfree (info);
238     }
239 }
240
241 /* Free and clear the traceframe info cache of the current
242    traceframe.  */
243
244 static void
245 clear_traceframe_info (void)
246 {
247   free_traceframe_info (traceframe_info);
248   traceframe_info = NULL;
249 }
250
251 /* Set traceframe number to NUM.  */
252 static void
253 set_traceframe_num (int num)
254 {
255   traceframe_number = num;
256   set_internalvar_integer (lookup_internalvar ("trace_frame"), num);
257 }
258
259 /* Set tracepoint number to NUM.  */
260 static void
261 set_tracepoint_num (int num)
262 {
263   tracepoint_number = num;
264   set_internalvar_integer (lookup_internalvar ("tracepoint"), num);
265 }
266
267 /* Set externally visible debug variables for querying/printing
268    the traceframe context (line, function, file).  */
269
270 static void
271 set_traceframe_context (struct frame_info *trace_frame)
272 {
273   CORE_ADDR trace_pc;
274
275   /* Save as globals for internal use.  */
276   if (trace_frame != NULL
277       && get_frame_pc_if_available (trace_frame, &trace_pc))
278     {
279       traceframe_sal = find_pc_line (trace_pc, 0);
280       traceframe_fun = find_pc_function (trace_pc);
281
282       /* Save linenumber as "$trace_line", a debugger variable visible to
283          users.  */
284       set_internalvar_integer (lookup_internalvar ("trace_line"),
285                                traceframe_sal.line);
286     }
287   else
288     {
289       init_sal (&traceframe_sal);
290       traceframe_fun = NULL;
291       set_internalvar_integer (lookup_internalvar ("trace_line"), -1);
292     }
293
294   /* Save func name as "$trace_func", a debugger variable visible to
295      users.  */
296   if (traceframe_fun == NULL
297       || SYMBOL_LINKAGE_NAME (traceframe_fun) == NULL)
298     clear_internalvar (lookup_internalvar ("trace_func"));
299   else
300     set_internalvar_string (lookup_internalvar ("trace_func"),
301                             SYMBOL_LINKAGE_NAME (traceframe_fun));
302
303   /* Save file name as "$trace_file", a debugger variable visible to
304      users.  */
305   if (traceframe_sal.symtab == NULL)
306     clear_internalvar (lookup_internalvar ("trace_file"));
307   else
308     set_internalvar_string (lookup_internalvar ("trace_file"),
309                         symtab_to_filename_for_display (traceframe_sal.symtab));
310 }
311
312 /* Create a new trace state variable with the given name.  */
313
314 struct trace_state_variable *
315 create_trace_state_variable (const char *name)
316 {
317   struct trace_state_variable tsv;
318
319   memset (&tsv, 0, sizeof (tsv));
320   tsv.name = xstrdup (name);
321   tsv.number = next_tsv_number++;
322   return VEC_safe_push (tsv_s, tvariables, &tsv);
323 }
324
325 /* Look for a trace state variable of the given name.  */
326
327 struct trace_state_variable *
328 find_trace_state_variable (const char *name)
329 {
330   struct trace_state_variable *tsv;
331   int ix;
332
333   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
334     if (strcmp (name, tsv->name) == 0)
335       return tsv;
336
337   return NULL;
338 }
339
340 static void
341 delete_trace_state_variable (const char *name)
342 {
343   struct trace_state_variable *tsv;
344   int ix;
345
346   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
347     if (strcmp (name, tsv->name) == 0)
348       {
349         observer_notify_tsv_deleted (tsv);
350
351         xfree ((void *)tsv->name);
352         VEC_unordered_remove (tsv_s, tvariables, ix);
353
354         return;
355       }
356
357   warning (_("No trace variable named \"$%s\", not deleting"), name);
358 }
359
360 /* Throws an error if NAME is not valid syntax for a trace state
361    variable's name.  */
362
363 void
364 validate_trace_state_variable_name (const char *name)
365 {
366   const char *p;
367
368   if (*name == '\0')
369     error (_("Must supply a non-empty variable name"));
370
371   /* All digits in the name is reserved for value history
372      references.  */
373   for (p = name; isdigit (*p); p++)
374     ;
375   if (*p == '\0')
376     error (_("$%s is not a valid trace state variable name"), name);
377
378   for (p = name; isalnum (*p) || *p == '_'; p++)
379     ;
380   if (*p != '\0')
381     error (_("$%s is not a valid trace state variable name"), name);
382 }
383
384 /* The 'tvariable' command collects a name and optional expression to
385    evaluate into an initial value.  */
386
387 static void
388 trace_variable_command (char *args, int from_tty)
389 {
390   struct cleanup *old_chain;
391   LONGEST initval = 0;
392   struct trace_state_variable *tsv;
393   char *name, *p;
394
395   if (!args || !*args)
396     error_no_arg (_("Syntax is $NAME [ = EXPR ]"));
397
398   /* Only allow two syntaxes; "$name" and "$name=value".  */
399   p = skip_spaces (args);
400
401   if (*p++ != '$')
402     error (_("Name of trace variable should start with '$'"));
403
404   name = p;
405   while (isalnum (*p) || *p == '_')
406     p++;
407   name = savestring (name, p - name);
408   old_chain = make_cleanup (xfree, name);
409
410   p = skip_spaces (p);
411   if (*p != '=' && *p != '\0')
412     error (_("Syntax must be $NAME [ = EXPR ]"));
413
414   validate_trace_state_variable_name (name);
415
416   if (*p == '=')
417     initval = value_as_long (parse_and_eval (++p));
418
419   /* If the variable already exists, just change its initial value.  */
420   tsv = find_trace_state_variable (name);
421   if (tsv)
422     {
423       if (tsv->initial_value != initval)
424         {
425           tsv->initial_value = initval;
426           observer_notify_tsv_modified (tsv);
427         }
428       printf_filtered (_("Trace state variable $%s "
429                          "now has initial value %s.\n"),
430                        tsv->name, plongest (tsv->initial_value));
431       do_cleanups (old_chain);
432       return;
433     }
434
435   /* Create a new variable.  */
436   tsv = create_trace_state_variable (name);
437   tsv->initial_value = initval;
438
439   observer_notify_tsv_created (tsv);
440
441   printf_filtered (_("Trace state variable $%s "
442                      "created, with initial value %s.\n"),
443                    tsv->name, plongest (tsv->initial_value));
444
445   do_cleanups (old_chain);
446 }
447
448 static void
449 delete_trace_variable_command (char *args, int from_tty)
450 {
451   int ix;
452   char **argv;
453   struct cleanup *back_to;
454
455   if (args == NULL)
456     {
457       if (query (_("Delete all trace state variables? ")))
458         VEC_free (tsv_s, tvariables);
459       dont_repeat ();
460       observer_notify_tsv_deleted (NULL);
461       return;
462     }
463
464   argv = gdb_buildargv (args);
465   back_to = make_cleanup_freeargv (argv);
466
467   for (ix = 0; argv[ix] != NULL; ix++)
468     {
469       if (*argv[ix] == '$')
470         delete_trace_state_variable (argv[ix] + 1);
471       else
472         warning (_("Name \"%s\" not prefixed with '$', ignoring"), argv[ix]);
473     }
474
475   do_cleanups (back_to);
476
477   dont_repeat ();
478 }
479
480 void
481 tvariables_info_1 (void)
482 {
483   struct trace_state_variable *tsv;
484   int ix;
485   int count = 0;
486   struct cleanup *back_to;
487   struct ui_out *uiout = current_uiout;
488
489   if (VEC_length (tsv_s, tvariables) == 0 && !ui_out_is_mi_like_p (uiout))
490     {
491       printf_filtered (_("No trace state variables.\n"));
492       return;
493     }
494
495   /* Try to acquire values from the target.  */
496   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix, ++count)
497     tsv->value_known = target_get_trace_state_variable_value (tsv->number,
498                                                               &(tsv->value));
499
500   back_to = make_cleanup_ui_out_table_begin_end (uiout, 3,
501                                                  count, "trace-variables");
502   ui_out_table_header (uiout, 15, ui_left, "name", "Name");
503   ui_out_table_header (uiout, 11, ui_left, "initial", "Initial");
504   ui_out_table_header (uiout, 11, ui_left, "current", "Current");
505
506   ui_out_table_body (uiout);
507
508   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
509     {
510       struct cleanup *back_to2;
511       char *c;
512       char *name;
513
514       back_to2 = make_cleanup_ui_out_tuple_begin_end (uiout, "variable");
515
516       name = concat ("$", tsv->name, (char *) NULL);
517       make_cleanup (xfree, name);
518       ui_out_field_string (uiout, "name", name);
519       ui_out_field_string (uiout, "initial", plongest (tsv->initial_value));
520
521       if (tsv->value_known)
522         c = plongest (tsv->value);
523       else if (ui_out_is_mi_like_p (uiout))
524         /* For MI, we prefer not to use magic string constants, but rather
525            omit the field completely.  The difference between unknown and
526            undefined does not seem important enough to represent.  */
527         c = NULL;
528       else if (current_trace_status ()->running || traceframe_number >= 0)
529         /* The value is/was defined, but we don't have it.  */
530         c = "<unknown>";
531       else
532         /* It is not meaningful to ask about the value.  */
533         c = "<undefined>";
534       if (c)
535         ui_out_field_string (uiout, "current", c);
536       ui_out_text (uiout, "\n");
537
538       do_cleanups (back_to2);
539     }
540
541   do_cleanups (back_to);
542 }
543
544 /* List all the trace state variables.  */
545
546 static void
547 tvariables_info (char *args, int from_tty)
548 {
549   tvariables_info_1 ();
550 }
551
552 /* Stash definitions of tsvs into the given file.  */
553
554 void
555 save_trace_state_variables (struct ui_file *fp)
556 {
557   struct trace_state_variable *tsv;
558   int ix;
559
560   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
561     {
562       fprintf_unfiltered (fp, "tvariable $%s", tsv->name);
563       if (tsv->initial_value)
564         fprintf_unfiltered (fp, " = %s", plongest (tsv->initial_value));
565       fprintf_unfiltered (fp, "\n");
566     }
567 }
568
569 /* ACTIONS functions: */
570
571 /* The three functions:
572    collect_pseudocommand, 
573    while_stepping_pseudocommand, and 
574    end_actions_pseudocommand
575    are placeholders for "commands" that are actually ONLY to be used
576    within a tracepoint action list.  If the actual function is ever called,
577    it means that somebody issued the "command" at the top level,
578    which is always an error.  */
579
580 static void
581 end_actions_pseudocommand (char *args, int from_tty)
582 {
583   error (_("This command cannot be used at the top level."));
584 }
585
586 static void
587 while_stepping_pseudocommand (char *args, int from_tty)
588 {
589   error (_("This command can only be used in a tracepoint actions list."));
590 }
591
592 static void
593 collect_pseudocommand (char *args, int from_tty)
594 {
595   error (_("This command can only be used in a tracepoint actions list."));
596 }
597
598 static void
599 teval_pseudocommand (char *args, int from_tty)
600 {
601   error (_("This command can only be used in a tracepoint actions list."));
602 }
603
604 /* Parse any collection options, such as /s for strings.  */
605
606 const char *
607 decode_agent_options (const char *exp, int *trace_string)
608 {
609   struct value_print_options opts;
610
611   *trace_string = 0;
612
613   if (*exp != '/')
614     return exp;
615
616   /* Call this to borrow the print elements default for collection
617      size.  */
618   get_user_print_options (&opts);
619
620   exp++;
621   if (*exp == 's')
622     {
623       if (target_supports_string_tracing ())
624         {
625           /* Allow an optional decimal number giving an explicit maximum
626              string length, defaulting it to the "print elements" value;
627              so "collect/s80 mystr" gets at most 80 bytes of string.  */
628           *trace_string = opts.print_max;
629           exp++;
630           if (*exp >= '0' && *exp <= '9')
631             *trace_string = atoi (exp);
632           while (*exp >= '0' && *exp <= '9')
633             exp++;
634         }
635       else
636         error (_("Target does not support \"/s\" option for string tracing."));
637     }
638   else
639     error (_("Undefined collection format \"%c\"."), *exp);
640
641   exp = skip_spaces_const (exp);
642
643   return exp;
644 }
645
646 /* Enter a list of actions for a tracepoint.  */
647 static void
648 trace_actions_command (char *args, int from_tty)
649 {
650   struct tracepoint *t;
651   struct command_line *l;
652
653   t = get_tracepoint_by_number (&args, NULL, 1);
654   if (t)
655     {
656       char *tmpbuf =
657         xstrprintf ("Enter actions for tracepoint %d, one per line.",
658                     t->base.number);
659       struct cleanup *cleanups = make_cleanup (xfree, tmpbuf);
660
661       l = read_command_lines (tmpbuf, from_tty, 1,
662                               check_tracepoint_command, t);
663       do_cleanups (cleanups);
664       breakpoint_set_commands (&t->base, l);
665     }
666   /* else just return */
667 }
668
669 /* Report the results of checking the agent expression, as errors or
670    internal errors.  */
671
672 static void
673 report_agent_reqs_errors (struct agent_expr *aexpr)
674 {
675   /* All of the "flaws" are serious bytecode generation issues that
676      should never occur.  */
677   if (aexpr->flaw != agent_flaw_none)
678     internal_error (__FILE__, __LINE__, _("expression is malformed"));
679
680   /* If analysis shows a stack underflow, GDB must have done something
681      badly wrong in its bytecode generation.  */
682   if (aexpr->min_height < 0)
683     internal_error (__FILE__, __LINE__,
684                     _("expression has min height < 0"));
685
686   /* Issue this error if the stack is predicted to get too deep.  The
687      limit is rather arbitrary; a better scheme might be for the
688      target to report how much stack it will have available.  The
689      depth roughly corresponds to parenthesization, so a limit of 20
690      amounts to 20 levels of expression nesting, which is actually
691      a pretty big hairy expression.  */
692   if (aexpr->max_height > 20)
693     error (_("Expression is too complicated."));
694 }
695
696 /* worker function */
697 void
698 validate_actionline (const char *line, struct breakpoint *b)
699 {
700   struct cmd_list_element *c;
701   struct expression *exp = NULL;
702   struct cleanup *old_chain = NULL;
703   const char *tmp_p;
704   const char *p;
705   struct bp_location *loc;
706   struct agent_expr *aexpr;
707   struct tracepoint *t = (struct tracepoint *) b;
708
709   /* If EOF is typed, *line is NULL.  */
710   if (line == NULL)
711     return;
712
713   p = skip_spaces_const (line);
714
715   /* Symbol lookup etc.  */
716   if (*p == '\0')       /* empty line: just prompt for another line.  */
717     return;
718
719   if (*p == '#')                /* comment line */
720     return;
721
722   c = lookup_cmd (&p, cmdlist, "", -1, 1);
723   if (c == 0)
724     error (_("`%s' is not a tracepoint action, or is ambiguous."), p);
725
726   if (cmd_cfunc_eq (c, collect_pseudocommand))
727     {
728       int trace_string = 0;
729
730       if (*p == '/')
731         p = decode_agent_options (p, &trace_string);
732
733       do
734         {                       /* Repeat over a comma-separated list.  */
735           QUIT;                 /* Allow user to bail out with ^C.  */
736           p = skip_spaces_const (p);
737
738           if (*p == '$')        /* Look for special pseudo-symbols.  */
739             {
740               if (0 == strncasecmp ("reg", p + 1, 3)
741                   || 0 == strncasecmp ("arg", p + 1, 3)
742                   || 0 == strncasecmp ("loc", p + 1, 3)
743                   || 0 == strncasecmp ("_ret", p + 1, 4)
744                   || 0 == strncasecmp ("_sdata", p + 1, 6))
745                 {
746                   p = strchr (p, ',');
747                   continue;
748                 }
749               /* else fall thru, treat p as an expression and parse it!  */
750             }
751           tmp_p = p;
752           for (loc = t->base.loc; loc; loc = loc->next)
753             {
754               p = tmp_p;
755               exp = parse_exp_1 (&p, loc->address,
756                                  block_for_pc (loc->address), 1);
757               old_chain = make_cleanup (free_current_contents, &exp);
758
759               if (exp->elts[0].opcode == OP_VAR_VALUE)
760                 {
761                   if (SYMBOL_CLASS (exp->elts[2].symbol) == LOC_CONST)
762                     {
763                       error (_("constant `%s' (value %s) "
764                                "will not be collected."),
765                              SYMBOL_PRINT_NAME (exp->elts[2].symbol),
766                              plongest (SYMBOL_VALUE (exp->elts[2].symbol)));
767                     }
768                   else if (SYMBOL_CLASS (exp->elts[2].symbol)
769                            == LOC_OPTIMIZED_OUT)
770                     {
771                       error (_("`%s' is optimized away "
772                                "and cannot be collected."),
773                              SYMBOL_PRINT_NAME (exp->elts[2].symbol));
774                     }
775                 }
776
777               /* We have something to collect, make sure that the expr to
778                  bytecode translator can handle it and that it's not too
779                  long.  */
780               aexpr = gen_trace_for_expr (loc->address, exp, trace_string);
781               make_cleanup_free_agent_expr (aexpr);
782
783               if (aexpr->len > MAX_AGENT_EXPR_LEN)
784                 error (_("Expression is too complicated."));
785
786               ax_reqs (aexpr);
787
788               report_agent_reqs_errors (aexpr);
789
790               do_cleanups (old_chain);
791             }
792         }
793       while (p && *p++ == ',');
794     }
795
796   else if (cmd_cfunc_eq (c, teval_pseudocommand))
797     {
798       do
799         {                       /* Repeat over a comma-separated list.  */
800           QUIT;                 /* Allow user to bail out with ^C.  */
801           p = skip_spaces_const (p);
802
803           tmp_p = p;
804           for (loc = t->base.loc; loc; loc = loc->next)
805             {
806               p = tmp_p;
807
808               /* Only expressions are allowed for this action.  */
809               exp = parse_exp_1 (&p, loc->address,
810                                  block_for_pc (loc->address), 1);
811               old_chain = make_cleanup (free_current_contents, &exp);
812
813               /* We have something to evaluate, make sure that the expr to
814                  bytecode translator can handle it and that it's not too
815                  long.  */
816               aexpr = gen_eval_for_expr (loc->address, exp);
817               make_cleanup_free_agent_expr (aexpr);
818
819               if (aexpr->len > MAX_AGENT_EXPR_LEN)
820                 error (_("Expression is too complicated."));
821
822               ax_reqs (aexpr);
823               report_agent_reqs_errors (aexpr);
824
825               do_cleanups (old_chain);
826             }
827         }
828       while (p && *p++ == ',');
829     }
830
831   else if (cmd_cfunc_eq (c, while_stepping_pseudocommand))
832     {
833       char *endp;
834
835       p = skip_spaces_const (p);
836       t->step_count = strtol (p, &endp, 0);
837       if (endp == p || t->step_count == 0)
838         error (_("while-stepping step count `%s' is malformed."), line);
839       p = endp;
840     }
841
842   else if (cmd_cfunc_eq (c, end_actions_pseudocommand))
843     ;
844
845   else
846     error (_("`%s' is not a supported tracepoint action."), line);
847 }
848
849 enum {
850   memrange_absolute = -1
851 };
852
853 struct memrange
854 {
855   int type;             /* memrange_absolute for absolute memory range,
856                            else basereg number.  */
857   bfd_signed_vma start;
858   bfd_signed_vma end;
859 };
860
861 struct collection_list
862   {
863     unsigned char regs_mask[32];        /* room for up to 256 regs */
864     long listsize;
865     long next_memrange;
866     struct memrange *list;
867     long aexpr_listsize;        /* size of array pointed to by expr_list elt */
868     long next_aexpr_elt;
869     struct agent_expr **aexpr_list;
870
871     /* True is the user requested a collection of "$_sdata", "static
872        tracepoint data".  */
873     int strace_data;
874   }
875 tracepoint_list, stepping_list;
876
877 /* MEMRANGE functions: */
878
879 static int memrange_cmp (const void *, const void *);
880
881 /* Compare memranges for qsort.  */
882 static int
883 memrange_cmp (const void *va, const void *vb)
884 {
885   const struct memrange *a = va, *b = vb;
886
887   if (a->type < b->type)
888     return -1;
889   if (a->type > b->type)
890     return 1;
891   if (a->type == memrange_absolute)
892     {
893       if ((bfd_vma) a->start < (bfd_vma) b->start)
894         return -1;
895       if ((bfd_vma) a->start > (bfd_vma) b->start)
896         return 1;
897     }
898   else
899     {
900       if (a->start < b->start)
901         return -1;
902       if (a->start > b->start)
903         return 1;
904     }
905   return 0;
906 }
907
908 /* Sort the memrange list using qsort, and merge adjacent memranges.  */
909 static void
910 memrange_sortmerge (struct collection_list *memranges)
911 {
912   int a, b;
913
914   qsort (memranges->list, memranges->next_memrange,
915          sizeof (struct memrange), memrange_cmp);
916   if (memranges->next_memrange > 0)
917     {
918       for (a = 0, b = 1; b < memranges->next_memrange; b++)
919         {
920           /* If memrange b overlaps or is adjacent to memrange a,
921              merge them.  */
922           if (memranges->list[a].type == memranges->list[b].type
923               && memranges->list[b].start <= memranges->list[a].end)
924             {
925               if (memranges->list[b].end > memranges->list[a].end)
926                 memranges->list[a].end = memranges->list[b].end;
927               continue;         /* next b, same a */
928             }
929           a++;                  /* next a */
930           if (a != b)
931             memcpy (&memranges->list[a], &memranges->list[b],
932                     sizeof (struct memrange));
933         }
934       memranges->next_memrange = a + 1;
935     }
936 }
937
938 /* Add a register to a collection list.  */
939 static void
940 add_register (struct collection_list *collection, unsigned int regno)
941 {
942   if (info_verbose)
943     printf_filtered ("collect register %d\n", regno);
944   if (regno >= (8 * sizeof (collection->regs_mask)))
945     error (_("Internal: register number %d too large for tracepoint"),
946            regno);
947   collection->regs_mask[regno / 8] |= 1 << (regno % 8);
948 }
949
950 /* Add a memrange to a collection list.  */
951 static void
952 add_memrange (struct collection_list *memranges, 
953               int type, bfd_signed_vma base,
954               unsigned long len)
955 {
956   if (info_verbose)
957     {
958       printf_filtered ("(%d,", type);
959       printf_vma (base);
960       printf_filtered (",%ld)\n", len);
961     }
962
963   /* type: memrange_absolute == memory, other n == basereg */
964   memranges->list[memranges->next_memrange].type = type;
965   /* base: addr if memory, offset if reg relative.  */
966   memranges->list[memranges->next_memrange].start = base;
967   /* len: we actually save end (base + len) for convenience */
968   memranges->list[memranges->next_memrange].end = base + len;
969   memranges->next_memrange++;
970   if (memranges->next_memrange >= memranges->listsize)
971     {
972       memranges->listsize *= 2;
973       memranges->list = xrealloc (memranges->list,
974                                   memranges->listsize);
975     }
976
977   if (type != memrange_absolute)    /* Better collect the base register!  */
978     add_register (memranges, type);
979 }
980
981 /* Add a symbol to a collection list.  */
982 static void
983 collect_symbol (struct collection_list *collect, 
984                 struct symbol *sym,
985                 struct gdbarch *gdbarch,
986                 long frame_regno, long frame_offset,
987                 CORE_ADDR scope,
988                 int trace_string)
989 {
990   unsigned long len;
991   unsigned int reg;
992   bfd_signed_vma offset;
993   int treat_as_expr = 0;
994
995   len = TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym)));
996   switch (SYMBOL_CLASS (sym))
997     {
998     default:
999       printf_filtered ("%s: don't know symbol class %d\n",
1000                        SYMBOL_PRINT_NAME (sym),
1001                        SYMBOL_CLASS (sym));
1002       break;
1003     case LOC_CONST:
1004       printf_filtered ("constant %s (value %s) will not be collected.\n",
1005                        SYMBOL_PRINT_NAME (sym), plongest (SYMBOL_VALUE (sym)));
1006       break;
1007     case LOC_STATIC:
1008       offset = SYMBOL_VALUE_ADDRESS (sym);
1009       if (info_verbose)
1010         {
1011           char tmp[40];
1012
1013           sprintf_vma (tmp, offset);
1014           printf_filtered ("LOC_STATIC %s: collect %ld bytes at %s.\n",
1015                            SYMBOL_PRINT_NAME (sym), len,
1016                            tmp /* address */);
1017         }
1018       /* A struct may be a C++ class with static fields, go to general
1019          expression handling.  */
1020       if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_STRUCT)
1021         treat_as_expr = 1;
1022       else
1023         add_memrange (collect, memrange_absolute, offset, len);
1024       break;
1025     case LOC_REGISTER:
1026       reg = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1027       if (info_verbose)
1028         printf_filtered ("LOC_REG[parm] %s: ", 
1029                          SYMBOL_PRINT_NAME (sym));
1030       add_register (collect, reg);
1031       /* Check for doubles stored in two registers.  */
1032       /* FIXME: how about larger types stored in 3 or more regs?  */
1033       if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_FLT &&
1034           len > register_size (gdbarch, reg))
1035         add_register (collect, reg + 1);
1036       break;
1037     case LOC_REF_ARG:
1038       printf_filtered ("Sorry, don't know how to do LOC_REF_ARG yet.\n");
1039       printf_filtered ("       (will not collect %s)\n",
1040                        SYMBOL_PRINT_NAME (sym));
1041       break;
1042     case LOC_ARG:
1043       reg = frame_regno;
1044       offset = frame_offset + SYMBOL_VALUE (sym);
1045       if (info_verbose)
1046         {
1047           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
1048                            SYMBOL_PRINT_NAME (sym), len);
1049           printf_vma (offset);
1050           printf_filtered (" from frame ptr reg %d\n", reg);
1051         }
1052       add_memrange (collect, reg, offset, len);
1053       break;
1054     case LOC_REGPARM_ADDR:
1055       reg = SYMBOL_VALUE (sym);
1056       offset = 0;
1057       if (info_verbose)
1058         {
1059           printf_filtered ("LOC_REGPARM_ADDR %s: Collect %ld bytes at offset ",
1060                            SYMBOL_PRINT_NAME (sym), len);
1061           printf_vma (offset);
1062           printf_filtered (" from reg %d\n", reg);
1063         }
1064       add_memrange (collect, reg, offset, len);
1065       break;
1066     case LOC_LOCAL:
1067       reg = frame_regno;
1068       offset = frame_offset + SYMBOL_VALUE (sym);
1069       if (info_verbose)
1070         {
1071           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
1072                            SYMBOL_PRINT_NAME (sym), len);
1073           printf_vma (offset);
1074           printf_filtered (" from frame ptr reg %d\n", reg);
1075         }
1076       add_memrange (collect, reg, offset, len);
1077       break;
1078
1079     case LOC_UNRESOLVED:
1080       treat_as_expr = 1;
1081       break;
1082
1083     case LOC_OPTIMIZED_OUT:
1084       printf_filtered ("%s has been optimized out of existence.\n",
1085                        SYMBOL_PRINT_NAME (sym));
1086       break;
1087
1088     case LOC_COMPUTED:
1089       treat_as_expr = 1;
1090       break;
1091     }
1092
1093   /* Expressions are the most general case.  */
1094   if (treat_as_expr)
1095     {
1096       struct agent_expr *aexpr;
1097       struct cleanup *old_chain1 = NULL;
1098
1099       aexpr = gen_trace_for_var (scope, gdbarch, sym, trace_string);
1100
1101       /* It can happen that the symbol is recorded as a computed
1102          location, but it's been optimized away and doesn't actually
1103          have a location expression.  */
1104       if (!aexpr)
1105         {
1106           printf_filtered ("%s has been optimized out of existence.\n",
1107                            SYMBOL_PRINT_NAME (sym));
1108           return;
1109         }
1110
1111       old_chain1 = make_cleanup_free_agent_expr (aexpr);
1112
1113       ax_reqs (aexpr);
1114
1115       report_agent_reqs_errors (aexpr);
1116
1117       discard_cleanups (old_chain1);
1118       add_aexpr (collect, aexpr);
1119
1120       /* Take care of the registers.  */
1121       if (aexpr->reg_mask_len > 0)
1122         {
1123           int ndx1, ndx2;
1124
1125           for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
1126             {
1127               QUIT;     /* Allow user to bail out with ^C.  */
1128               if (aexpr->reg_mask[ndx1] != 0)
1129                 {
1130                   /* Assume chars have 8 bits.  */
1131                   for (ndx2 = 0; ndx2 < 8; ndx2++)
1132                     if (aexpr->reg_mask[ndx1] & (1 << ndx2))
1133                       /* It's used -- record it.  */
1134                       add_register (collect, ndx1 * 8 + ndx2);
1135                 }
1136             }
1137         }
1138     }
1139 }
1140
1141 /* Data to be passed around in the calls to the locals and args
1142    iterators.  */
1143
1144 struct add_local_symbols_data
1145 {
1146   struct collection_list *collect;
1147   struct gdbarch *gdbarch;
1148   CORE_ADDR pc;
1149   long frame_regno;
1150   long frame_offset;
1151   int count;
1152   int trace_string;
1153 };
1154
1155 /* The callback for the locals and args iterators.  */
1156
1157 static void
1158 do_collect_symbol (const char *print_name,
1159                    struct symbol *sym,
1160                    void *cb_data)
1161 {
1162   struct add_local_symbols_data *p = cb_data;
1163
1164   collect_symbol (p->collect, sym, p->gdbarch, p->frame_regno,
1165                   p->frame_offset, p->pc, p->trace_string);
1166   p->count++;
1167 }
1168
1169 /* Add all locals (or args) symbols to collection list.  */
1170 static void
1171 add_local_symbols (struct collection_list *collect,
1172                    struct gdbarch *gdbarch, CORE_ADDR pc,
1173                    long frame_regno, long frame_offset, int type,
1174                    int trace_string)
1175 {
1176   struct block *block;
1177   struct add_local_symbols_data cb_data;
1178
1179   cb_data.collect = collect;
1180   cb_data.gdbarch = gdbarch;
1181   cb_data.pc = pc;
1182   cb_data.frame_regno = frame_regno;
1183   cb_data.frame_offset = frame_offset;
1184   cb_data.count = 0;
1185   cb_data.trace_string = trace_string;
1186
1187   if (type == 'L')
1188     {
1189       block = block_for_pc (pc);
1190       if (block == NULL)
1191         {
1192           warning (_("Can't collect locals; "
1193                      "no symbol table info available.\n"));
1194           return;
1195         }
1196
1197       iterate_over_block_local_vars (block, do_collect_symbol, &cb_data);
1198       if (cb_data.count == 0)
1199         warning (_("No locals found in scope."));
1200     }
1201   else
1202     {
1203       pc = get_pc_function_start (pc);
1204       block = block_for_pc (pc);
1205       if (block == NULL)
1206         {
1207           warning (_("Can't collect args; no symbol table info available."));
1208           return;
1209         }
1210
1211       iterate_over_block_arg_vars (block, do_collect_symbol, &cb_data);
1212       if (cb_data.count == 0)
1213         warning (_("No args found in scope."));
1214     }
1215 }
1216
1217 static void
1218 add_static_trace_data (struct collection_list *collection)
1219 {
1220   if (info_verbose)
1221     printf_filtered ("collect static trace data\n");
1222   collection->strace_data = 1;
1223 }
1224
1225 /* worker function */
1226 static void
1227 clear_collection_list (struct collection_list *list)
1228 {
1229   int ndx;
1230
1231   list->next_memrange = 0;
1232   for (ndx = 0; ndx < list->next_aexpr_elt; ndx++)
1233     {
1234       free_agent_expr (list->aexpr_list[ndx]);
1235       list->aexpr_list[ndx] = NULL;
1236     }
1237   list->next_aexpr_elt = 0;
1238   memset (list->regs_mask, 0, sizeof (list->regs_mask));
1239   list->strace_data = 0;
1240 }
1241
1242 /* Reduce a collection list to string form (for gdb protocol).  */
1243 static char **
1244 stringify_collection_list (struct collection_list *list)
1245 {
1246   char temp_buf[2048];
1247   char tmp2[40];
1248   int count;
1249   int ndx = 0;
1250   char *(*str_list)[];
1251   char *end;
1252   long i;
1253
1254   count = 1 + 1 + list->next_memrange + list->next_aexpr_elt + 1;
1255   str_list = (char *(*)[]) xmalloc (count * sizeof (char *));
1256
1257   if (list->strace_data)
1258     {
1259       if (info_verbose)
1260         printf_filtered ("\nCollecting static trace data\n");
1261       end = temp_buf;
1262       *end++ = 'L';
1263       (*str_list)[ndx] = savestring (temp_buf, end - temp_buf);
1264       ndx++;
1265     }
1266
1267   for (i = sizeof (list->regs_mask) - 1; i > 0; i--)
1268     if (list->regs_mask[i] != 0)    /* Skip leading zeroes in regs_mask.  */
1269       break;
1270   if (list->regs_mask[i] != 0)  /* Prepare to send regs_mask to the stub.  */
1271     {
1272       if (info_verbose)
1273         printf_filtered ("\nCollecting registers (mask): 0x");
1274       end = temp_buf;
1275       *end++ = 'R';
1276       for (; i >= 0; i--)
1277         {
1278           QUIT;                 /* Allow user to bail out with ^C.  */
1279           if (info_verbose)
1280             printf_filtered ("%02X", list->regs_mask[i]);
1281           sprintf (end, "%02X", list->regs_mask[i]);
1282           end += 2;
1283         }
1284       (*str_list)[ndx] = xstrdup (temp_buf);
1285       ndx++;
1286     }
1287   if (info_verbose)
1288     printf_filtered ("\n");
1289   if (list->next_memrange > 0 && info_verbose)
1290     printf_filtered ("Collecting memranges: \n");
1291   for (i = 0, count = 0, end = temp_buf; i < list->next_memrange; i++)
1292     {
1293       QUIT;                     /* Allow user to bail out with ^C.  */
1294       sprintf_vma (tmp2, list->list[i].start);
1295       if (info_verbose)
1296         {
1297           printf_filtered ("(%d, %s, %ld)\n", 
1298                            list->list[i].type, 
1299                            tmp2, 
1300                            (long) (list->list[i].end - list->list[i].start));
1301         }
1302       if (count + 27 > MAX_AGENT_EXPR_LEN)
1303         {
1304           (*str_list)[ndx] = savestring (temp_buf, count);
1305           ndx++;
1306           count = 0;
1307           end = temp_buf;
1308         }
1309
1310       {
1311         bfd_signed_vma length = list->list[i].end - list->list[i].start;
1312
1313         /* The "%X" conversion specifier expects an unsigned argument,
1314            so passing -1 (memrange_absolute) to it directly gives you
1315            "FFFFFFFF" (or more, depending on sizeof (unsigned)).
1316            Special-case it.  */
1317         if (list->list[i].type == memrange_absolute)
1318           sprintf (end, "M-1,%s,%lX", tmp2, (long) length);
1319         else
1320           sprintf (end, "M%X,%s,%lX", list->list[i].type, tmp2, (long) length);
1321       }
1322
1323       count += strlen (end);
1324       end = temp_buf + count;
1325     }
1326
1327   for (i = 0; i < list->next_aexpr_elt; i++)
1328     {
1329       QUIT;                     /* Allow user to bail out with ^C.  */
1330       if ((count + 10 + 2 * list->aexpr_list[i]->len) > MAX_AGENT_EXPR_LEN)
1331         {
1332           (*str_list)[ndx] = savestring (temp_buf, count);
1333           ndx++;
1334           count = 0;
1335           end = temp_buf;
1336         }
1337       sprintf (end, "X%08X,", list->aexpr_list[i]->len);
1338       end += 10;                /* 'X' + 8 hex digits + ',' */
1339       count += 10;
1340
1341       end = mem2hex (list->aexpr_list[i]->buf, 
1342                      end, list->aexpr_list[i]->len);
1343       count += 2 * list->aexpr_list[i]->len;
1344     }
1345
1346   if (count != 0)
1347     {
1348       (*str_list)[ndx] = savestring (temp_buf, count);
1349       ndx++;
1350       count = 0;
1351       end = temp_buf;
1352     }
1353   (*str_list)[ndx] = NULL;
1354
1355   if (ndx == 0)
1356     {
1357       xfree (str_list);
1358       return NULL;
1359     }
1360   else
1361     return *str_list;
1362 }
1363
1364
1365 static void
1366 encode_actions_1 (struct command_line *action,
1367                   struct breakpoint *t,
1368                   struct bp_location *tloc,
1369                   int frame_reg,
1370                   LONGEST frame_offset,
1371                   struct collection_list *collect,
1372                   struct collection_list *stepping_list)
1373 {
1374   const char *action_exp;
1375   struct expression *exp = NULL;
1376   int i;
1377   struct value *tempval;
1378   struct cmd_list_element *cmd;
1379   struct agent_expr *aexpr;
1380
1381   for (; action; action = action->next)
1382     {
1383       QUIT;                     /* Allow user to bail out with ^C.  */
1384       action_exp = action->line;
1385       action_exp = skip_spaces_const (action_exp);
1386
1387       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
1388       if (cmd == 0)
1389         error (_("Bad action list item: %s"), action_exp);
1390
1391       if (cmd_cfunc_eq (cmd, collect_pseudocommand))
1392         {
1393           int trace_string = 0;
1394
1395           if (*action_exp == '/')
1396             action_exp = decode_agent_options (action_exp, &trace_string);
1397
1398           do
1399             {                   /* Repeat over a comma-separated list.  */
1400               QUIT;             /* Allow user to bail out with ^C.  */
1401               action_exp = skip_spaces_const (action_exp);
1402
1403               if (0 == strncasecmp ("$reg", action_exp, 4))
1404                 {
1405                   for (i = 0; i < gdbarch_num_regs (tloc->gdbarch); i++)
1406                     add_register (collect, i);
1407                   action_exp = strchr (action_exp, ',');        /* more? */
1408                 }
1409               else if (0 == strncasecmp ("$arg", action_exp, 4))
1410                 {
1411                   add_local_symbols (collect,
1412                                      tloc->gdbarch,
1413                                      tloc->address,
1414                                      frame_reg,
1415                                      frame_offset,
1416                                      'A',
1417                                      trace_string);
1418                   action_exp = strchr (action_exp, ',');        /* more? */
1419                 }
1420               else if (0 == strncasecmp ("$loc", action_exp, 4))
1421                 {
1422                   add_local_symbols (collect,
1423                                      tloc->gdbarch,
1424                                      tloc->address,
1425                                      frame_reg,
1426                                      frame_offset,
1427                                      'L',
1428                                      trace_string);
1429                   action_exp = strchr (action_exp, ',');        /* more? */
1430                 }
1431               else if (0 == strncasecmp ("$_ret", action_exp, 5))
1432                 {
1433                   struct cleanup *old_chain1 = NULL;
1434
1435                   aexpr = gen_trace_for_return_address (tloc->address,
1436                                                         tloc->gdbarch,
1437                                                         trace_string);
1438
1439                   old_chain1 = make_cleanup_free_agent_expr (aexpr);
1440
1441                   ax_reqs (aexpr);
1442                   report_agent_reqs_errors (aexpr);
1443
1444                   discard_cleanups (old_chain1);
1445                   add_aexpr (collect, aexpr);
1446
1447                   /* take care of the registers */
1448                   if (aexpr->reg_mask_len > 0)
1449                     {
1450                       int ndx1, ndx2;
1451
1452                       for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
1453                         {
1454                           QUIT; /* allow user to bail out with ^C */
1455                           if (aexpr->reg_mask[ndx1] != 0)
1456                             {
1457                               /* assume chars have 8 bits */
1458                               for (ndx2 = 0; ndx2 < 8; ndx2++)
1459                                 if (aexpr->reg_mask[ndx1] & (1 << ndx2))
1460                                   /* it's used -- record it */
1461                                   add_register (collect, 
1462                                                 ndx1 * 8 + ndx2);
1463                             }
1464                         }
1465                     }
1466
1467                   action_exp = strchr (action_exp, ',');        /* more? */
1468                 }
1469               else if (0 == strncasecmp ("$_sdata", action_exp, 7))
1470                 {
1471                   add_static_trace_data (collect);
1472                   action_exp = strchr (action_exp, ',');        /* more? */
1473                 }
1474               else
1475                 {
1476                   unsigned long addr;
1477                   struct cleanup *old_chain = NULL;
1478                   struct cleanup *old_chain1 = NULL;
1479
1480                   exp = parse_exp_1 (&action_exp, tloc->address,
1481                                      block_for_pc (tloc->address), 1);
1482                   old_chain = make_cleanup (free_current_contents, &exp);
1483
1484                   switch (exp->elts[0].opcode)
1485                     {
1486                     case OP_REGISTER:
1487                       {
1488                         const char *name = &exp->elts[2].string;
1489
1490                         i = user_reg_map_name_to_regnum (tloc->gdbarch,
1491                                                          name, strlen (name));
1492                         if (i == -1)
1493                           internal_error (__FILE__, __LINE__,
1494                                           _("Register $%s not available"),
1495                                           name);
1496                         if (info_verbose)
1497                           printf_filtered ("OP_REGISTER: ");
1498                         add_register (collect, i);
1499                         break;
1500                       }
1501
1502                     case UNOP_MEMVAL:
1503                       /* Safe because we know it's a simple expression.  */
1504                       tempval = evaluate_expression (exp);
1505                       addr = value_address (tempval);
1506                       /* Initialize the TYPE_LENGTH if it is a typedef.  */
1507                       check_typedef (exp->elts[1].type);
1508                       add_memrange (collect, memrange_absolute, addr,
1509                                     TYPE_LENGTH (exp->elts[1].type));
1510                       break;
1511
1512                     case OP_VAR_VALUE:
1513                       collect_symbol (collect,
1514                                       exp->elts[2].symbol,
1515                                       tloc->gdbarch,
1516                                       frame_reg,
1517                                       frame_offset,
1518                                       tloc->address,
1519                                       trace_string);
1520                       break;
1521
1522                     default:    /* Full-fledged expression.  */
1523                       aexpr = gen_trace_for_expr (tloc->address, exp,
1524                                                   trace_string);
1525
1526                       old_chain1 = make_cleanup_free_agent_expr (aexpr);
1527
1528                       ax_reqs (aexpr);
1529
1530                       report_agent_reqs_errors (aexpr);
1531
1532                       discard_cleanups (old_chain1);
1533                       add_aexpr (collect, aexpr);
1534
1535                       /* Take care of the registers.  */
1536                       if (aexpr->reg_mask_len > 0)
1537                         {
1538                           int ndx1;
1539                           int ndx2;
1540
1541                           for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
1542                             {
1543                               QUIT;     /* Allow user to bail out with ^C.  */
1544                               if (aexpr->reg_mask[ndx1] != 0)
1545                                 {
1546                                   /* Assume chars have 8 bits.  */
1547                                   for (ndx2 = 0; ndx2 < 8; ndx2++)
1548                                     if (aexpr->reg_mask[ndx1] & (1 << ndx2))
1549                                       /* It's used -- record it.  */
1550                                       add_register (collect, 
1551                                                     ndx1 * 8 + ndx2);
1552                                 }
1553                             }
1554                         }
1555                       break;
1556                     }           /* switch */
1557                   do_cleanups (old_chain);
1558                 }               /* do */
1559             }
1560           while (action_exp && *action_exp++ == ',');
1561         }                       /* if */
1562       else if (cmd_cfunc_eq (cmd, teval_pseudocommand))
1563         {
1564           do
1565             {                   /* Repeat over a comma-separated list.  */
1566               QUIT;             /* Allow user to bail out with ^C.  */
1567               action_exp = skip_spaces_const (action_exp);
1568
1569                 {
1570                   struct cleanup *old_chain = NULL;
1571                   struct cleanup *old_chain1 = NULL;
1572
1573                   exp = parse_exp_1 (&action_exp, tloc->address,
1574                                      block_for_pc (tloc->address), 1);
1575                   old_chain = make_cleanup (free_current_contents, &exp);
1576
1577                   aexpr = gen_eval_for_expr (tloc->address, exp);
1578                   old_chain1 = make_cleanup_free_agent_expr (aexpr);
1579
1580                   ax_reqs (aexpr);
1581                   report_agent_reqs_errors (aexpr);
1582
1583                   discard_cleanups (old_chain1);
1584                   /* Even though we're not officially collecting, add
1585                      to the collect list anyway.  */
1586                   add_aexpr (collect, aexpr);
1587
1588                   do_cleanups (old_chain);
1589                 }               /* do */
1590             }
1591           while (action_exp && *action_exp++ == ',');
1592         }                       /* if */
1593       else if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
1594         {
1595           /* We check against nested while-stepping when setting
1596              breakpoint action, so no way to run into nested
1597              here.  */
1598           gdb_assert (stepping_list);
1599
1600           encode_actions_1 (action->body_list[0], t, tloc, frame_reg,
1601                             frame_offset, stepping_list, NULL);
1602         }
1603       else
1604         error (_("Invalid tracepoint command '%s'"), action->line);
1605     }                           /* for */
1606 }
1607
1608 /* Render all actions into gdb protocol.  */
1609
1610 void
1611 encode_actions (struct breakpoint *t, struct bp_location *tloc,
1612                 char ***tdp_actions, char ***stepping_actions)
1613 {
1614   char *default_collect_line = NULL;
1615   struct command_line *actions;
1616   struct command_line *default_collect_action = NULL;
1617   int frame_reg;
1618   LONGEST frame_offset;
1619   struct cleanup *back_to;
1620
1621   back_to = make_cleanup (null_cleanup, NULL);
1622
1623   clear_collection_list (&tracepoint_list);
1624   clear_collection_list (&stepping_list);
1625
1626   *tdp_actions = NULL;
1627   *stepping_actions = NULL;
1628
1629   gdbarch_virtual_frame_pointer (tloc->gdbarch,
1630                                  tloc->address, &frame_reg, &frame_offset);
1631
1632   actions = breakpoint_commands (t);
1633
1634   /* If there are default expressions to collect, make up a collect
1635      action and prepend to the action list to encode.  Note that since
1636      validation is per-tracepoint (local var "xyz" might be valid for
1637      one tracepoint and not another, etc), we make up the action on
1638      the fly, and don't cache it.  */
1639   if (*default_collect)
1640     {
1641       default_collect_line =  xstrprintf ("collect %s", default_collect);
1642       make_cleanup (xfree, default_collect_line);
1643
1644       validate_actionline (default_collect_line, t);
1645
1646       default_collect_action = xmalloc (sizeof (struct command_line));
1647       make_cleanup (xfree, default_collect_action);
1648       default_collect_action->next = actions;
1649       default_collect_action->line = default_collect_line;
1650       actions = default_collect_action;
1651     }
1652   encode_actions_1 (actions, t, tloc, frame_reg, frame_offset,
1653                     &tracepoint_list, &stepping_list);
1654
1655   memrange_sortmerge (&tracepoint_list);
1656   memrange_sortmerge (&stepping_list);
1657
1658   *tdp_actions = stringify_collection_list (&tracepoint_list);
1659   *stepping_actions = stringify_collection_list (&stepping_list);
1660
1661   do_cleanups (back_to);
1662 }
1663
1664 static void
1665 add_aexpr (struct collection_list *collect, struct agent_expr *aexpr)
1666 {
1667   if (collect->next_aexpr_elt >= collect->aexpr_listsize)
1668     {
1669       collect->aexpr_list =
1670         xrealloc (collect->aexpr_list,
1671                   2 * collect->aexpr_listsize * sizeof (struct agent_expr *));
1672       collect->aexpr_listsize *= 2;
1673     }
1674   collect->aexpr_list[collect->next_aexpr_elt] = aexpr;
1675   collect->next_aexpr_elt++;
1676 }
1677
1678 static void
1679 process_tracepoint_on_disconnect (void)
1680 {
1681   VEC(breakpoint_p) *tp_vec = NULL;
1682   int ix;
1683   struct breakpoint *b;
1684   int has_pending_p = 0;
1685
1686   /* Check whether we still have pending tracepoint.  If we have, warn the
1687      user that pending tracepoint will no longer work.  */
1688   tp_vec = all_tracepoints ();
1689   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
1690     {
1691       if (b->loc == NULL)
1692         {
1693           has_pending_p = 1;
1694           break;
1695         }
1696       else
1697         {
1698           struct bp_location *loc1;
1699
1700           for (loc1 = b->loc; loc1; loc1 = loc1->next)
1701             {
1702               if (loc1->shlib_disabled)
1703                 {
1704                   has_pending_p = 1;
1705                   break;
1706                 }
1707             }
1708
1709           if (has_pending_p)
1710             break;
1711         }
1712     }
1713   VEC_free (breakpoint_p, tp_vec);
1714
1715   if (has_pending_p)
1716     warning (_("Pending tracepoints will not be resolved while"
1717                " GDB is disconnected\n"));
1718 }
1719
1720
1721 void
1722 start_tracing (char *notes)
1723 {
1724   VEC(breakpoint_p) *tp_vec = NULL;
1725   int ix;
1726   struct breakpoint *b;
1727   struct trace_state_variable *tsv;
1728   int any_enabled = 0, num_to_download = 0;
1729   int ret;
1730
1731   tp_vec = all_tracepoints ();
1732
1733   /* No point in tracing without any tracepoints...  */
1734   if (VEC_length (breakpoint_p, tp_vec) == 0)
1735     {
1736       VEC_free (breakpoint_p, tp_vec);
1737       error (_("No tracepoints defined, not starting trace"));
1738     }
1739
1740   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
1741     {
1742       struct tracepoint *t = (struct tracepoint *) b;
1743       struct bp_location *loc;
1744
1745       if (b->enable_state == bp_enabled)
1746         any_enabled = 1;
1747
1748       if ((b->type == bp_fast_tracepoint
1749            ? may_insert_fast_tracepoints
1750            : may_insert_tracepoints))
1751         ++num_to_download;
1752       else
1753         warning (_("May not insert %stracepoints, skipping tracepoint %d"),
1754                  (b->type == bp_fast_tracepoint ? "fast " : ""), b->number);
1755     }
1756
1757   if (!any_enabled)
1758     {
1759       if (target_supports_enable_disable_tracepoint ())
1760         warning (_("No tracepoints enabled"));
1761       else
1762         {
1763           /* No point in tracing with only disabled tracepoints that
1764              cannot be re-enabled.  */
1765           VEC_free (breakpoint_p, tp_vec);
1766           error (_("No tracepoints enabled, not starting trace"));
1767         }
1768     }
1769
1770   if (num_to_download <= 0)
1771     {
1772       VEC_free (breakpoint_p, tp_vec);
1773       error (_("No tracepoints that may be downloaded, not starting trace"));
1774     }
1775
1776   target_trace_init ();
1777
1778   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
1779     {
1780       struct tracepoint *t = (struct tracepoint *) b;
1781       struct bp_location *loc;
1782       int bp_location_downloaded = 0;
1783
1784       /* Clear `inserted' flag.  */
1785       for (loc = b->loc; loc; loc = loc->next)
1786         loc->inserted = 0;
1787
1788       if ((b->type == bp_fast_tracepoint
1789            ? !may_insert_fast_tracepoints
1790            : !may_insert_tracepoints))
1791         continue;
1792
1793       t->number_on_target = 0;
1794
1795       for (loc = b->loc; loc; loc = loc->next)
1796         {
1797           /* Since tracepoint locations are never duplicated, `inserted'
1798              flag should be zero.  */
1799           gdb_assert (!loc->inserted);
1800
1801           target_download_tracepoint (loc);
1802
1803           loc->inserted = 1;
1804           bp_location_downloaded = 1;
1805         }
1806
1807       t->number_on_target = b->number;
1808
1809       for (loc = b->loc; loc; loc = loc->next)
1810         if (loc->probe != NULL)
1811           loc->probe->pops->set_semaphore (loc->probe, loc->gdbarch);
1812
1813       if (bp_location_downloaded)
1814         observer_notify_breakpoint_modified (b);
1815     }
1816   VEC_free (breakpoint_p, tp_vec);
1817
1818   /* Send down all the trace state variables too.  */
1819   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
1820     {
1821       target_download_trace_state_variable (tsv);
1822     }
1823   
1824   /* Tell target to treat text-like sections as transparent.  */
1825   target_trace_set_readonly_regions ();
1826   /* Set some mode flags.  */
1827   target_set_disconnected_tracing (disconnected_tracing);
1828   target_set_circular_trace_buffer (circular_trace_buffer);
1829   target_set_trace_buffer_size (trace_buffer_size);
1830
1831   if (!notes)
1832     notes = trace_notes;
1833   ret = target_set_trace_notes (trace_user, notes, NULL);
1834
1835   if (!ret && (trace_user || notes))
1836     warning (_("Target does not support trace user/notes, info ignored"));
1837
1838   /* Now insert traps and begin collecting data.  */
1839   target_trace_start ();
1840
1841   /* Reset our local state.  */
1842   set_traceframe_num (-1);
1843   set_tracepoint_num (-1);
1844   set_traceframe_context (NULL);
1845   current_trace_status()->running = 1;
1846   clear_traceframe_info ();
1847 }
1848
1849 /* The tstart command requests the target to start a new trace run.
1850    The command passes any arguments it has to the target verbatim, as
1851    an optional "trace note".  This is useful as for instance a warning
1852    to other users if the trace runs disconnected, and you don't want
1853    anybody else messing with the target.  */
1854
1855 static void
1856 trace_start_command (char *args, int from_tty)
1857 {
1858   dont_repeat ();       /* Like "run", dangerous to repeat accidentally.  */
1859
1860   if (current_trace_status ()->running)
1861     {
1862       if (from_tty
1863           && !query (_("A trace is running already.  Start a new run? ")))
1864         error (_("New trace run not started."));
1865     }
1866
1867   start_tracing (args);
1868 }
1869
1870 /* The tstop command stops the tracing run.  The command passes any
1871    supplied arguments to the target verbatim as a "stop note"; if the
1872    target supports trace notes, then it will be reported back as part
1873    of the trace run's status.  */
1874
1875 static void
1876 trace_stop_command (char *args, int from_tty)
1877 {
1878   if (!current_trace_status ()->running)
1879     error (_("Trace is not running."));
1880
1881   stop_tracing (args);
1882 }
1883
1884 void
1885 stop_tracing (char *note)
1886 {
1887   int ret;
1888   VEC(breakpoint_p) *tp_vec = NULL;
1889   int ix;
1890   struct breakpoint *t;
1891
1892   target_trace_stop ();
1893
1894   tp_vec = all_tracepoints ();
1895   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, t); ix++)
1896     {
1897       struct bp_location *loc;
1898
1899       if ((t->type == bp_fast_tracepoint
1900            ? !may_insert_fast_tracepoints
1901            : !may_insert_tracepoints))
1902         continue;
1903
1904       for (loc = t->loc; loc; loc = loc->next)
1905         {
1906           /* GDB can be totally absent in some disconnected trace scenarios,
1907              but we don't really care if this semaphore goes out of sync.
1908              That's why we are decrementing it here, but not taking care
1909              in other places.  */
1910           if (loc->probe != NULL)
1911             loc->probe->pops->clear_semaphore (loc->probe, loc->gdbarch);
1912         }
1913     }
1914
1915   VEC_free (breakpoint_p, tp_vec);
1916
1917   if (!note)
1918     note = trace_stop_notes;
1919   ret = target_set_trace_notes (NULL, NULL, note);
1920
1921   if (!ret && note)
1922     warning (_("Target does not support trace notes, note ignored"));
1923
1924   /* Should change in response to reply?  */
1925   current_trace_status ()->running = 0;
1926 }
1927
1928 /* tstatus command */
1929 static void
1930 trace_status_command (char *args, int from_tty)
1931 {
1932   struct trace_status *ts = current_trace_status ();
1933   int status, ix;
1934   VEC(breakpoint_p) *tp_vec = NULL;
1935   struct breakpoint *t;
1936   
1937   status = target_get_trace_status (ts);
1938
1939   if (status == -1)
1940     {
1941       if (ts->filename != NULL)
1942         printf_filtered (_("Using a trace file.\n"));
1943       else
1944         {
1945           printf_filtered (_("Trace can not be run on this target.\n"));
1946           return;
1947         }
1948     }
1949
1950   if (!ts->running_known)
1951     {
1952       printf_filtered (_("Run/stop status is unknown.\n"));
1953     }
1954   else if (ts->running)
1955     {
1956       printf_filtered (_("Trace is running on the target.\n"));
1957     }
1958   else
1959     {
1960       switch (ts->stop_reason)
1961         {
1962         case trace_never_run:
1963           printf_filtered (_("No trace has been run on the target.\n"));
1964           break;
1965         case tstop_command:
1966           if (ts->stop_desc)
1967             printf_filtered (_("Trace stopped by a tstop command (%s).\n"),
1968                              ts->stop_desc);
1969           else
1970             printf_filtered (_("Trace stopped by a tstop command.\n"));
1971           break;
1972         case trace_buffer_full:
1973           printf_filtered (_("Trace stopped because the buffer was full.\n"));
1974           break;
1975         case trace_disconnected:
1976           printf_filtered (_("Trace stopped because of disconnection.\n"));
1977           break;
1978         case tracepoint_passcount:
1979           printf_filtered (_("Trace stopped by tracepoint %d.\n"),
1980                            ts->stopping_tracepoint);
1981           break;
1982         case tracepoint_error:
1983           if (ts->stopping_tracepoint)
1984             printf_filtered (_("Trace stopped by an "
1985                                "error (%s, tracepoint %d).\n"),
1986                              ts->stop_desc, ts->stopping_tracepoint);
1987           else
1988             printf_filtered (_("Trace stopped by an error (%s).\n"),
1989                              ts->stop_desc);
1990           break;
1991         case trace_stop_reason_unknown:
1992           printf_filtered (_("Trace stopped for an unknown reason.\n"));
1993           break;
1994         default:
1995           printf_filtered (_("Trace stopped for some other reason (%d).\n"),
1996                            ts->stop_reason);
1997           break;
1998         }
1999     }
2000
2001   if (ts->traceframes_created >= 0
2002       && ts->traceframe_count != ts->traceframes_created)
2003     {
2004       printf_filtered (_("Buffer contains %d trace "
2005                          "frames (of %d created total).\n"),
2006                        ts->traceframe_count, ts->traceframes_created);
2007     }
2008   else if (ts->traceframe_count >= 0)
2009     {
2010       printf_filtered (_("Collected %d trace frames.\n"),
2011                        ts->traceframe_count);
2012     }
2013
2014   if (ts->buffer_free >= 0)
2015     {
2016       if (ts->buffer_size >= 0)
2017         {
2018           printf_filtered (_("Trace buffer has %d bytes of %d bytes free"),
2019                            ts->buffer_free, ts->buffer_size);
2020           if (ts->buffer_size > 0)
2021             printf_filtered (_(" (%d%% full)"),
2022                              ((int) ((((long long) (ts->buffer_size
2023                                                     - ts->buffer_free)) * 100)
2024                                      / ts->buffer_size)));
2025           printf_filtered (_(".\n"));
2026         }
2027       else
2028         printf_filtered (_("Trace buffer has %d bytes free.\n"),
2029                          ts->buffer_free);
2030     }
2031
2032   if (ts->disconnected_tracing)
2033     printf_filtered (_("Trace will continue if GDB disconnects.\n"));
2034   else
2035     printf_filtered (_("Trace will stop if GDB disconnects.\n"));
2036
2037   if (ts->circular_buffer)
2038     printf_filtered (_("Trace buffer is circular.\n"));
2039
2040   if (ts->user_name && strlen (ts->user_name) > 0)
2041     printf_filtered (_("Trace user is %s.\n"), ts->user_name);
2042
2043   if (ts->notes && strlen (ts->notes) > 0)
2044     printf_filtered (_("Trace notes: %s.\n"), ts->notes);
2045
2046   /* Now report on what we're doing with tfind.  */
2047   if (traceframe_number >= 0)
2048     printf_filtered (_("Looking at trace frame %d, tracepoint %d.\n"),
2049                      traceframe_number, tracepoint_number);
2050   else
2051     printf_filtered (_("Not looking at any trace frame.\n"));
2052
2053   /* Report start/stop times if supplied.  */
2054   if (ts->start_time)
2055     {
2056       if (ts->stop_time)
2057         {
2058           LONGEST run_time = ts->stop_time - ts->start_time;
2059
2060           /* Reporting a run time is more readable than two long numbers.  */
2061           printf_filtered (_("Trace started at %ld.%06ld secs, stopped %ld.%06ld secs later.\n"),
2062                            (long int) ts->start_time / 1000000,
2063                            (long int) ts->start_time % 1000000,
2064                            (long int) run_time / 1000000,
2065                            (long int) run_time % 1000000);
2066         }
2067       else
2068         printf_filtered (_("Trace started at %ld.%06ld secs.\n"),
2069                          (long int) ts->start_time / 1000000,
2070                          (long int) ts->start_time % 1000000);
2071     }
2072   else if (ts->stop_time)
2073     printf_filtered (_("Trace stopped at %ld.%06ld secs.\n"),
2074                      (long int) ts->stop_time / 1000000,
2075                      (long int) ts->stop_time % 1000000);
2076
2077   /* Now report any per-tracepoint status available.  */
2078   tp_vec = all_tracepoints ();
2079
2080   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, t); ix++)
2081     target_get_tracepoint_status (t, NULL);
2082
2083   VEC_free (breakpoint_p, tp_vec);
2084 }
2085
2086 /* Report the trace status to uiout, in a way suitable for MI, and not
2087    suitable for CLI.  If ON_STOP is true, suppress a few fields that
2088    are not meaningful in the -trace-stop response.
2089
2090    The implementation is essentially parallel to trace_status_command, but
2091    merging them will result in unreadable code.  */
2092 void
2093 trace_status_mi (int on_stop)
2094 {
2095   struct ui_out *uiout = current_uiout;
2096   struct trace_status *ts = current_trace_status ();
2097   int status;
2098
2099   status = target_get_trace_status (ts);
2100
2101   if (status == -1 && ts->filename == NULL)
2102     {
2103       ui_out_field_string (uiout, "supported", "0");
2104       return;
2105     }
2106
2107   if (ts->filename != NULL)
2108     ui_out_field_string (uiout, "supported", "file");
2109   else if (!on_stop)
2110     ui_out_field_string (uiout, "supported", "1");
2111
2112   if (ts->filename != NULL)
2113     ui_out_field_string (uiout, "trace-file", ts->filename);
2114
2115   gdb_assert (ts->running_known);
2116
2117   if (ts->running)
2118     {
2119       ui_out_field_string (uiout, "running", "1");
2120
2121       /* Unlike CLI, do not show the state of 'disconnected-tracing' variable.
2122          Given that the frontend gets the status either on -trace-stop, or from
2123          -trace-status after re-connection, it does not seem like this
2124          information is necessary for anything.  It is not necessary for either
2125          figuring the vital state of the target nor for navigation of trace
2126          frames.  If the frontend wants to show the current state is some
2127          configure dialog, it can request the value when such dialog is
2128          invoked by the user.  */
2129     }
2130   else
2131     {
2132       char *stop_reason = NULL;
2133       int stopping_tracepoint = -1;
2134
2135       if (!on_stop)
2136         ui_out_field_string (uiout, "running", "0");
2137
2138       if (ts->stop_reason != trace_stop_reason_unknown)
2139         {
2140           switch (ts->stop_reason)
2141             {
2142             case tstop_command:
2143               stop_reason = "request";
2144               break;
2145             case trace_buffer_full:
2146               stop_reason = "overflow";
2147               break;
2148             case trace_disconnected:
2149               stop_reason = "disconnection";
2150               break;
2151             case tracepoint_passcount:
2152               stop_reason = "passcount";
2153               stopping_tracepoint = ts->stopping_tracepoint;
2154               break;
2155             case tracepoint_error:
2156               stop_reason = "error";
2157               stopping_tracepoint = ts->stopping_tracepoint;
2158               break;
2159             }
2160           
2161           if (stop_reason)
2162             {
2163               ui_out_field_string (uiout, "stop-reason", stop_reason);
2164               if (stopping_tracepoint != -1)
2165                 ui_out_field_int (uiout, "stopping-tracepoint",
2166                                   stopping_tracepoint);
2167               if (ts->stop_reason == tracepoint_error)
2168                 ui_out_field_string (uiout, "error-description",
2169                                      ts->stop_desc);
2170             }
2171         }
2172     }
2173
2174   if (ts->traceframe_count != -1)
2175     ui_out_field_int (uiout, "frames", ts->traceframe_count);
2176   if (ts->traceframes_created != -1)
2177     ui_out_field_int (uiout, "frames-created", ts->traceframes_created);
2178   if (ts->buffer_size != -1)
2179     ui_out_field_int (uiout, "buffer-size", ts->buffer_size);
2180   if (ts->buffer_free != -1)
2181     ui_out_field_int (uiout, "buffer-free", ts->buffer_free);
2182
2183   ui_out_field_int (uiout, "disconnected",  ts->disconnected_tracing);
2184   ui_out_field_int (uiout, "circular",  ts->circular_buffer);
2185
2186   ui_out_field_string (uiout, "user-name", ts->user_name);
2187   ui_out_field_string (uiout, "notes", ts->notes);
2188
2189   {
2190     char buf[100];
2191
2192     xsnprintf (buf, sizeof buf, "%ld.%06ld",
2193                (long int) ts->start_time / 1000000,
2194                (long int) ts->start_time % 1000000);
2195     ui_out_field_string (uiout, "start-time", buf);
2196     xsnprintf (buf, sizeof buf, "%ld.%06ld",
2197                (long int) ts->stop_time / 1000000,
2198                (long int) ts->stop_time % 1000000);
2199     ui_out_field_string (uiout, "stop-time", buf);
2200   }
2201 }
2202
2203 /* Check if a trace run is ongoing.  If so, and FROM_TTY, query the
2204    user if she really wants to detach.  */
2205
2206 void
2207 query_if_trace_running (int from_tty)
2208 {
2209   if (!from_tty)
2210     return;
2211
2212   /* It can happen that the target that was tracing went away on its
2213      own, and we didn't notice.  Get a status update, and if the
2214      current target doesn't even do tracing, then assume it's not
2215      running anymore.  */
2216   if (target_get_trace_status (current_trace_status ()) < 0)
2217     current_trace_status ()->running = 0;
2218
2219   /* If running interactively, give the user the option to cancel and
2220      then decide what to do differently with the run.  Scripts are
2221      just going to disconnect and let the target deal with it,
2222      according to how it's been instructed previously via
2223      disconnected-tracing.  */
2224   if (current_trace_status ()->running)
2225     {
2226       process_tracepoint_on_disconnect ();
2227
2228       if (current_trace_status ()->disconnected_tracing)
2229         {
2230           if (!query (_("Trace is running and will "
2231                         "continue after detach; detach anyway? ")))
2232             error (_("Not confirmed."));
2233         }
2234       else
2235         {
2236           if (!query (_("Trace is running but will "
2237                         "stop on detach; detach anyway? ")))
2238             error (_("Not confirmed."));
2239         }
2240     }
2241 }
2242
2243 /* This function handles the details of what to do about an ongoing
2244    tracing run if the user has asked to detach or otherwise disconnect
2245    from the target.  */
2246
2247 void
2248 disconnect_tracing (void)
2249 {
2250   /* Also we want to be out of tfind mode, otherwise things can get
2251      confusing upon reconnection.  Just use these calls instead of
2252      full tfind_1 behavior because we're in the middle of detaching,
2253      and there's no point to updating current stack frame etc.  */
2254   set_current_traceframe (-1);
2255   set_tracepoint_num (-1);
2256   set_traceframe_context (NULL);
2257 }
2258
2259 /* Worker function for the various flavors of the tfind command.  */
2260 void
2261 tfind_1 (enum trace_find_type type, int num,
2262          CORE_ADDR addr1, CORE_ADDR addr2,
2263          int from_tty)
2264 {
2265   int target_frameno = -1, target_tracept = -1;
2266   struct frame_id old_frame_id = null_frame_id;
2267   struct tracepoint *tp;
2268   struct ui_out *uiout = current_uiout;
2269
2270   /* Only try to get the current stack frame if we have a chance of
2271      succeeding.  In particular, if we're trying to get a first trace
2272      frame while all threads are running, it's not going to succeed,
2273      so leave it with a default value and let the frame comparison
2274      below (correctly) decide to print out the source location of the
2275      trace frame.  */
2276   if (!(type == tfind_number && num == -1)
2277       && (has_stack_frames () || traceframe_number >= 0))
2278     old_frame_id = get_frame_id (get_current_frame ());
2279
2280   target_frameno = target_trace_find (type, num, addr1, addr2,
2281                                       &target_tracept);
2282   
2283   if (type == tfind_number
2284       && num == -1
2285       && target_frameno == -1)
2286     {
2287       /* We told the target to get out of tfind mode, and it did.  */
2288     }
2289   else if (target_frameno == -1)
2290     {
2291       /* A request for a non-existent trace frame has failed.
2292          Our response will be different, depending on FROM_TTY:
2293
2294          If FROM_TTY is true, meaning that this command was 
2295          typed interactively by the user, then give an error
2296          and DO NOT change the state of traceframe_number etc.
2297
2298          However if FROM_TTY is false, meaning that we're either
2299          in a script, a loop, or a user-defined command, then 
2300          DON'T give an error, but DO change the state of
2301          traceframe_number etc. to invalid.
2302
2303          The rationalle is that if you typed the command, you
2304          might just have committed a typo or something, and you'd
2305          like to NOT lose your current debugging state.  However
2306          if you're in a user-defined command or especially in a
2307          loop, then you need a way to detect that the command
2308          failed WITHOUT aborting.  This allows you to write
2309          scripts that search thru the trace buffer until the end,
2310          and then continue on to do something else.  */
2311   
2312       if (from_tty)
2313         error (_("Target failed to find requested trace frame."));
2314       else
2315         {
2316           if (info_verbose)
2317             printf_filtered ("End of trace buffer.\n");
2318 #if 0 /* dubious now?  */
2319           /* The following will not recurse, since it's
2320              special-cased.  */
2321           trace_find_command ("-1", from_tty);
2322 #endif
2323         }
2324     }
2325   
2326   tp = get_tracepoint_by_number_on_target (target_tracept);
2327
2328   reinit_frame_cache ();
2329   target_dcache_invalidate ();
2330
2331   set_tracepoint_num (tp ? tp->base.number : target_tracept);
2332
2333   if (target_frameno != get_traceframe_number ())
2334     observer_notify_traceframe_changed (target_frameno, tracepoint_number);
2335
2336   set_current_traceframe (target_frameno);
2337
2338   if (target_frameno == -1)
2339     set_traceframe_context (NULL);
2340   else
2341     set_traceframe_context (get_current_frame ());
2342
2343   if (traceframe_number >= 0)
2344     {
2345       /* Use different branches for MI and CLI to make CLI messages
2346          i18n-eable.  */
2347       if (ui_out_is_mi_like_p (uiout))
2348         {
2349           ui_out_field_string (uiout, "found", "1");
2350           ui_out_field_int (uiout, "tracepoint", tracepoint_number);
2351           ui_out_field_int (uiout, "traceframe", traceframe_number);
2352         }
2353       else
2354         {
2355           printf_unfiltered (_("Found trace frame %d, tracepoint %d\n"),
2356                              traceframe_number, tracepoint_number);
2357         }
2358     }
2359   else
2360     {
2361       if (ui_out_is_mi_like_p (uiout))
2362         ui_out_field_string (uiout, "found", "0");
2363       else if (type == tfind_number && num == -1)
2364         printf_unfiltered (_("No longer looking at any trace frame\n"));
2365       else /* This case may never occur, check.  */
2366         printf_unfiltered (_("No trace frame found\n"));
2367     }
2368
2369   /* If we're in nonstop mode and getting out of looking at trace
2370      frames, there won't be any current frame to go back to and
2371      display.  */
2372   if (from_tty
2373       && (has_stack_frames () || traceframe_number >= 0))
2374     {
2375       enum print_what print_what;
2376
2377       /* NOTE: in imitation of the step command, try to determine
2378          whether we have made a transition from one function to
2379          another.  If so, we'll print the "stack frame" (ie. the new
2380          function and it's arguments) -- otherwise we'll just show the
2381          new source line.  */
2382
2383       if (frame_id_eq (old_frame_id,
2384                        get_frame_id (get_current_frame ())))
2385         print_what = SRC_LINE;
2386       else
2387         print_what = SRC_AND_LOC;
2388
2389       print_stack_frame (get_selected_frame (NULL), 1, print_what);
2390       do_displays ();
2391     }
2392 }
2393
2394 /* trace_find_command takes a trace frame number n, 
2395    sends "QTFrame:<n>" to the target, 
2396    and accepts a reply that may contain several optional pieces
2397    of information: a frame number, a tracepoint number, and an
2398    indication of whether this is a trap frame or a stepping frame.
2399
2400    The minimal response is just "OK" (which indicates that the 
2401    target does not give us a frame number or a tracepoint number).
2402    Instead of that, the target may send us a string containing
2403    any combination of:
2404    F<hexnum>    (gives the selected frame number)
2405    T<hexnum>    (gives the selected tracepoint number)
2406  */
2407
2408 /* tfind command */
2409 static void
2410 trace_find_command (char *args, int from_tty)
2411 { /* This should only be called with a numeric argument.  */
2412   int frameno = -1;
2413
2414   if (current_trace_status ()->running
2415       && current_trace_status ()->filename == NULL)
2416     error (_("May not look at trace frames while trace is running."));
2417   
2418   if (args == 0 || *args == 0)
2419     { /* TFIND with no args means find NEXT trace frame.  */
2420       if (traceframe_number == -1)
2421         frameno = 0;    /* "next" is first one.  */
2422         else
2423         frameno = traceframe_number + 1;
2424     }
2425   else if (0 == strcmp (args, "-"))
2426     {
2427       if (traceframe_number == -1)
2428         error (_("not debugging trace buffer"));
2429       else if (from_tty && traceframe_number == 0)
2430         error (_("already at start of trace buffer"));
2431       
2432       frameno = traceframe_number - 1;
2433       }
2434   /* A hack to work around eval's need for fp to have been collected.  */
2435   else if (0 == strcmp (args, "-1"))
2436     frameno = -1;
2437   else
2438     frameno = parse_and_eval_long (args);
2439
2440   if (frameno < -1)
2441     error (_("invalid input (%d is less than zero)"), frameno);
2442
2443   tfind_1 (tfind_number, frameno, 0, 0, from_tty);
2444 }
2445
2446 /* tfind end */
2447 static void
2448 trace_find_end_command (char *args, int from_tty)
2449 {
2450   trace_find_command ("-1", from_tty);
2451 }
2452
2453 /* tfind start */
2454 static void
2455 trace_find_start_command (char *args, int from_tty)
2456 {
2457   trace_find_command ("0", from_tty);
2458 }
2459
2460 /* tfind pc command */
2461 static void
2462 trace_find_pc_command (char *args, int from_tty)
2463 {
2464   CORE_ADDR pc;
2465
2466   if (current_trace_status ()->running
2467       && current_trace_status ()->filename == NULL)
2468     error (_("May not look at trace frames while trace is running."));
2469
2470   if (args == 0 || *args == 0)
2471     pc = regcache_read_pc (get_current_regcache ());
2472   else
2473     pc = parse_and_eval_address (args);
2474
2475   tfind_1 (tfind_pc, 0, pc, 0, from_tty);
2476 }
2477
2478 /* tfind tracepoint command */
2479 static void
2480 trace_find_tracepoint_command (char *args, int from_tty)
2481 {
2482   int tdp;
2483   struct tracepoint *tp;
2484
2485   if (current_trace_status ()->running
2486       && current_trace_status ()->filename == NULL)
2487     error (_("May not look at trace frames while trace is running."));
2488
2489   if (args == 0 || *args == 0)
2490     {
2491       if (tracepoint_number == -1)
2492         error (_("No current tracepoint -- please supply an argument."));
2493       else
2494         tdp = tracepoint_number;        /* Default is current TDP.  */
2495     }
2496   else
2497     tdp = parse_and_eval_long (args);
2498
2499   /* If we have the tracepoint on hand, use the number that the
2500      target knows about (which may be different if we disconnected
2501      and reconnected).  */
2502   tp = get_tracepoint (tdp);
2503   if (tp)
2504     tdp = tp->number_on_target;
2505
2506   tfind_1 (tfind_tp, tdp, 0, 0, from_tty);
2507 }
2508
2509 /* TFIND LINE command:
2510
2511    This command will take a sourceline for argument, just like BREAK
2512    or TRACE (ie. anything that "decode_line_1" can handle).
2513
2514    With no argument, this command will find the next trace frame 
2515    corresponding to a source line OTHER THAN THE CURRENT ONE.  */
2516
2517 static void
2518 trace_find_line_command (char *args, int from_tty)
2519 {
2520   static CORE_ADDR start_pc, end_pc;
2521   struct symtabs_and_lines sals;
2522   struct symtab_and_line sal;
2523   struct cleanup *old_chain;
2524
2525   if (current_trace_status ()->running
2526       && current_trace_status ()->filename == NULL)
2527     error (_("May not look at trace frames while trace is running."));
2528
2529   if (args == 0 || *args == 0)
2530     {
2531       sal = find_pc_line (get_frame_pc (get_current_frame ()), 0);
2532       sals.nelts = 1;
2533       sals.sals = (struct symtab_and_line *)
2534         xmalloc (sizeof (struct symtab_and_line));
2535       sals.sals[0] = sal;
2536     }
2537   else
2538     {
2539       sals = decode_line_with_current_source (args, DECODE_LINE_FUNFIRSTLINE);
2540       sal = sals.sals[0];
2541     }
2542   
2543   old_chain = make_cleanup (xfree, sals.sals);
2544   if (sal.symtab == 0)
2545     error (_("No line number information available."));
2546
2547   if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
2548     {
2549       if (start_pc == end_pc)
2550         {
2551           printf_filtered ("Line %d of \"%s\"",
2552                            sal.line,
2553                            symtab_to_filename_for_display (sal.symtab));
2554           wrap_here ("  ");
2555           printf_filtered (" is at address ");
2556           print_address (get_current_arch (), start_pc, gdb_stdout);
2557           wrap_here ("  ");
2558           printf_filtered (" but contains no code.\n");
2559           sal = find_pc_line (start_pc, 0);
2560           if (sal.line > 0
2561               && find_line_pc_range (sal, &start_pc, &end_pc)
2562               && start_pc != end_pc)
2563             printf_filtered ("Attempting to find line %d instead.\n",
2564                              sal.line);
2565           else
2566             error (_("Cannot find a good line."));
2567         }
2568       }
2569     else
2570     /* Is there any case in which we get here, and have an address
2571        which the user would want to see?  If we have debugging
2572        symbols and no line numbers?  */
2573     error (_("Line number %d is out of range for \"%s\"."),
2574            sal.line, symtab_to_filename_for_display (sal.symtab));
2575
2576   /* Find within range of stated line.  */
2577   if (args && *args)
2578     tfind_1 (tfind_range, 0, start_pc, end_pc - 1, from_tty);
2579   else
2580     tfind_1 (tfind_outside, 0, start_pc, end_pc - 1, from_tty);
2581   do_cleanups (old_chain);
2582 }
2583
2584 /* tfind range command */
2585 static void
2586 trace_find_range_command (char *args, int from_tty)
2587 {
2588   static CORE_ADDR start, stop;
2589   char *tmp;
2590
2591   if (current_trace_status ()->running
2592       && current_trace_status ()->filename == NULL)
2593     error (_("May not look at trace frames while trace is running."));
2594
2595   if (args == 0 || *args == 0)
2596     { /* XXX FIXME: what should default behavior be?  */
2597       printf_filtered ("Usage: tfind range <startaddr>,<endaddr>\n");
2598       return;
2599     }
2600
2601   if (0 != (tmp = strchr (args, ',')))
2602     {
2603       *tmp++ = '\0';    /* Terminate start address.  */
2604       tmp = skip_spaces (tmp);
2605       start = parse_and_eval_address (args);
2606       stop = parse_and_eval_address (tmp);
2607     }
2608   else
2609     {                   /* No explicit end address?  */
2610       start = parse_and_eval_address (args);
2611       stop = start + 1; /* ??? */
2612     }
2613
2614   tfind_1 (tfind_range, 0, start, stop, from_tty);
2615 }
2616
2617 /* tfind outside command */
2618 static void
2619 trace_find_outside_command (char *args, int from_tty)
2620 {
2621   CORE_ADDR start, stop;
2622   char *tmp;
2623
2624   if (current_trace_status ()->running
2625       && current_trace_status ()->filename == NULL)
2626     error (_("May not look at trace frames while trace is running."));
2627
2628   if (args == 0 || *args == 0)
2629     { /* XXX FIXME: what should default behavior be?  */
2630       printf_filtered ("Usage: tfind outside <startaddr>,<endaddr>\n");
2631       return;
2632     }
2633
2634   if (0 != (tmp = strchr (args, ',')))
2635     {
2636       *tmp++ = '\0';    /* Terminate start address.  */
2637       tmp = skip_spaces (tmp);
2638       start = parse_and_eval_address (args);
2639       stop = parse_and_eval_address (tmp);
2640     }
2641   else
2642     {                   /* No explicit end address?  */
2643       start = parse_and_eval_address (args);
2644       stop = start + 1; /* ??? */
2645     }
2646
2647   tfind_1 (tfind_outside, 0, start, stop, from_tty);
2648 }
2649
2650 /* info scope command: list the locals for a scope.  */
2651 static void
2652 scope_info (char *args, int from_tty)
2653 {
2654   struct symtabs_and_lines sals;
2655   struct symbol *sym;
2656   struct minimal_symbol *msym;
2657   struct block *block;
2658   const char *symname;
2659   char *save_args = args;
2660   struct block_iterator iter;
2661   int j, count = 0;
2662   struct gdbarch *gdbarch;
2663   int regno;
2664
2665   if (args == 0 || *args == 0)
2666     error (_("requires an argument (function, "
2667              "line or *addr) to define a scope"));
2668
2669   sals = decode_line_1 (&args, DECODE_LINE_FUNFIRSTLINE, NULL, 0);
2670   if (sals.nelts == 0)
2671     return;             /* Presumably decode_line_1 has already warned.  */
2672
2673   /* Resolve line numbers to PC.  */
2674   resolve_sal_pc (&sals.sals[0]);
2675   block = block_for_pc (sals.sals[0].pc);
2676
2677   while (block != 0)
2678     {
2679       QUIT;                     /* Allow user to bail out with ^C.  */
2680       ALL_BLOCK_SYMBOLS (block, iter, sym)
2681         {
2682           QUIT;                 /* Allow user to bail out with ^C.  */
2683           if (count == 0)
2684             printf_filtered ("Scope for %s:\n", save_args);
2685           count++;
2686
2687           symname = SYMBOL_PRINT_NAME (sym);
2688           if (symname == NULL || *symname == '\0')
2689             continue;           /* Probably botched, certainly useless.  */
2690
2691           gdbarch = get_objfile_arch (SYMBOL_SYMTAB (sym)->objfile);
2692
2693           printf_filtered ("Symbol %s is ", symname);
2694
2695           if (SYMBOL_COMPUTED_OPS (sym) != NULL)
2696             SYMBOL_COMPUTED_OPS (sym)->describe_location (sym,
2697                                                           BLOCK_START (block),
2698                                                           gdb_stdout);
2699           else
2700             {
2701               switch (SYMBOL_CLASS (sym))
2702                 {
2703                 default:
2704                 case LOC_UNDEF: /* Messed up symbol?  */
2705                   printf_filtered ("a bogus symbol, class %d.\n",
2706                                    SYMBOL_CLASS (sym));
2707                   count--;              /* Don't count this one.  */
2708                   continue;
2709                 case LOC_CONST:
2710                   printf_filtered ("a constant with value %s (%s)",
2711                                    plongest (SYMBOL_VALUE (sym)),
2712                                    hex_string (SYMBOL_VALUE (sym)));
2713                   break;
2714                 case LOC_CONST_BYTES:
2715                   printf_filtered ("constant bytes: ");
2716                   if (SYMBOL_TYPE (sym))
2717                     for (j = 0; j < TYPE_LENGTH (SYMBOL_TYPE (sym)); j++)
2718                       fprintf_filtered (gdb_stdout, " %02x",
2719                                         (unsigned) SYMBOL_VALUE_BYTES (sym)[j]);
2720                   break;
2721                 case LOC_STATIC:
2722                   printf_filtered ("in static storage at address ");
2723                   printf_filtered ("%s", paddress (gdbarch,
2724                                                    SYMBOL_VALUE_ADDRESS (sym)));
2725                   break;
2726                 case LOC_REGISTER:
2727                   /* GDBARCH is the architecture associated with the objfile
2728                      the symbol is defined in; the target architecture may be
2729                      different, and may provide additional registers.  However,
2730                      we do not know the target architecture at this point.
2731                      We assume the objfile architecture will contain all the
2732                      standard registers that occur in debug info in that
2733                      objfile.  */
2734                   regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym,
2735                                                                       gdbarch);
2736
2737                   if (SYMBOL_IS_ARGUMENT (sym))
2738                     printf_filtered ("an argument in register $%s",
2739                                      gdbarch_register_name (gdbarch, regno));
2740                   else
2741                     printf_filtered ("a local variable in register $%s",
2742                                      gdbarch_register_name (gdbarch, regno));
2743                   break;
2744                 case LOC_ARG:
2745                   printf_filtered ("an argument at stack/frame offset %s",
2746                                    plongest (SYMBOL_VALUE (sym)));
2747                   break;
2748                 case LOC_LOCAL:
2749                   printf_filtered ("a local variable at frame offset %s",
2750                                    plongest (SYMBOL_VALUE (sym)));
2751                   break;
2752                 case LOC_REF_ARG:
2753                   printf_filtered ("a reference argument at offset %s",
2754                                    plongest (SYMBOL_VALUE (sym)));
2755                   break;
2756                 case LOC_REGPARM_ADDR:
2757                   /* Note comment at LOC_REGISTER.  */
2758                   regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym,
2759                                                                       gdbarch);
2760                   printf_filtered ("the address of an argument, in register $%s",
2761                                    gdbarch_register_name (gdbarch, regno));
2762                   break;
2763                 case LOC_TYPEDEF:
2764                   printf_filtered ("a typedef.\n");
2765                   continue;
2766                 case LOC_LABEL:
2767                   printf_filtered ("a label at address ");
2768                   printf_filtered ("%s", paddress (gdbarch,
2769                                                    SYMBOL_VALUE_ADDRESS (sym)));
2770                   break;
2771                 case LOC_BLOCK:
2772                   printf_filtered ("a function at address ");
2773                   printf_filtered ("%s",
2774                                    paddress (gdbarch, BLOCK_START (SYMBOL_BLOCK_VALUE (sym))));
2775                   break;
2776                 case LOC_UNRESOLVED:
2777                   msym = lookup_minimal_symbol (SYMBOL_LINKAGE_NAME (sym),
2778                                                 NULL, NULL);
2779                   if (msym == NULL)
2780                     printf_filtered ("Unresolved Static");
2781                   else
2782                     {
2783                       printf_filtered ("static storage at address ");
2784                       printf_filtered ("%s",
2785                                        paddress (gdbarch,
2786                                                  SYMBOL_VALUE_ADDRESS (msym)));
2787                     }
2788                   break;
2789                 case LOC_OPTIMIZED_OUT:
2790                   printf_filtered ("optimized out.\n");
2791                   continue;
2792                 case LOC_COMPUTED:
2793                   gdb_assert_not_reached (_("LOC_COMPUTED variable missing a method"));
2794                 }
2795             }
2796           if (SYMBOL_TYPE (sym))
2797             printf_filtered (", length %d.\n",
2798                              TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym))));
2799         }
2800       if (BLOCK_FUNCTION (block))
2801         break;
2802       else
2803         block = BLOCK_SUPERBLOCK (block);
2804     }
2805   if (count <= 0)
2806     printf_filtered ("Scope for %s contains no locals or arguments.\n",
2807                      save_args);
2808 }
2809
2810 /* Helper for trace_dump_command.  Dump the action list starting at
2811    ACTION.  STEPPING_ACTIONS is true if we're iterating over the
2812    actions of the body of a while-stepping action.  STEPPING_FRAME is
2813    set if the current traceframe was determined to be a while-stepping
2814    traceframe.  */
2815
2816 static void
2817 trace_dump_actions (struct command_line *action,
2818                     int stepping_actions, int stepping_frame,
2819                     int from_tty)
2820 {
2821   const char *action_exp, *next_comma;
2822
2823   for (; action != NULL; action = action->next)
2824     {
2825       struct cmd_list_element *cmd;
2826
2827       QUIT;                     /* Allow user to bail out with ^C.  */
2828       action_exp = action->line;
2829       action_exp = skip_spaces_const (action_exp);
2830
2831       /* The collection actions to be done while stepping are
2832          bracketed by the commands "while-stepping" and "end".  */
2833
2834       if (*action_exp == '#')   /* comment line */
2835         continue;
2836
2837       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
2838       if (cmd == 0)
2839         error (_("Bad action list item: %s"), action_exp);
2840
2841       if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
2842         {
2843           int i;
2844
2845           for (i = 0; i < action->body_count; ++i)
2846             trace_dump_actions (action->body_list[i],
2847                                 1, stepping_frame, from_tty);
2848         }
2849       else if (cmd_cfunc_eq (cmd, collect_pseudocommand))
2850         {
2851           /* Display the collected data.
2852              For the trap frame, display only what was collected at
2853              the trap.  Likewise for stepping frames, display only
2854              what was collected while stepping.  This means that the
2855              two boolean variables, STEPPING_FRAME and
2856              STEPPING_ACTIONS should be equal.  */
2857           if (stepping_frame == stepping_actions)
2858             {
2859               char *cmd = NULL;
2860               struct cleanup *old_chain
2861                 = make_cleanup (free_current_contents, &cmd);
2862               int trace_string = 0;
2863
2864               if (*action_exp == '/')
2865                 action_exp = decode_agent_options (action_exp, &trace_string);
2866
2867               do
2868                 {               /* Repeat over a comma-separated list.  */
2869                   QUIT;         /* Allow user to bail out with ^C.  */
2870                   if (*action_exp == ',')
2871                     action_exp++;
2872                   action_exp = skip_spaces_const (action_exp);
2873
2874                   next_comma = strchr (action_exp, ',');
2875
2876                   if (0 == strncasecmp (action_exp, "$reg", 4))
2877                     registers_info (NULL, from_tty);
2878                   else if (0 == strncasecmp (action_exp, "$_ret", 5))
2879                     ;
2880                   else if (0 == strncasecmp (action_exp, "$loc", 4))
2881                     locals_info (NULL, from_tty);
2882                   else if (0 == strncasecmp (action_exp, "$arg", 4))
2883                     args_info (NULL, from_tty);
2884                   else
2885                     {           /* variable */
2886                       if (next_comma != NULL)
2887                         {
2888                           size_t len = next_comma - action_exp;
2889
2890                           cmd = xrealloc (cmd, len + 1);
2891                           memcpy (cmd, action_exp, len);
2892                           cmd[len] = 0;
2893                         }
2894                       else
2895                         {
2896                           size_t len = strlen (action_exp);
2897
2898                           cmd = xrealloc (cmd, len + 1);
2899                           memcpy (cmd, action_exp, len + 1);
2900                         }
2901
2902                       printf_filtered ("%s = ", cmd);
2903                       output_command_const (cmd, from_tty);
2904                       printf_filtered ("\n");
2905                     }
2906                   action_exp = next_comma;
2907                 }
2908               while (action_exp && *action_exp == ',');
2909
2910               do_cleanups (old_chain);
2911             }
2912         }
2913     }
2914 }
2915
2916 /* The tdump command.  */
2917
2918 static void
2919 trace_dump_command (char *args, int from_tty)
2920 {
2921   struct regcache *regcache;
2922   struct tracepoint *t;
2923   int stepping_frame = 0;
2924   struct bp_location *loc;
2925   char *default_collect_line = NULL;
2926   struct command_line *actions, *default_collect_action = NULL;
2927   struct cleanup *old_chain = NULL;
2928
2929   if (tracepoint_number == -1)
2930     {
2931       warning (_("No current trace frame."));
2932       return;
2933     }
2934
2935   t = get_tracepoint (tracepoint_number);
2936
2937   if (t == NULL)
2938     error (_("No known tracepoint matches 'current' tracepoint #%d."),
2939            tracepoint_number);
2940
2941   printf_filtered ("Data collected at tracepoint %d, trace frame %d:\n",
2942                    tracepoint_number, traceframe_number);
2943
2944   /* The current frame is a trap frame if the frame PC is equal
2945      to the tracepoint PC.  If not, then the current frame was
2946      collected during single-stepping.  */
2947
2948   regcache = get_current_regcache ();
2949
2950   /* If the traceframe's address matches any of the tracepoint's
2951      locations, assume it is a direct hit rather than a while-stepping
2952      frame.  (FIXME this is not reliable, should record each frame's
2953      type.)  */
2954   stepping_frame = 1;
2955   for (loc = t->base.loc; loc; loc = loc->next)
2956     if (loc->address == regcache_read_pc (regcache))
2957       stepping_frame = 0;
2958
2959   actions = breakpoint_commands (&t->base);
2960
2961   /* If there is a default-collect list, make up a collect command,
2962      prepend to the tracepoint's commands, and pass the whole mess to
2963      the trace dump scanner.  We need to validate because
2964      default-collect might have been junked since the trace run.  */
2965   if (*default_collect)
2966     {
2967       default_collect_line = xstrprintf ("collect %s", default_collect);
2968       old_chain = make_cleanup (xfree, default_collect_line);
2969       validate_actionline (default_collect_line, &t->base);
2970       default_collect_action = xmalloc (sizeof (struct command_line));
2971       make_cleanup (xfree, default_collect_action);
2972       default_collect_action->next = actions;
2973       default_collect_action->line = default_collect_line;
2974       actions = default_collect_action;
2975     }
2976
2977   trace_dump_actions (actions, 0, stepping_frame, from_tty);
2978
2979   if (*default_collect)
2980     do_cleanups (old_chain);
2981 }
2982
2983 /* Encode a piece of a tracepoint's source-level definition in a form
2984    that is suitable for both protocol and saving in files.  */
2985 /* This version does not do multiple encodes for long strings; it should
2986    return an offset to the next piece to encode.  FIXME  */
2987
2988 extern int
2989 encode_source_string (int tpnum, ULONGEST addr,
2990                       char *srctype, char *src, char *buf, int buf_size)
2991 {
2992   if (80 + strlen (srctype) > buf_size)
2993     error (_("Buffer too small for source encoding"));
2994   sprintf (buf, "%x:%s:%s:%x:%x:",
2995            tpnum, phex_nz (addr, sizeof (addr)),
2996            srctype, 0, (int) strlen (src));
2997   if (strlen (buf) + strlen (src) * 2 >= buf_size)
2998     error (_("Source string too long for buffer"));
2999   bin2hex ((gdb_byte *) src, buf + strlen (buf), 0);
3000   return -1;
3001 }
3002
3003 /* Free trace file writer.  */
3004
3005 static void
3006 trace_file_writer_xfree (void *arg)
3007 {
3008   struct trace_file_writer *writer = arg;
3009
3010   writer->ops->dtor (writer);
3011   xfree (writer);
3012 }
3013
3014 /* TFILE trace writer.  */
3015
3016 struct tfile_trace_file_writer
3017 {
3018   struct trace_file_writer base;
3019
3020   /* File pointer to tfile trace file.  */
3021   FILE *fp;
3022   /* Path name of the tfile trace file.  */
3023   char *pathname;
3024 };
3025
3026 /* This is the implementation of trace_file_write_ops method
3027    target_save.  We just call the generic target
3028    target_save_trace_data to do target-side saving.  */
3029
3030 static int
3031 tfile_target_save (struct trace_file_writer *self,
3032                    const char *filename)
3033 {
3034   int err = target_save_trace_data (filename);
3035
3036   return (err >= 0);
3037 }
3038
3039 /* This is the implementation of trace_file_write_ops method
3040    dtor.  */
3041
3042 static void
3043 tfile_dtor (struct trace_file_writer *self)
3044 {
3045   struct tfile_trace_file_writer *writer
3046     = (struct tfile_trace_file_writer *) self;
3047
3048   xfree (writer->pathname);
3049
3050   if (writer->fp != NULL)
3051     fclose (writer->fp);
3052 }
3053
3054 /* This is the implementation of trace_file_write_ops method
3055    start.  It creates the trace file FILENAME and registers some
3056    cleanups.  */
3057
3058 static void
3059 tfile_start (struct trace_file_writer *self, const char *filename)
3060 {
3061   struct tfile_trace_file_writer *writer
3062     = (struct tfile_trace_file_writer *) self;
3063
3064   writer->pathname = tilde_expand (filename);
3065   writer->fp = gdb_fopen_cloexec (writer->pathname, "wb");
3066   if (writer->fp == NULL)
3067     error (_("Unable to open file '%s' for saving trace data (%s)"),
3068            filename, safe_strerror (errno));
3069 }
3070
3071 /* This is the implementation of trace_file_write_ops method
3072    write_header.  Write the TFILE header.  */
3073
3074 static void
3075 tfile_write_header (struct trace_file_writer *self)
3076 {
3077   struct tfile_trace_file_writer *writer
3078     = (struct tfile_trace_file_writer *) self;
3079   int written;
3080
3081   /* Write a file header, with a high-bit-set char to indicate a
3082      binary file, plus a hint as what this file is, and a version
3083      number in case of future needs.  */
3084   written = fwrite ("\x7fTRACE0\n", 8, 1, writer->fp);
3085   if (written < 1)
3086     perror_with_name (writer->pathname);
3087 }
3088
3089 /* This is the implementation of trace_file_write_ops method
3090    write_regblock_type.  Write the size of register block.  */
3091
3092 static void
3093 tfile_write_regblock_type (struct trace_file_writer *self, int size)
3094 {
3095   struct tfile_trace_file_writer *writer
3096     = (struct tfile_trace_file_writer *) self;
3097
3098   fprintf (writer->fp, "R %x\n", size);
3099 }
3100
3101 /* This is the implementation of trace_file_write_ops method
3102    write_status.  */
3103
3104 static void
3105 tfile_write_status (struct trace_file_writer *self,
3106                     struct trace_status *ts)
3107 {
3108   struct tfile_trace_file_writer *writer
3109     = (struct tfile_trace_file_writer *) self;
3110
3111   fprintf (writer->fp, "status %c;%s",
3112            (ts->running ? '1' : '0'), stop_reason_names[ts->stop_reason]);
3113   if (ts->stop_reason == tracepoint_error
3114       || ts->stop_reason == tstop_command)
3115     {
3116       char *buf = (char *) alloca (strlen (ts->stop_desc) * 2 + 1);
3117
3118       bin2hex ((gdb_byte *) ts->stop_desc, buf, 0);
3119       fprintf (writer->fp, ":%s", buf);
3120     }
3121   fprintf (writer->fp, ":%x", ts->stopping_tracepoint);
3122   if (ts->traceframe_count >= 0)
3123     fprintf (writer->fp, ";tframes:%x", ts->traceframe_count);
3124   if (ts->traceframes_created >= 0)
3125     fprintf (writer->fp, ";tcreated:%x", ts->traceframes_created);
3126   if (ts->buffer_free >= 0)
3127     fprintf (writer->fp, ";tfree:%x", ts->buffer_free);
3128   if (ts->buffer_size >= 0)
3129     fprintf (writer->fp, ";tsize:%x", ts->buffer_size);
3130   if (ts->disconnected_tracing)
3131     fprintf (writer->fp, ";disconn:%x", ts->disconnected_tracing);
3132   if (ts->circular_buffer)
3133     fprintf (writer->fp, ";circular:%x", ts->circular_buffer);
3134   if (ts->notes != NULL)
3135     {
3136       char *buf = (char *) alloca (strlen (ts->notes) * 2 + 1);
3137
3138       bin2hex ((gdb_byte *) ts->notes, buf, 0);
3139       fprintf (writer->fp, ";notes:%s", buf);
3140     }
3141   if (ts->user_name != NULL)
3142     {
3143       char *buf = (char *) alloca (strlen (ts->user_name) * 2 + 1);
3144
3145       bin2hex ((gdb_byte *) ts->user_name, buf, 0);
3146       fprintf (writer->fp, ";username:%s", buf);
3147     }
3148   fprintf (writer->fp, "\n");
3149 }
3150
3151 /* This is the implementation of trace_file_write_ops method
3152    write_uploaded_tsv.  */
3153
3154 static void
3155 tfile_write_uploaded_tsv (struct trace_file_writer *self,
3156                           struct uploaded_tsv *utsv)
3157 {
3158   char *buf = "";
3159   struct tfile_trace_file_writer *writer
3160     = (struct tfile_trace_file_writer *) self;
3161
3162   if (utsv->name)
3163     {
3164       buf = (char *) xmalloc (strlen (utsv->name) * 2 + 1);
3165       bin2hex ((gdb_byte *) (utsv->name), buf, 0);
3166     }
3167
3168   fprintf (writer->fp, "tsv %x:%s:%x:%s\n",
3169            utsv->number, phex_nz (utsv->initial_value, 8),
3170            utsv->builtin, buf);
3171
3172   if (utsv->name)
3173     xfree (buf);
3174 }
3175
3176 #define MAX_TRACE_UPLOAD 2000
3177
3178 /* This is the implementation of trace_file_write_ops method
3179    write_uploaded_tp.  */
3180
3181 static void
3182 tfile_write_uploaded_tp (struct trace_file_writer *self,
3183                          struct uploaded_tp *utp)
3184 {
3185   struct tfile_trace_file_writer *writer
3186     = (struct tfile_trace_file_writer *) self;
3187   int a;
3188   char *act;
3189   char buf[MAX_TRACE_UPLOAD];
3190
3191   fprintf (writer->fp, "tp T%x:%s:%c:%x:%x",
3192            utp->number, phex_nz (utp->addr, sizeof (utp->addr)),
3193            (utp->enabled ? 'E' : 'D'), utp->step, utp->pass);
3194   if (utp->type == bp_fast_tracepoint)
3195     fprintf (writer->fp, ":F%x", utp->orig_size);
3196   if (utp->cond)
3197     fprintf (writer->fp,
3198              ":X%x,%s", (unsigned int) strlen (utp->cond) / 2,
3199              utp->cond);
3200   fprintf (writer->fp, "\n");
3201   for (a = 0; VEC_iterate (char_ptr, utp->actions, a, act); ++a)
3202     fprintf (writer->fp, "tp A%x:%s:%s\n",
3203              utp->number, phex_nz (utp->addr, sizeof (utp->addr)), act);
3204   for (a = 0; VEC_iterate (char_ptr, utp->step_actions, a, act); ++a)
3205     fprintf (writer->fp, "tp S%x:%s:%s\n",
3206              utp->number, phex_nz (utp->addr, sizeof (utp->addr)), act);
3207   if (utp->at_string)
3208     {
3209       encode_source_string (utp->number, utp->addr,
3210                             "at", utp->at_string, buf, MAX_TRACE_UPLOAD);
3211       fprintf (writer->fp, "tp Z%s\n", buf);
3212     }
3213   if (utp->cond_string)
3214     {
3215       encode_source_string (utp->number, utp->addr,
3216                             "cond", utp->cond_string,
3217                             buf, MAX_TRACE_UPLOAD);
3218       fprintf (writer->fp, "tp Z%s\n", buf);
3219     }
3220   for (a = 0; VEC_iterate (char_ptr, utp->cmd_strings, a, act); ++a)
3221     {
3222       encode_source_string (utp->number, utp->addr, "cmd", act,
3223                             buf, MAX_TRACE_UPLOAD);
3224       fprintf (writer->fp, "tp Z%s\n", buf);
3225     }
3226   fprintf (writer->fp, "tp V%x:%s:%x:%s\n",
3227            utp->number, phex_nz (utp->addr, sizeof (utp->addr)),
3228            utp->hit_count,
3229            phex_nz (utp->traceframe_usage,
3230                     sizeof (utp->traceframe_usage)));
3231 }
3232
3233 /* This is the implementation of trace_file_write_ops method
3234    write_definition_end.  */
3235
3236 static void
3237 tfile_write_definition_end (struct trace_file_writer *self)
3238 {
3239   struct tfile_trace_file_writer *writer
3240     = (struct tfile_trace_file_writer *) self;
3241
3242   fprintf (writer->fp, "\n");
3243 }
3244
3245 /* This is the implementation of trace_file_write_ops method
3246    write_raw_data.  */
3247
3248 static void
3249 tfile_write_raw_data (struct trace_file_writer *self, gdb_byte *buf,
3250                       LONGEST len)
3251 {
3252   struct tfile_trace_file_writer *writer
3253     = (struct tfile_trace_file_writer *) self;
3254
3255   if (fwrite (buf, len, 1, writer->fp) < 1)
3256     perror_with_name (writer->pathname);
3257 }
3258
3259 /* This is the implementation of trace_file_write_ops method
3260    end.  */
3261
3262 static void
3263 tfile_end (struct trace_file_writer *self)
3264 {
3265   struct tfile_trace_file_writer *writer
3266     = (struct tfile_trace_file_writer *) self;
3267   uint32_t gotten = 0;
3268
3269   /* Mark the end of trace data.  */
3270   if (fwrite (&gotten, 4, 1, writer->fp) < 1)
3271     perror_with_name (writer->pathname);
3272 }
3273
3274 /* Operations to write trace buffers into TFILE format.  */
3275
3276 static const struct trace_file_write_ops tfile_write_ops =
3277 {
3278   tfile_dtor,
3279   tfile_target_save,
3280   tfile_start,
3281   tfile_write_header,
3282   tfile_write_regblock_type,
3283   tfile_write_status,
3284   tfile_write_uploaded_tsv,
3285   tfile_write_uploaded_tp,
3286   tfile_write_definition_end,
3287   tfile_write_raw_data,
3288   NULL,
3289   tfile_end,
3290 };
3291
3292 /* Helper macros.  */
3293
3294 #define TRACE_WRITE_R_BLOCK(writer, buf, size)  \
3295   writer->ops->frame_ops->write_r_block ((writer), (buf), (size))
3296 #define TRACE_WRITE_M_BLOCK_HEADER(writer, addr, size)            \
3297   writer->ops->frame_ops->write_m_block_header ((writer), (addr), \
3298                                                 (size))
3299 #define TRACE_WRITE_M_BLOCK_MEMORY(writer, buf, size)     \
3300   writer->ops->frame_ops->write_m_block_memory ((writer), (buf), \
3301                                                 (size))
3302 #define TRACE_WRITE_V_BLOCK(writer, num, val)   \
3303   writer->ops->frame_ops->write_v_block ((writer), (num), (val))
3304
3305 /* Save tracepoint data to file named FILENAME through WRITER.  WRITER
3306    determines the trace file format.  If TARGET_DOES_SAVE is non-zero,
3307    the save is performed on the target, otherwise GDB obtains all trace
3308    data and saves it locally.  */
3309
3310 static void
3311 trace_save (const char *filename, struct trace_file_writer *writer,
3312             int target_does_save)
3313 {
3314   struct trace_status *ts = current_trace_status ();
3315   int status;
3316   struct uploaded_tp *uploaded_tps = NULL, *utp;
3317   struct uploaded_tsv *uploaded_tsvs = NULL, *utsv;
3318
3319   ULONGEST offset = 0;
3320   gdb_byte buf[MAX_TRACE_UPLOAD];
3321 #define MAX_TRACE_UPLOAD 2000
3322   int written;
3323   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
3324
3325   /* If the target is to save the data to a file on its own, then just
3326      send the command and be done with it.  */
3327   if (target_does_save)
3328     {
3329       if (!writer->ops->target_save (writer, filename))
3330         error (_("Target failed to save trace data to '%s'."),
3331                filename);
3332       return;
3333     }
3334
3335   /* Get the trace status first before opening the file, so if the
3336      target is losing, we can get out without touching files.  */
3337   status = target_get_trace_status (ts);
3338
3339   writer->ops->start (writer, filename);
3340
3341   writer->ops->write_header (writer);
3342
3343   /* Write descriptive info.  */
3344
3345   /* Write out the size of a register block.  */
3346   writer->ops->write_regblock_type (writer, trace_regblock_size);
3347
3348   /* Write out status of the tracing run (aka "tstatus" info).  */
3349   writer->ops->write_status (writer, ts);
3350
3351   /* Note that we want to upload tracepoints and save those, rather
3352      than simply writing out the local ones, because the user may have
3353      changed tracepoints in GDB in preparation for a future tracing
3354      run, or maybe just mass-deleted all types of breakpoints as part
3355      of cleaning up.  So as not to contaminate the session, leave the
3356      data in its uploaded form, don't make into real tracepoints.  */
3357
3358   /* Get trace state variables first, they may be checked when parsing
3359      uploaded commands.  */
3360
3361   target_upload_trace_state_variables (&uploaded_tsvs);
3362
3363   for (utsv = uploaded_tsvs; utsv; utsv = utsv->next)
3364     writer->ops->write_uploaded_tsv (writer, utsv);
3365
3366   free_uploaded_tsvs (&uploaded_tsvs);
3367
3368   target_upload_tracepoints (&uploaded_tps);
3369
3370   for (utp = uploaded_tps; utp; utp = utp->next)
3371     target_get_tracepoint_status (NULL, utp);
3372
3373   for (utp = uploaded_tps; utp; utp = utp->next)
3374     writer->ops->write_uploaded_tp (writer, utp);
3375
3376   free_uploaded_tps (&uploaded_tps);
3377
3378   /* Mark the end of the definition section.  */
3379   writer->ops->write_definition_end (writer);
3380
3381   /* Get and write the trace data proper.  */
3382   while (1)
3383     {
3384       LONGEST gotten = 0;
3385
3386       /* The writer supports writing the contents of trace buffer
3387           directly to trace file.  Don't parse the contents of trace
3388           buffer.  */
3389       if (writer->ops->write_trace_buffer != NULL)
3390         {
3391           /* We ask for big blocks, in the hopes of efficiency, but
3392              will take less if the target has packet size limitations
3393              or some such.  */
3394           gotten = target_get_raw_trace_data (buf, offset,
3395                                               MAX_TRACE_UPLOAD);
3396           if (gotten < 0)
3397             error (_("Failure to get requested trace buffer data"));
3398           /* No more data is forthcoming, we're done.  */
3399           if (gotten == 0)
3400             break;
3401
3402           writer->ops->write_trace_buffer (writer, buf, gotten);
3403
3404           offset += gotten;
3405         }
3406       else
3407         {
3408           uint16_t tp_num;
3409           uint32_t tf_size;
3410           /* Parse the trace buffers according to how data are stored
3411              in trace buffer in GDBserver.  */
3412
3413           gotten = target_get_raw_trace_data (buf, offset, 6);
3414
3415           if (gotten == 0)
3416             break;
3417
3418           /* Read the first six bytes in, which is the tracepoint
3419              number and trace frame size.  */
3420           tp_num = (uint16_t)
3421             extract_unsigned_integer (&buf[0], 2, byte_order);
3422
3423           tf_size = (uint32_t)
3424             extract_unsigned_integer (&buf[2], 4, byte_order);
3425
3426           writer->ops->frame_ops->start (writer, tp_num);
3427           gotten = 6;
3428
3429           if (tf_size > 0)
3430             {
3431               unsigned int block;
3432
3433               offset += 6;
3434
3435               for (block = 0; block < tf_size; )
3436                 {
3437                   gdb_byte block_type;
3438
3439                   /* We'll fetch one block each time, in order to
3440                      handle the extremely large 'M' block.  We first
3441                      fetch one byte to get the type of the block.  */
3442                   gotten = target_get_raw_trace_data (buf, offset, 1);
3443                   if (gotten < 1)
3444                     error (_("Failure to get requested trace buffer data"));
3445
3446                   gotten = 1;
3447                   block += 1;
3448                   offset += 1;
3449
3450                   block_type = buf[0];
3451                   switch (block_type)
3452                     {
3453                     case 'R':
3454                       gotten
3455                         = target_get_raw_trace_data (buf, offset,
3456                                                      trace_regblock_size);
3457                       if (gotten < trace_regblock_size)
3458                         error (_("Failure to get requested trace"
3459                                  " buffer data"));
3460
3461                       TRACE_WRITE_R_BLOCK (writer, buf,
3462                                            trace_regblock_size);
3463                       break;
3464                     case 'M':
3465                       {
3466                         unsigned short mlen;
3467                         ULONGEST addr;
3468                         LONGEST t;
3469                         int j;
3470
3471                         t = target_get_raw_trace_data (buf,offset, 10);
3472                         if (t < 10)
3473                           error (_("Failure to get requested trace"
3474                                    " buffer data"));
3475
3476                         offset += 10;
3477                         block += 10;
3478
3479                         gotten = 0;
3480                         addr = (ULONGEST)
3481                           extract_unsigned_integer (buf, 8,
3482                                                     byte_order);
3483                         mlen = (unsigned short)
3484                           extract_unsigned_integer (&buf[8], 2,
3485                                                     byte_order);
3486
3487                         TRACE_WRITE_M_BLOCK_HEADER (writer, addr,
3488                                                     mlen);
3489
3490                         /* The memory contents in 'M' block may be
3491                            very large.  Fetch the data from the target
3492                            and write them into file one by one.  */
3493                         for (j = 0; j < mlen; )
3494                           {
3495                             unsigned int read_length;
3496
3497                             if (mlen - j > MAX_TRACE_UPLOAD)
3498                               read_length = MAX_TRACE_UPLOAD;
3499                             else
3500                               read_length = mlen - j;
3501
3502                             t = target_get_raw_trace_data (buf,
3503                                                            offset + j,
3504                                                            read_length);
3505                             if (t < read_length)
3506                               error (_("Failure to get requested"
3507                                        " trace buffer data"));
3508
3509                             TRACE_WRITE_M_BLOCK_MEMORY (writer, buf,
3510                                                         read_length);
3511
3512                             j += read_length;
3513                             gotten += read_length;
3514                           }
3515
3516                         break;
3517                       }
3518                     case 'V':
3519                       {
3520                         int vnum;
3521                         LONGEST val;
3522
3523                         gotten
3524                           = target_get_raw_trace_data (buf, offset,
3525                                                        12);
3526                         if (gotten < 12)
3527                           error (_("Failure to get requested"
3528                                    " trace buffer data"));
3529
3530                         vnum  = (int) extract_signed_integer (buf,
3531                                                               4,
3532                                                               byte_order);
3533                         val
3534                           = extract_signed_integer (&buf[4], 8,
3535                                                     byte_order);
3536
3537                         TRACE_WRITE_V_BLOCK (writer, vnum, val);
3538                       }
3539                       break;
3540                     default:
3541                       error (_("Unknown block type '%c' (0x%x) in"
3542                                " trace frame"),
3543                              block_type, block_type);
3544                     }
3545
3546                   block += gotten;
3547                   offset += gotten;
3548                 }
3549             }
3550           else
3551             offset += gotten;
3552
3553           writer->ops->frame_ops->end (writer);
3554         }
3555     }
3556
3557   writer->ops->end (writer);
3558 }
3559
3560 /* Return a trace writer for TFILE format.  */
3561
3562 static struct trace_file_writer *
3563 tfile_trace_file_writer_new (void)
3564 {
3565   struct tfile_trace_file_writer *writer
3566     = xmalloc (sizeof (struct tfile_trace_file_writer));
3567
3568   writer->base.ops = &tfile_write_ops;
3569   writer->fp = NULL;
3570   writer->pathname = NULL;
3571
3572   return (struct trace_file_writer *) writer;
3573 }
3574
3575 static void
3576 trace_save_command (char *args, int from_tty)
3577 {
3578   int target_does_save = 0;
3579   char **argv;
3580   char *filename = NULL;
3581   struct cleanup *back_to;
3582   int generate_ctf = 0;
3583   struct trace_file_writer *writer = NULL;
3584
3585   if (args == NULL)
3586     error_no_arg (_("file in which to save trace data"));
3587
3588   argv = gdb_buildargv (args);
3589   back_to = make_cleanup_freeargv (argv);
3590
3591   for (; *argv; ++argv)
3592     {
3593       if (strcmp (*argv, "-r") == 0)
3594         target_does_save = 1;
3595       if (strcmp (*argv, "-ctf") == 0)
3596         generate_ctf = 1;
3597       else if (**argv == '-')
3598         error (_("unknown option `%s'"), *argv);
3599       else
3600         filename = *argv;
3601     }
3602
3603   if (!filename)
3604     error_no_arg (_("file in which to save trace data"));
3605
3606   if (generate_ctf)
3607     writer = ctf_trace_file_writer_new ();
3608   else
3609     writer = tfile_trace_file_writer_new ();
3610
3611   make_cleanup (trace_file_writer_xfree, writer);
3612
3613   trace_save (filename, writer, target_does_save);
3614
3615   if (from_tty)
3616     printf_filtered (_("Trace data saved to %s '%s'.\n"),
3617                      generate_ctf ? "directory" : "file", filename);
3618
3619   do_cleanups (back_to);
3620 }
3621
3622 /* Save the trace data to file FILENAME of tfile format.  */
3623
3624 void
3625 trace_save_tfile (const char *filename, int target_does_save)
3626 {
3627   struct trace_file_writer *writer;
3628   struct cleanup *back_to;
3629
3630   writer = tfile_trace_file_writer_new ();
3631   back_to = make_cleanup (trace_file_writer_xfree, writer);
3632   trace_save (filename, writer, target_does_save);
3633   do_cleanups (back_to);
3634 }
3635
3636 /* Save the trace data to dir DIRNAME of ctf format.  */
3637
3638 void
3639 trace_save_ctf (const char *dirname, int target_does_save)
3640 {
3641   struct trace_file_writer *writer;
3642   struct cleanup *back_to;
3643
3644   writer = ctf_trace_file_writer_new ();
3645   back_to = make_cleanup (trace_file_writer_xfree, writer);
3646
3647   trace_save (dirname, writer, target_does_save);
3648   do_cleanups (back_to);
3649 }
3650
3651 /* Tell the target what to do with an ongoing tracing run if GDB
3652    disconnects for some reason.  */
3653
3654 static void
3655 set_disconnected_tracing (char *args, int from_tty,
3656                           struct cmd_list_element *c)
3657 {
3658   target_set_disconnected_tracing (disconnected_tracing);
3659 }
3660
3661 static void
3662 set_circular_trace_buffer (char *args, int from_tty,
3663                            struct cmd_list_element *c)
3664 {
3665   target_set_circular_trace_buffer (circular_trace_buffer);
3666 }
3667
3668 static void
3669 set_trace_buffer_size (char *args, int from_tty,
3670                            struct cmd_list_element *c)
3671 {
3672   target_set_trace_buffer_size (trace_buffer_size);
3673 }
3674
3675 static void
3676 set_trace_user (char *args, int from_tty,
3677                 struct cmd_list_element *c)
3678 {
3679   int ret;
3680
3681   ret = target_set_trace_notes (trace_user, NULL, NULL);
3682
3683   if (!ret)
3684     warning (_("Target does not support trace notes, user ignored"));
3685 }
3686
3687 static void
3688 set_trace_notes (char *args, int from_tty,
3689                  struct cmd_list_element *c)
3690 {
3691   int ret;
3692
3693   ret = target_set_trace_notes (NULL, trace_notes, NULL);
3694
3695   if (!ret)
3696     warning (_("Target does not support trace notes, note ignored"));
3697 }
3698
3699 static void
3700 set_trace_stop_notes (char *args, int from_tty,
3701                       struct cmd_list_element *c)
3702 {
3703   int ret;
3704
3705   ret = target_set_trace_notes (NULL, NULL, trace_stop_notes);
3706
3707   if (!ret)
3708     warning (_("Target does not support trace notes, stop note ignored"));
3709 }
3710
3711 /* Convert the memory pointed to by mem into hex, placing result in buf.
3712  * Return a pointer to the last char put in buf (null)
3713  * "stolen" from sparc-stub.c
3714  */
3715
3716 static const char hexchars[] = "0123456789abcdef";
3717
3718 static char *
3719 mem2hex (gdb_byte *mem, char *buf, int count)
3720 {
3721   gdb_byte ch;
3722
3723   while (count-- > 0)
3724     {
3725       ch = *mem++;
3726
3727       *buf++ = hexchars[ch >> 4];
3728       *buf++ = hexchars[ch & 0xf];
3729     }
3730
3731   *buf = 0;
3732
3733   return buf;
3734 }
3735
3736 int
3737 get_traceframe_number (void)
3738 {
3739   return traceframe_number;
3740 }
3741
3742 int
3743 get_tracepoint_number (void)
3744 {
3745   return tracepoint_number;
3746 }
3747
3748 /* Make the traceframe NUM be the current trace frame.  Does nothing
3749    if NUM is already current.  */
3750
3751 void
3752 set_current_traceframe (int num)
3753 {
3754   int newnum;
3755
3756   if (traceframe_number == num)
3757     {
3758       /* Nothing to do.  */
3759       return;
3760     }
3761
3762   newnum = target_trace_find (tfind_number, num, 0, 0, NULL);
3763
3764   if (newnum != num)
3765     warning (_("could not change traceframe"));
3766
3767   set_traceframe_num (newnum);
3768
3769   /* Changing the traceframe changes our view of registers and of the
3770      frame chain.  */
3771   registers_changed ();
3772
3773   clear_traceframe_info ();
3774 }
3775
3776 /* Make the traceframe NUM be the current trace frame, and do nothing
3777    more.  */
3778
3779 void
3780 set_traceframe_number (int num)
3781 {
3782   traceframe_number = num;
3783 }
3784
3785 /* A cleanup used when switching away and back from tfind mode.  */
3786
3787 struct current_traceframe_cleanup
3788 {
3789   /* The traceframe we were inspecting.  */
3790   int traceframe_number;
3791 };
3792
3793 static void
3794 do_restore_current_traceframe_cleanup (void *arg)
3795 {
3796   struct current_traceframe_cleanup *old = arg;
3797
3798   set_current_traceframe (old->traceframe_number);
3799 }
3800
3801 static void
3802 restore_current_traceframe_cleanup_dtor (void *arg)
3803 {
3804   struct current_traceframe_cleanup *old = arg;
3805
3806   xfree (old);
3807 }
3808
3809 struct cleanup *
3810 make_cleanup_restore_current_traceframe (void)
3811 {
3812   struct current_traceframe_cleanup *old;
3813
3814   old = xmalloc (sizeof (struct current_traceframe_cleanup));
3815   old->traceframe_number = traceframe_number;
3816
3817   return make_cleanup_dtor (do_restore_current_traceframe_cleanup, old,
3818                             restore_current_traceframe_cleanup_dtor);
3819 }
3820
3821 struct cleanup *
3822 make_cleanup_restore_traceframe_number (void)
3823 {
3824   return make_cleanup_restore_integer (&traceframe_number);
3825 }
3826
3827 /* Given a number and address, return an uploaded tracepoint with that
3828    number, creating if necessary.  */
3829
3830 struct uploaded_tp *
3831 get_uploaded_tp (int num, ULONGEST addr, struct uploaded_tp **utpp)
3832 {
3833   struct uploaded_tp *utp;
3834
3835   for (utp = *utpp; utp; utp = utp->next)
3836     if (utp->number == num && utp->addr == addr)
3837       return utp;
3838   utp = (struct uploaded_tp *) xmalloc (sizeof (struct uploaded_tp));
3839   memset (utp, 0, sizeof (struct uploaded_tp));
3840   utp->number = num;
3841   utp->addr = addr;
3842   utp->actions = NULL;
3843   utp->step_actions = NULL;
3844   utp->cmd_strings = NULL;
3845   utp->next = *utpp;
3846   *utpp = utp;
3847   return utp;
3848 }
3849
3850 static void
3851 free_uploaded_tps (struct uploaded_tp **utpp)
3852 {
3853   struct uploaded_tp *next_one;
3854
3855   while (*utpp)
3856     {
3857       next_one = (*utpp)->next;
3858       xfree (*utpp);
3859       *utpp = next_one;
3860     }
3861 }
3862
3863 /* Given a number and address, return an uploaded tracepoint with that
3864    number, creating if necessary.  */
3865
3866 struct uploaded_tsv *
3867 get_uploaded_tsv (int num, struct uploaded_tsv **utsvp)
3868 {
3869   struct uploaded_tsv *utsv;
3870
3871   for (utsv = *utsvp; utsv; utsv = utsv->next)
3872     if (utsv->number == num)
3873       return utsv;
3874   utsv = (struct uploaded_tsv *) xmalloc (sizeof (struct uploaded_tsv));
3875   memset (utsv, 0, sizeof (struct uploaded_tsv));
3876   utsv->number = num;
3877   utsv->next = *utsvp;
3878   *utsvp = utsv;
3879   return utsv;
3880 }
3881
3882 static void
3883 free_uploaded_tsvs (struct uploaded_tsv **utsvp)
3884 {
3885   struct uploaded_tsv *next_one;
3886
3887   while (*utsvp)
3888     {
3889       next_one = (*utsvp)->next;
3890       xfree (*utsvp);
3891       *utsvp = next_one;
3892     }
3893 }
3894
3895 /* FIXME this function is heuristic and will miss the cases where the
3896    conditional is semantically identical but differs in whitespace,
3897    such as "x == 0" vs "x==0".  */
3898
3899 static int
3900 cond_string_is_same (char *str1, char *str2)
3901 {
3902   if (str1 == NULL || str2 == NULL)
3903     return (str1 == str2);
3904
3905   return (strcmp (str1, str2) == 0);
3906 }
3907
3908 /* Look for an existing tracepoint that seems similar enough to the
3909    uploaded one.  Enablement isn't compared, because the user can
3910    toggle that freely, and may have done so in anticipation of the
3911    next trace run.  Return the location of matched tracepoint.  */
3912
3913 static struct bp_location *
3914 find_matching_tracepoint_location (struct uploaded_tp *utp)
3915 {
3916   VEC(breakpoint_p) *tp_vec = all_tracepoints ();
3917   int ix;
3918   struct breakpoint *b;
3919   struct bp_location *loc;
3920
3921   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
3922     {
3923       struct tracepoint *t = (struct tracepoint *) b;
3924
3925       if (b->type == utp->type
3926           && t->step_count == utp->step
3927           && t->pass_count == utp->pass
3928           && cond_string_is_same (t->base.cond_string, utp->cond_string)
3929           /* FIXME also test actions.  */
3930           )
3931         {
3932           /* Scan the locations for an address match.  */
3933           for (loc = b->loc; loc; loc = loc->next)
3934             {
3935               if (loc->address == utp->addr)
3936                 return loc;
3937             }
3938         }
3939     }
3940   return NULL;
3941 }
3942
3943 /* Given a list of tracepoints uploaded from a target, attempt to
3944    match them up with existing tracepoints, and create new ones if not
3945    found.  */
3946
3947 void
3948 merge_uploaded_tracepoints (struct uploaded_tp **uploaded_tps)
3949 {
3950   struct uploaded_tp *utp;
3951   /* A set of tracepoints which are modified.  */
3952   VEC(breakpoint_p) *modified_tp = NULL;
3953   int ix;
3954   struct breakpoint *b;
3955
3956   /* Look for GDB tracepoints that match up with our uploaded versions.  */
3957   for (utp = *uploaded_tps; utp; utp = utp->next)
3958     {
3959       struct bp_location *loc;
3960       struct tracepoint *t;
3961
3962       loc = find_matching_tracepoint_location (utp);
3963       if (loc)
3964         {
3965           int found = 0;
3966
3967           /* Mark this location as already inserted.  */
3968           loc->inserted = 1;
3969           t = (struct tracepoint *) loc->owner;
3970           printf_filtered (_("Assuming tracepoint %d is same "
3971                              "as target's tracepoint %d at %s.\n"),
3972                            loc->owner->number, utp->number,
3973                            paddress (loc->gdbarch, utp->addr));
3974
3975           /* The tracepoint LOC->owner was modified (the location LOC
3976              was marked as inserted in the target).  Save it in
3977              MODIFIED_TP if not there yet.  The 'breakpoint-modified'
3978              observers will be notified later once for each tracepoint
3979              saved in MODIFIED_TP.  */
3980           for (ix = 0;
3981                VEC_iterate (breakpoint_p, modified_tp, ix, b);
3982                ix++)
3983             if (b == loc->owner)
3984               {
3985                 found = 1;
3986                 break;
3987               }
3988           if (!found)
3989             VEC_safe_push (breakpoint_p, modified_tp, loc->owner);
3990         }
3991       else
3992         {
3993           t = create_tracepoint_from_upload (utp);
3994           if (t)
3995             printf_filtered (_("Created tracepoint %d for "
3996                                "target's tracepoint %d at %s.\n"),
3997                              t->base.number, utp->number,
3998                              paddress (get_current_arch (), utp->addr));
3999           else
4000             printf_filtered (_("Failed to create tracepoint for target's "
4001                                "tracepoint %d at %s, skipping it.\n"),
4002                              utp->number,
4003                              paddress (get_current_arch (), utp->addr));
4004         }
4005       /* Whether found or created, record the number used by the
4006          target, to help with mapping target tracepoints back to their
4007          counterparts here.  */
4008       if (t)
4009         t->number_on_target = utp->number;
4010     }
4011
4012   /* Notify 'breakpoint-modified' observer that at least one of B's
4013      locations was changed.  */
4014   for (ix = 0; VEC_iterate (breakpoint_p, modified_tp, ix, b); ix++)
4015     observer_notify_breakpoint_modified (b);
4016
4017   VEC_free (breakpoint_p, modified_tp);
4018   free_uploaded_tps (uploaded_tps);
4019 }
4020
4021 /* Trace state variables don't have much to identify them beyond their
4022    name, so just use that to detect matches.  */
4023
4024 static struct trace_state_variable *
4025 find_matching_tsv (struct uploaded_tsv *utsv)
4026 {
4027   if (!utsv->name)
4028     return NULL;
4029
4030   return find_trace_state_variable (utsv->name);
4031 }
4032
4033 static struct trace_state_variable *
4034 create_tsv_from_upload (struct uploaded_tsv *utsv)
4035 {
4036   const char *namebase;
4037   char *buf;
4038   int try_num = 0;
4039   struct trace_state_variable *tsv;
4040   struct cleanup *old_chain;
4041
4042   if (utsv->name)
4043     {
4044       namebase = utsv->name;
4045       buf = xstrprintf ("%s", namebase);
4046     }
4047   else
4048     {
4049       namebase = "__tsv";
4050       buf = xstrprintf ("%s_%d", namebase, try_num++);
4051     }
4052
4053   /* Fish for a name that is not in use.  */
4054   /* (should check against all internal vars?)  */
4055   while (find_trace_state_variable (buf))
4056     {
4057       xfree (buf);
4058       buf = xstrprintf ("%s_%d", namebase, try_num++);
4059     }
4060
4061   old_chain = make_cleanup (xfree, buf);
4062
4063   /* We have an available name, create the variable.  */
4064   tsv = create_trace_state_variable (buf);
4065   tsv->initial_value = utsv->initial_value;
4066   tsv->builtin = utsv->builtin;
4067
4068   observer_notify_tsv_created (tsv);
4069
4070   do_cleanups (old_chain);
4071
4072   return tsv;
4073 }
4074
4075 /* Given a list of uploaded trace state variables, try to match them
4076    up with existing variables, or create additional ones.  */
4077
4078 void
4079 merge_uploaded_trace_state_variables (struct uploaded_tsv **uploaded_tsvs)
4080 {
4081   int ix;
4082   struct uploaded_tsv *utsv;
4083   struct trace_state_variable *tsv;
4084   int highest;
4085
4086   /* Most likely some numbers will have to be reassigned as part of
4087      the merge, so clear them all in anticipation.  */
4088   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
4089     tsv->number = 0;
4090
4091   for (utsv = *uploaded_tsvs; utsv; utsv = utsv->next)
4092     {
4093       tsv = find_matching_tsv (utsv);
4094       if (tsv)
4095         {
4096           if (info_verbose)
4097             printf_filtered (_("Assuming trace state variable $%s "
4098                                "is same as target's variable %d.\n"),
4099                              tsv->name, utsv->number);
4100         }
4101       else
4102         {
4103           tsv = create_tsv_from_upload (utsv);
4104           if (info_verbose)
4105             printf_filtered (_("Created trace state variable "
4106                                "$%s for target's variable %d.\n"),
4107                              tsv->name, utsv->number);
4108         }
4109       /* Give precedence to numberings that come from the target.  */
4110       if (tsv)
4111         tsv->number = utsv->number;
4112     }
4113
4114   /* Renumber everything that didn't get a target-assigned number.  */
4115   highest = 0;
4116   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
4117     if (tsv->number > highest)
4118       highest = tsv->number;
4119
4120   ++highest;
4121   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
4122     if (tsv->number == 0)
4123       tsv->number = highest++;
4124
4125   free_uploaded_tsvs (uploaded_tsvs);
4126 }
4127
4128 /* target tfile command */
4129
4130 static struct target_ops tfile_ops;
4131
4132 /* Fill in tfile_ops with its defined operations and properties.  */
4133
4134 #define TRACE_HEADER_SIZE 8
4135
4136 static char *trace_filename;
4137 static int trace_fd = -1;
4138 static off_t trace_frames_offset;
4139 static off_t cur_offset;
4140 static int cur_data_size;
4141 int trace_regblock_size;
4142
4143 static void tfile_interp_line (char *line,
4144                                struct uploaded_tp **utpp,
4145                                struct uploaded_tsv **utsvp);
4146
4147 /* Read SIZE bytes into READBUF from the trace frame, starting at
4148    TRACE_FD's current position.  Note that this call `read'
4149    underneath, hence it advances the file's seek position.  Throws an
4150    error if the `read' syscall fails, or less than SIZE bytes are
4151    read.  */
4152
4153 static void
4154 tfile_read (gdb_byte *readbuf, int size)
4155 {
4156   int gotten;
4157
4158   gotten = read (trace_fd, readbuf, size);
4159   if (gotten < 0)
4160     perror_with_name (trace_filename);
4161   else if (gotten < size)
4162     error (_("Premature end of file while reading trace file"));
4163 }
4164
4165 static void
4166 tfile_open (char *filename, int from_tty)
4167 {
4168   volatile struct gdb_exception ex;
4169   char *temp;
4170   struct cleanup *old_chain;
4171   int flags;
4172   int scratch_chan;
4173   char header[TRACE_HEADER_SIZE];
4174   char linebuf[1000]; /* Should be max remote packet size or so.  */
4175   gdb_byte byte;
4176   int bytes, i;
4177   struct trace_status *ts;
4178   struct uploaded_tp *uploaded_tps = NULL;
4179   struct uploaded_tsv *uploaded_tsvs = NULL;
4180
4181   target_preopen (from_tty);
4182   if (!filename)
4183     error (_("No trace file specified."));
4184
4185   filename = tilde_expand (filename);
4186   if (!IS_ABSOLUTE_PATH(filename))
4187     {
4188       temp = concat (current_directory, "/", filename, (char *) NULL);
4189       xfree (filename);
4190       filename = temp;
4191     }
4192
4193   old_chain = make_cleanup (xfree, filename);
4194
4195   flags = O_BINARY | O_LARGEFILE;
4196   flags |= O_RDONLY;
4197   scratch_chan = gdb_open_cloexec (filename, flags, 0);
4198   if (scratch_chan < 0)
4199     perror_with_name (filename);
4200
4201   /* Looks semi-reasonable.  Toss the old trace file and work on the new.  */
4202
4203   discard_cleanups (old_chain); /* Don't free filename any more.  */
4204   unpush_target (&tfile_ops);
4205
4206   trace_filename = xstrdup (filename);
4207   trace_fd = scratch_chan;
4208
4209   bytes = 0;
4210   /* Read the file header and test for validity.  */
4211   tfile_read ((gdb_byte *) &header, TRACE_HEADER_SIZE);
4212
4213   bytes += TRACE_HEADER_SIZE;
4214   if (!(header[0] == 0x7f
4215         && (strncmp (header + 1, "TRACE0\n", 7) == 0)))
4216     error (_("File is not a valid trace file."));
4217
4218   push_target (&tfile_ops);
4219
4220   trace_regblock_size = 0;
4221   ts = current_trace_status ();
4222   /* We know we're working with a file.  Record its name.  */
4223   ts->filename = trace_filename;
4224   /* Set defaults in case there is no status line.  */
4225   ts->running_known = 0;
4226   ts->stop_reason = trace_stop_reason_unknown;
4227   ts->traceframe_count = -1;
4228   ts->buffer_free = 0;
4229   ts->disconnected_tracing = 0;
4230   ts->circular_buffer = 0;
4231
4232   TRY_CATCH (ex, RETURN_MASK_ALL)
4233     {
4234       /* Read through a section of newline-terminated lines that
4235          define things like tracepoints.  */
4236       i = 0;
4237       while (1)
4238         {
4239           tfile_read (&byte, 1);
4240
4241           ++bytes;
4242           if (byte == '\n')
4243             {
4244               /* Empty line marks end of the definition section.  */
4245               if (i == 0)
4246                 break;
4247               linebuf[i] = '\0';
4248               i = 0;
4249               tfile_interp_line (linebuf, &uploaded_tps, &uploaded_tsvs);
4250             }
4251           else
4252             linebuf[i++] = byte;
4253           if (i >= 1000)
4254             error (_("Excessively long lines in trace file"));
4255         }
4256
4257       /* Record the starting offset of the binary trace data.  */
4258       trace_frames_offset = bytes;
4259
4260       /* If we don't have a blocksize, we can't interpret the
4261          traceframes.  */
4262       if (trace_regblock_size == 0)
4263         error (_("No register block size recorded in trace file"));
4264     }
4265   if (ex.reason < 0)
4266     {
4267       /* Pop the partially set up target.  */
4268       pop_target ();
4269       throw_exception (ex);
4270     }
4271
4272   if (ts->traceframe_count <= 0)
4273     warning (_("No traceframes present in this file."));
4274
4275   /* Add the file's tracepoints and variables into the current mix.  */
4276
4277   /* Get trace state variables first, they may be checked when parsing
4278      uploaded commands.  */
4279   merge_uploaded_trace_state_variables (&uploaded_tsvs);
4280
4281   merge_uploaded_tracepoints (&uploaded_tps);
4282 }
4283
4284 /* Interpret the given line from the definitions part of the trace
4285    file.  */
4286
4287 static void
4288 tfile_interp_line (char *line, struct uploaded_tp **utpp,
4289                    struct uploaded_tsv **utsvp)
4290 {
4291   char *p = line;
4292
4293   if (strncmp (p, "R ", strlen ("R ")) == 0)
4294     {
4295       p += strlen ("R ");
4296       trace_regblock_size = strtol (p, &p, 16);
4297     }
4298   else if (strncmp (p, "status ", strlen ("status ")) == 0)
4299     {
4300       p += strlen ("status ");
4301       parse_trace_status (p, current_trace_status ());
4302     }
4303   else if (strncmp (p, "tp ", strlen ("tp ")) == 0)
4304     {
4305       p += strlen ("tp ");
4306       parse_tracepoint_definition (p, utpp);
4307     }
4308   else if (strncmp (p, "tsv ", strlen ("tsv ")) == 0)
4309     {
4310       p += strlen ("tsv ");
4311       parse_tsv_definition (p, utsvp);
4312     }
4313   else
4314     warning (_("Ignoring trace file definition \"%s\""), line);
4315 }
4316
4317 /* Parse the part of trace status syntax that is shared between
4318    the remote protocol and the trace file reader.  */
4319
4320 void
4321 parse_trace_status (char *line, struct trace_status *ts)
4322 {
4323   char *p = line, *p1, *p2, *p3, *p_temp;
4324   int end;
4325   ULONGEST val;
4326
4327   ts->running_known = 1;
4328   ts->running = (*p++ == '1');
4329   ts->stop_reason = trace_stop_reason_unknown;
4330   xfree (ts->stop_desc);
4331   ts->stop_desc = NULL;
4332   ts->traceframe_count = -1;
4333   ts->traceframes_created = -1;
4334   ts->buffer_free = -1;
4335   ts->buffer_size = -1;
4336   ts->disconnected_tracing = 0;
4337   ts->circular_buffer = 0;
4338   xfree (ts->user_name);
4339   ts->user_name = NULL;
4340   xfree (ts->notes);
4341   ts->notes = NULL;
4342   ts->start_time = ts->stop_time = 0;
4343
4344   while (*p++)
4345     {
4346       p1 = strchr (p, ':');
4347       if (p1 == NULL)
4348         error (_("Malformed trace status, at %s\n\
4349 Status line: '%s'\n"), p, line);
4350       p3 = strchr (p, ';');
4351       if (p3 == NULL)
4352         p3 = p + strlen (p);
4353       if (strncmp (p, stop_reason_names[trace_buffer_full], p1 - p) == 0)
4354         {
4355           p = unpack_varlen_hex (++p1, &val);
4356           ts->stop_reason = trace_buffer_full;
4357         }
4358       else if (strncmp (p, stop_reason_names[trace_never_run], p1 - p) == 0)
4359         {
4360           p = unpack_varlen_hex (++p1, &val);
4361           ts->stop_reason = trace_never_run;
4362         }
4363       else if (strncmp (p, stop_reason_names[tracepoint_passcount],
4364                         p1 - p) == 0)
4365         {
4366           p = unpack_varlen_hex (++p1, &val);
4367           ts->stop_reason = tracepoint_passcount;
4368           ts->stopping_tracepoint = val;
4369         }
4370       else if (strncmp (p, stop_reason_names[tstop_command], p1 - p) == 0)
4371         {
4372           p2 = strchr (++p1, ':');
4373           if (!p2 || p2 > p3)
4374             {
4375               /*older style*/
4376               p2 = p1;
4377             }
4378           else if (p2 != p1)
4379             {
4380               ts->stop_desc = xmalloc (strlen (line));
4381               end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
4382               ts->stop_desc[end] = '\0';
4383             }
4384           else
4385             ts->stop_desc = xstrdup ("");
4386
4387           p = unpack_varlen_hex (++p2, &val);
4388           ts->stop_reason = tstop_command;
4389         }
4390       else if (strncmp (p, stop_reason_names[trace_disconnected], p1 - p) == 0)
4391         {
4392           p = unpack_varlen_hex (++p1, &val);
4393           ts->stop_reason = trace_disconnected;
4394         }
4395       else if (strncmp (p, stop_reason_names[tracepoint_error], p1 - p) == 0)
4396         {
4397           p2 = strchr (++p1, ':');
4398           if (p2 != p1)
4399             {
4400               ts->stop_desc = xmalloc ((p2 - p1) / 2 + 1);
4401               end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
4402               ts->stop_desc[end] = '\0';
4403             }
4404           else
4405             ts->stop_desc = xstrdup ("");
4406
4407           p = unpack_varlen_hex (++p2, &val);
4408           ts->stopping_tracepoint = val;
4409           ts->stop_reason = tracepoint_error;
4410         }
4411       else if (strncmp (p, "tframes", p1 - p) == 0)
4412         {
4413           p = unpack_varlen_hex (++p1, &val);
4414           ts->traceframe_count = val;
4415         }
4416       else if (strncmp (p, "tcreated", p1 - p) == 0)
4417         {
4418           p = unpack_varlen_hex (++p1, &val);
4419           ts->traceframes_created = val;
4420         }
4421       else if (strncmp (p, "tfree", p1 - p) == 0)
4422         {
4423           p = unpack_varlen_hex (++p1, &val);
4424           ts->buffer_free = val;
4425         }
4426       else if (strncmp (p, "tsize", p1 - p) == 0)
4427         {
4428           p = unpack_varlen_hex (++p1, &val);
4429           ts->buffer_size = val;
4430         }
4431       else if (strncmp (p, "disconn", p1 - p) == 0)
4432         {
4433           p = unpack_varlen_hex (++p1, &val);
4434           ts->disconnected_tracing = val;
4435         }
4436       else if (strncmp (p, "circular", p1 - p) == 0)
4437         {
4438           p = unpack_varlen_hex (++p1, &val);
4439           ts->circular_buffer = val;
4440         }
4441       else if (strncmp (p, "starttime", p1 - p) == 0)
4442         {
4443           p = unpack_varlen_hex (++p1, &val);
4444           ts->start_time = val;
4445         }
4446       else if (strncmp (p, "stoptime", p1 - p) == 0)
4447         {
4448           p = unpack_varlen_hex (++p1, &val);
4449           ts->stop_time = val;
4450         }
4451       else if (strncmp (p, "username", p1 - p) == 0)
4452         {
4453           ++p1;
4454           ts->user_name = xmalloc (strlen (p) / 2);
4455           end = hex2bin (p1, (gdb_byte *) ts->user_name, (p3 - p1)  / 2);
4456           ts->user_name[end] = '\0';
4457           p = p3;
4458         }
4459       else if (strncmp (p, "notes", p1 - p) == 0)
4460         {
4461           ++p1;
4462           ts->notes = xmalloc (strlen (p) / 2);
4463           end = hex2bin (p1, (gdb_byte *) ts->notes, (p3 - p1) / 2);
4464           ts->notes[end] = '\0';
4465           p = p3;
4466         }
4467       else
4468         {
4469           /* Silently skip unknown optional info.  */
4470           p_temp = strchr (p1 + 1, ';');
4471           if (p_temp)
4472             p = p_temp;
4473           else
4474             /* Must be at the end.  */
4475             break;
4476         }
4477     }
4478 }
4479
4480 void
4481 parse_tracepoint_status (char *p, struct breakpoint *bp,
4482                          struct uploaded_tp *utp)
4483 {
4484   ULONGEST uval;
4485   struct tracepoint *tp = (struct tracepoint *) bp;
4486
4487   p = unpack_varlen_hex (p, &uval);
4488   if (tp)
4489     tp->base.hit_count += uval;
4490   else
4491     utp->hit_count += uval;
4492   p = unpack_varlen_hex (p + 1, &uval);
4493   if (tp)
4494     tp->traceframe_usage += uval;
4495   else
4496     utp->traceframe_usage += uval;
4497   /* Ignore any extra, allowing for future extensions.  */
4498 }
4499
4500 /* Given a line of text defining a part of a tracepoint, parse it into
4501    an "uploaded tracepoint".  */
4502
4503 void
4504 parse_tracepoint_definition (char *line, struct uploaded_tp **utpp)
4505 {
4506   char *p;
4507   char piece;
4508   ULONGEST num, addr, step, pass, orig_size, xlen, start;
4509   int enabled, end;
4510   enum bptype type;
4511   char *cond, *srctype, *buf;
4512   struct uploaded_tp *utp = NULL;
4513
4514   p = line;
4515   /* Both tracepoint and action definitions start with the same number
4516      and address sequence.  */
4517   piece = *p++;
4518   p = unpack_varlen_hex (p, &num);
4519   p++;  /* skip a colon */
4520   p = unpack_varlen_hex (p, &addr);
4521   p++;  /* skip a colon */
4522   if (piece == 'T')
4523     {
4524       enabled = (*p++ == 'E');
4525       p++;  /* skip a colon */
4526       p = unpack_varlen_hex (p, &step);
4527       p++;  /* skip a colon */
4528       p = unpack_varlen_hex (p, &pass);
4529       type = bp_tracepoint;
4530       cond = NULL;
4531       /* Thumb through optional fields.  */
4532       while (*p == ':')
4533         {
4534           p++;  /* skip a colon */
4535           if (*p == 'F')
4536             {
4537               type = bp_fast_tracepoint;
4538               p++;
4539               p = unpack_varlen_hex (p, &orig_size);
4540             }
4541           else if (*p == 'S')
4542             {
4543               type = bp_static_tracepoint;
4544               p++;
4545             }
4546           else if (*p == 'X')
4547             {
4548               p++;
4549               p = unpack_varlen_hex (p, &xlen);
4550               p++;  /* skip a comma */
4551               cond = (char *) xmalloc (2 * xlen + 1);
4552               strncpy (cond, p, 2 * xlen);
4553               cond[2 * xlen] = '\0';
4554               p += 2 * xlen;
4555             }
4556           else
4557             warning (_("Unrecognized char '%c' in tracepoint "
4558                        "definition, skipping rest"), *p);
4559         }
4560       utp = get_uploaded_tp (num, addr, utpp);
4561       utp->type = type;
4562       utp->enabled = enabled;
4563       utp->step = step;
4564       utp->pass = pass;
4565       utp->cond = cond;
4566     }
4567   else if (piece == 'A')
4568     {
4569       utp = get_uploaded_tp (num, addr, utpp);
4570       VEC_safe_push (char_ptr, utp->actions, xstrdup (p));
4571     }
4572   else if (piece == 'S')
4573     {
4574       utp = get_uploaded_tp (num, addr, utpp);
4575       VEC_safe_push (char_ptr, utp->step_actions, xstrdup (p));
4576     }
4577   else if (piece == 'Z')
4578     {
4579       /* Parse a chunk of source form definition.  */
4580       utp = get_uploaded_tp (num, addr, utpp);
4581       srctype = p;
4582       p = strchr (p, ':');
4583       p++;  /* skip a colon */
4584       p = unpack_varlen_hex (p, &start);
4585       p++;  /* skip a colon */
4586       p = unpack_varlen_hex (p, &xlen);
4587       p++;  /* skip a colon */
4588
4589       buf = alloca (strlen (line));
4590
4591       end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
4592       buf[end] = '\0';
4593
4594       if (strncmp (srctype, "at:", strlen ("at:")) == 0)
4595         utp->at_string = xstrdup (buf);
4596       else if (strncmp (srctype, "cond:", strlen ("cond:")) == 0)
4597         utp->cond_string = xstrdup (buf);
4598       else if (strncmp (srctype, "cmd:", strlen ("cmd:")) == 0)
4599         VEC_safe_push (char_ptr, utp->cmd_strings, xstrdup (buf));
4600     }
4601   else if (piece == 'V')
4602     {
4603       utp = get_uploaded_tp (num, addr, utpp);
4604
4605       parse_tracepoint_status (p, NULL, utp);
4606     }
4607   else
4608     {
4609       /* Don't error out, the target might be sending us optional
4610          info that we don't care about.  */
4611       warning (_("Unrecognized tracepoint piece '%c', ignoring"), piece);
4612     }
4613 }
4614
4615 /* Convert a textual description of a trace state variable into an
4616    uploaded object.  */
4617
4618 void
4619 parse_tsv_definition (char *line, struct uploaded_tsv **utsvp)
4620 {
4621   char *p, *buf;
4622   ULONGEST num, initval, builtin;
4623   int end;
4624   struct uploaded_tsv *utsv = NULL;
4625
4626   buf = alloca (strlen (line));
4627
4628   p = line;
4629   p = unpack_varlen_hex (p, &num);
4630   p++; /* skip a colon */
4631   p = unpack_varlen_hex (p, &initval);
4632   p++; /* skip a colon */
4633   p = unpack_varlen_hex (p, &builtin);
4634   p++; /* skip a colon */
4635   end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
4636   buf[end] = '\0';
4637
4638   utsv = get_uploaded_tsv (num, utsvp);
4639   utsv->initial_value = initval;
4640   utsv->builtin = builtin;
4641   utsv->name = xstrdup (buf);
4642 }
4643
4644 /* Close the trace file and generally clean up.  */
4645
4646 static void
4647 tfile_close (void)
4648 {
4649   int pid;
4650
4651   if (trace_fd < 0)
4652     return;
4653
4654   close (trace_fd);
4655   trace_fd = -1;
4656   xfree (trace_filename);
4657   trace_filename = NULL;
4658 }
4659
4660 static void
4661 tfile_files_info (struct target_ops *t)
4662 {
4663   printf_filtered ("\t`%s'\n", trace_filename);
4664 }
4665
4666 /* The trace status for a file is that tracing can never be run.  */
4667
4668 static int
4669 tfile_get_trace_status (struct trace_status *ts)
4670 {
4671   /* Other bits of trace status were collected as part of opening the
4672      trace files, so nothing to do here.  */
4673
4674   return -1;
4675 }
4676
4677 static void
4678 tfile_get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
4679 {
4680   /* Other bits of trace status were collected as part of opening the
4681      trace files, so nothing to do here.  */
4682 }
4683
4684 /* Given the position of a traceframe in the file, figure out what
4685    address the frame was collected at.  This would normally be the
4686    value of a collected PC register, but if not available, we
4687    improvise.  */
4688
4689 static CORE_ADDR
4690 tfile_get_traceframe_address (off_t tframe_offset)
4691 {
4692   CORE_ADDR addr = 0;
4693   short tpnum;
4694   struct tracepoint *tp;
4695   off_t saved_offset = cur_offset;
4696
4697   /* FIXME dig pc out of collected registers.  */
4698
4699   /* Fall back to using tracepoint address.  */
4700   lseek (trace_fd, tframe_offset, SEEK_SET);
4701   tfile_read ((gdb_byte *) &tpnum, 2);
4702   tpnum = (short) extract_signed_integer ((gdb_byte *) &tpnum, 2,
4703                                           gdbarch_byte_order
4704                                               (target_gdbarch ()));
4705
4706   tp = get_tracepoint_by_number_on_target (tpnum);
4707   /* FIXME this is a poor heuristic if multiple locations.  */
4708   if (tp && tp->base.loc)
4709     addr = tp->base.loc->address;
4710
4711   /* Restore our seek position.  */
4712   cur_offset = saved_offset;
4713   lseek (trace_fd, cur_offset, SEEK_SET);
4714   return addr;
4715 }
4716
4717 /* Given a type of search and some parameters, scan the collection of
4718    traceframes in the file looking for a match.  When found, return
4719    both the traceframe and tracepoint number, otherwise -1 for
4720    each.  */
4721
4722 static int
4723 tfile_trace_find (enum trace_find_type type, int num,
4724                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
4725 {
4726   short tpnum;
4727   int tfnum = 0, found = 0;
4728   unsigned int data_size;
4729   struct tracepoint *tp;
4730   off_t offset, tframe_offset;
4731   CORE_ADDR tfaddr;
4732
4733   if (num == -1)
4734     {
4735       if (tpp)
4736         *tpp = -1;
4737       return -1;
4738     }
4739
4740   lseek (trace_fd, trace_frames_offset, SEEK_SET);
4741   offset = trace_frames_offset;
4742   while (1)
4743     {
4744       tframe_offset = offset;
4745       tfile_read ((gdb_byte *) &tpnum, 2);
4746       tpnum = (short) extract_signed_integer ((gdb_byte *) &tpnum, 2,
4747                                               gdbarch_byte_order
4748                                                   (target_gdbarch ()));
4749       offset += 2;
4750       if (tpnum == 0)
4751         break;
4752       tfile_read ((gdb_byte *) &data_size, 4);
4753       data_size = (unsigned int) extract_unsigned_integer
4754                                      ((gdb_byte *) &data_size, 4,
4755                                       gdbarch_byte_order (target_gdbarch ()));
4756       offset += 4;
4757
4758       if (type == tfind_number)
4759         {
4760           /* Looking for a specific trace frame.  */
4761           if (tfnum == num)
4762             found = 1;
4763         }
4764       else
4765         {
4766           /* Start from the _next_ trace frame.  */
4767           if (tfnum > traceframe_number)
4768             {
4769               switch (type)
4770                 {
4771                 case tfind_pc:
4772                   tfaddr = tfile_get_traceframe_address (tframe_offset);
4773                   if (tfaddr == addr1)
4774                     found = 1;
4775                   break;
4776                 case tfind_tp:
4777                   tp = get_tracepoint (num);
4778                   if (tp && tpnum == tp->number_on_target)
4779                     found = 1;
4780                   break;
4781                 case tfind_range:
4782                   tfaddr = tfile_get_traceframe_address (tframe_offset);
4783                   if (addr1 <= tfaddr && tfaddr <= addr2)
4784                     found = 1;
4785                   break;
4786                 case tfind_outside:
4787                   tfaddr = tfile_get_traceframe_address (tframe_offset);
4788                   if (!(addr1 <= tfaddr && tfaddr <= addr2))
4789                     found = 1;
4790                   break;
4791                 default:
4792                   internal_error (__FILE__, __LINE__, _("unknown tfind type"));
4793                 }
4794             }
4795         }
4796
4797       if (found)
4798         {
4799           if (tpp)
4800             *tpp = tpnum;
4801           cur_offset = offset;
4802           cur_data_size = data_size;
4803
4804           return tfnum;
4805         }
4806       /* Skip past the traceframe's data.  */
4807       lseek (trace_fd, data_size, SEEK_CUR);
4808       offset += data_size;
4809       /* Update our own count of traceframes.  */
4810       ++tfnum;
4811     }
4812   /* Did not find what we were looking for.  */
4813   if (tpp)
4814     *tpp = -1;
4815   return -1;
4816 }
4817
4818 /* Prototype of the callback passed to tframe_walk_blocks.  */
4819 typedef int (*walk_blocks_callback_func) (char blocktype, void *data);
4820
4821 /* Callback for traceframe_walk_blocks, used to find a given block
4822    type in a traceframe.  */
4823
4824 static int
4825 match_blocktype (char blocktype, void *data)
4826 {
4827   char *wantedp = data;
4828
4829   if (*wantedp == blocktype)
4830     return 1;
4831
4832   return 0;
4833 }
4834
4835 /* Walk over all traceframe block starting at POS offset from
4836    CUR_OFFSET, and call CALLBACK for each block found, passing in DATA
4837    unmodified.  If CALLBACK returns true, this returns the position in
4838    the traceframe where the block is found, relative to the start of
4839    the traceframe (cur_offset).  Returns -1 if no callback call
4840    returned true, indicating that all blocks have been walked.  */
4841
4842 static int
4843 traceframe_walk_blocks (walk_blocks_callback_func callback,
4844                         int pos, void *data)
4845 {
4846   /* Iterate through a traceframe's blocks, looking for a block of the
4847      requested type.  */
4848
4849   lseek (trace_fd, cur_offset + pos, SEEK_SET);
4850   while (pos < cur_data_size)
4851     {
4852       unsigned short mlen;
4853       char block_type;
4854
4855       tfile_read ((gdb_byte *) &block_type, 1);
4856
4857       ++pos;
4858
4859       if ((*callback) (block_type, data))
4860         return pos;
4861
4862       switch (block_type)
4863         {
4864         case 'R':
4865           lseek (trace_fd, cur_offset + pos + trace_regblock_size, SEEK_SET);
4866           pos += trace_regblock_size;
4867           break;
4868         case 'M':
4869           lseek (trace_fd, cur_offset + pos + 8, SEEK_SET);
4870           tfile_read ((gdb_byte *) &mlen, 2);
4871           mlen = (unsigned short)
4872                 extract_unsigned_integer ((gdb_byte *) &mlen, 2,
4873                                           gdbarch_byte_order
4874                                               (target_gdbarch ()));
4875           lseek (trace_fd, mlen, SEEK_CUR);
4876           pos += (8 + 2 + mlen);
4877           break;
4878         case 'V':
4879           lseek (trace_fd, cur_offset + pos + 4 + 8, SEEK_SET);
4880           pos += (4 + 8);
4881           break;
4882         default:
4883           error (_("Unknown block type '%c' (0x%x) in trace frame"),
4884                  block_type, block_type);
4885           break;
4886         }
4887     }
4888
4889   return -1;
4890 }
4891
4892 /* Convenience wrapper around traceframe_walk_blocks.  Looks for the
4893    position offset of a block of type TYPE_WANTED in the current trace
4894    frame, starting at POS.  Returns -1 if no such block was found.  */
4895
4896 static int
4897 traceframe_find_block_type (char type_wanted, int pos)
4898 {
4899   return traceframe_walk_blocks (match_blocktype, pos, &type_wanted);
4900 }
4901
4902 /* Look for a block of saved registers in the traceframe, and get the
4903    requested register from it.  */
4904
4905 static void
4906 tfile_fetch_registers (struct target_ops *ops,
4907                        struct regcache *regcache, int regno)
4908 {
4909   struct gdbarch *gdbarch = get_regcache_arch (regcache);
4910   int offset, regn, regsize, pc_regno;
4911   gdb_byte *regs;
4912
4913   /* An uninitialized reg size says we're not going to be
4914      successful at getting register blocks.  */
4915   if (!trace_regblock_size)
4916     return;
4917
4918   regs = alloca (trace_regblock_size);
4919
4920   if (traceframe_find_block_type ('R', 0) >= 0)
4921     {
4922       tfile_read (regs, trace_regblock_size);
4923
4924       /* Assume the block is laid out in GDB register number order,
4925          each register with the size that it has in GDB.  */
4926       offset = 0;
4927       for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
4928         {
4929           regsize = register_size (gdbarch, regn);
4930           /* Make sure we stay within block bounds.  */
4931           if (offset + regsize >= trace_regblock_size)
4932             break;
4933           if (regcache_register_status (regcache, regn) == REG_UNKNOWN)
4934             {
4935               if (regno == regn)
4936                 {
4937                   regcache_raw_supply (regcache, regno, regs + offset);
4938                   break;
4939                 }
4940               else if (regno == -1)
4941                 {
4942                   regcache_raw_supply (regcache, regn, regs + offset);
4943                 }
4944             }
4945           offset += regsize;
4946         }
4947       return;
4948     }
4949
4950   /* We get here if no register data has been found.  Mark registers
4951      as unavailable.  */
4952   for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
4953     regcache_raw_supply (regcache, regn, NULL);
4954
4955   /* We can often usefully guess that the PC is going to be the same
4956      as the address of the tracepoint.  */
4957   pc_regno = gdbarch_pc_regnum (gdbarch);
4958   if (pc_regno >= 0 && (regno == -1 || regno == pc_regno))
4959     {
4960       struct tracepoint *tp = get_tracepoint (tracepoint_number);
4961
4962       if (tp && tp->base.loc)
4963         {
4964           /* But don't try to guess if tracepoint is multi-location...  */
4965           if (tp->base.loc->next)
4966             {
4967               warning (_("Tracepoint %d has multiple "
4968                          "locations, cannot infer $pc"),
4969                        tp->base.number);
4970               return;
4971             }
4972           /* ... or does while-stepping.  */
4973           if (tp->step_count > 0)
4974             {
4975               warning (_("Tracepoint %d does while-stepping, "
4976                          "cannot infer $pc"),
4977                        tp->base.number);
4978               return;
4979             }
4980
4981           store_unsigned_integer (regs, register_size (gdbarch, pc_regno),
4982                                   gdbarch_byte_order (gdbarch),
4983                                   tp->base.loc->address);
4984           regcache_raw_supply (regcache, pc_regno, regs);
4985         }
4986     }
4987 }
4988
4989 static LONGEST
4990 tfile_xfer_partial (struct target_ops *ops, enum target_object object,
4991                     const char *annex, gdb_byte *readbuf,
4992                     const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
4993 {
4994   /* We're only doing regular memory for now.  */
4995   if (object != TARGET_OBJECT_MEMORY)
4996     return -1;
4997
4998   if (readbuf == NULL)
4999     error (_("tfile_xfer_partial: trace file is read-only"));
5000
5001  if (traceframe_number != -1)
5002     {
5003       int pos = 0;
5004
5005       /* Iterate through the traceframe's blocks, looking for
5006          memory.  */
5007       while ((pos = traceframe_find_block_type ('M', pos)) >= 0)
5008         {
5009           ULONGEST maddr, amt;
5010           unsigned short mlen;
5011           enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
5012
5013           tfile_read ((gdb_byte *) &maddr, 8);
5014           maddr = extract_unsigned_integer ((gdb_byte *) &maddr, 8,
5015                                             byte_order);
5016           tfile_read ((gdb_byte *) &mlen, 2);
5017           mlen = (unsigned short)
5018             extract_unsigned_integer ((gdb_byte *) &mlen, 2, byte_order);
5019
5020           /* If the block includes the first part of the desired
5021              range, return as much it has; GDB will re-request the
5022              remainder, which might be in a different block of this
5023              trace frame.  */
5024           if (maddr <= offset && offset < (maddr + mlen))
5025             {
5026               amt = (maddr + mlen) - offset;
5027               if (amt > len)
5028                 amt = len;
5029
5030               if (maddr != offset)
5031                 lseek (trace_fd, offset - maddr, SEEK_CUR);
5032               tfile_read (readbuf, amt);
5033               return amt;
5034             }
5035
5036           /* Skip over this block.  */
5037           pos += (8 + 2 + mlen);
5038         }
5039     }
5040
5041   /* It's unduly pedantic to refuse to look at the executable for
5042      read-only pieces; so do the equivalent of readonly regions aka
5043      QTro packet.  */
5044   /* FIXME account for relocation at some point.  */
5045   if (exec_bfd)
5046     {
5047       asection *s;
5048       bfd_size_type size;
5049       bfd_vma vma;
5050
5051       for (s = exec_bfd->sections; s; s = s->next)
5052         {
5053           if ((s->flags & SEC_LOAD) == 0
5054               || (s->flags & SEC_READONLY) == 0)
5055             continue;
5056
5057           vma = s->vma;
5058           size = bfd_get_section_size (s);
5059           if (vma <= offset && offset < (vma + size))
5060             {
5061               ULONGEST amt;
5062
5063               amt = (vma + size) - offset;
5064               if (amt > len)
5065                 amt = len;
5066
5067               amt = bfd_get_section_contents (exec_bfd, s,
5068                                               readbuf, offset - vma, amt);
5069               return amt;
5070             }
5071         }
5072     }
5073
5074   /* Indicate failure to find the requested memory block.  */
5075   return -1;
5076 }
5077
5078 /* Iterate through the blocks of a trace frame, looking for a 'V'
5079    block with a matching tsv number.  */
5080
5081 static int
5082 tfile_get_trace_state_variable_value (int tsvnum, LONGEST *val)
5083 {
5084   int pos;
5085   int found = 0;
5086
5087   /* Iterate over blocks in current frame and find the last 'V'
5088      block in which tsv number is TSVNUM.  In one trace frame, there
5089      may be multiple 'V' blocks created for a given trace variable,
5090      and the last matched 'V' block contains the updated value.  */
5091   pos = 0;
5092   while ((pos = traceframe_find_block_type ('V', pos)) >= 0)
5093     {
5094       int vnum;
5095
5096       tfile_read ((gdb_byte *) &vnum, 4);
5097       vnum = (int) extract_signed_integer ((gdb_byte *) &vnum, 4,
5098                                            gdbarch_byte_order
5099                                            (target_gdbarch ()));
5100       if (tsvnum == vnum)
5101         {
5102           tfile_read ((gdb_byte *) val, 8);
5103           *val = extract_signed_integer ((gdb_byte *) val, 8,
5104                                          gdbarch_byte_order
5105                                          (target_gdbarch ()));
5106           found = 1;
5107         }
5108       pos += (4 + 8);
5109     }
5110
5111   return found;
5112 }
5113
5114 static int
5115 tfile_has_all_memory (struct target_ops *ops)
5116 {
5117   return 1;
5118 }
5119
5120 static int
5121 tfile_has_memory (struct target_ops *ops)
5122 {
5123   return 1;
5124 }
5125
5126 static int
5127 tfile_has_stack (struct target_ops *ops)
5128 {
5129   return traceframe_number != -1;
5130 }
5131
5132 static int
5133 tfile_has_registers (struct target_ops *ops)
5134 {
5135   return traceframe_number != -1;
5136 }
5137
5138 /* Callback for traceframe_walk_blocks.  Builds a traceframe_info
5139    object for the tfile target's current traceframe.  */
5140
5141 static int
5142 build_traceframe_info (char blocktype, void *data)
5143 {
5144   struct traceframe_info *info = data;
5145
5146   switch (blocktype)
5147     {
5148     case 'M':
5149       {
5150         struct mem_range *r;
5151         ULONGEST maddr;
5152         unsigned short mlen;
5153
5154         tfile_read ((gdb_byte *) &maddr, 8);
5155         maddr = extract_unsigned_integer ((gdb_byte *) &maddr, 8,
5156                                           gdbarch_byte_order
5157                                           (target_gdbarch ()));
5158         tfile_read ((gdb_byte *) &mlen, 2);
5159         mlen = (unsigned short)
5160                 extract_unsigned_integer ((gdb_byte *) &mlen,
5161                                           2, gdbarch_byte_order
5162                                           (target_gdbarch ()));
5163
5164         r = VEC_safe_push (mem_range_s, info->memory, NULL);
5165
5166         r->start = maddr;
5167         r->length = mlen;
5168         break;
5169       }
5170     case 'V':
5171     case 'R':
5172     case 'S':
5173       {
5174         break;
5175       }
5176     default:
5177       warning (_("Unhandled trace block type (%d) '%c ' "
5178                  "while building trace frame info."),
5179                blocktype, blocktype);
5180       break;
5181     }
5182
5183   return 0;
5184 }
5185
5186 static struct traceframe_info *
5187 tfile_traceframe_info (void)
5188 {
5189   struct traceframe_info *info = XCNEW (struct traceframe_info);
5190
5191   traceframe_walk_blocks (build_traceframe_info, 0, info);
5192   return info;
5193 }
5194
5195 static void
5196 init_tfile_ops (void)
5197 {
5198   tfile_ops.to_shortname = "tfile";
5199   tfile_ops.to_longname = "Local trace dump file";
5200   tfile_ops.to_doc
5201     = "Use a trace file as a target.  Specify the filename of the trace file.";
5202   tfile_ops.to_open = tfile_open;
5203   tfile_ops.to_close = tfile_close;
5204   tfile_ops.to_fetch_registers = tfile_fetch_registers;
5205   tfile_ops.to_xfer_partial = tfile_xfer_partial;
5206   tfile_ops.to_files_info = tfile_files_info;
5207   tfile_ops.to_get_trace_status = tfile_get_trace_status;
5208   tfile_ops.to_get_tracepoint_status = tfile_get_tracepoint_status;
5209   tfile_ops.to_trace_find = tfile_trace_find;
5210   tfile_ops.to_get_trace_state_variable_value
5211     = tfile_get_trace_state_variable_value;
5212   tfile_ops.to_stratum = process_stratum;
5213   tfile_ops.to_has_all_memory = tfile_has_all_memory;
5214   tfile_ops.to_has_memory = tfile_has_memory;
5215   tfile_ops.to_has_stack = tfile_has_stack;
5216   tfile_ops.to_has_registers = tfile_has_registers;
5217   tfile_ops.to_traceframe_info = tfile_traceframe_info;
5218   tfile_ops.to_magic = OPS_MAGIC;
5219 }
5220
5221 void
5222 free_current_marker (void *arg)
5223 {
5224   struct static_tracepoint_marker **marker_p = arg;
5225
5226   if (*marker_p != NULL)
5227     {
5228       release_static_tracepoint_marker (*marker_p);
5229       xfree (*marker_p);
5230     }
5231   else
5232     *marker_p = NULL;
5233 }
5234
5235 /* Given a line of text defining a static tracepoint marker, parse it
5236    into a "static tracepoint marker" object.  Throws an error is
5237    parsing fails.  If PP is non-null, it points to one past the end of
5238    the parsed marker definition.  */
5239
5240 void
5241 parse_static_tracepoint_marker_definition (char *line, char **pp,
5242                                            struct static_tracepoint_marker *marker)
5243 {
5244   char *p, *endp;
5245   ULONGEST addr;
5246   int end;
5247
5248   p = line;
5249   p = unpack_varlen_hex (p, &addr);
5250   p++;  /* skip a colon */
5251
5252   marker->gdbarch = target_gdbarch ();
5253   marker->address = (CORE_ADDR) addr;
5254
5255   endp = strchr (p, ':');
5256   if (endp == NULL)
5257     error (_("bad marker definition: %s"), line);
5258
5259   marker->str_id = xmalloc (endp - p + 1);
5260   end = hex2bin (p, (gdb_byte *) marker->str_id, (endp - p + 1) / 2);
5261   marker->str_id[end] = '\0';
5262
5263   p += 2 * end;
5264   p++;  /* skip a colon */
5265
5266   marker->extra = xmalloc (strlen (p) + 1);
5267   end = hex2bin (p, (gdb_byte *) marker->extra, strlen (p) / 2);
5268   marker->extra[end] = '\0';
5269
5270   if (pp)
5271     *pp = p;
5272 }
5273
5274 /* Release a static tracepoint marker's contents.  Note that the
5275    object itself isn't released here.  There objects are usually on
5276    the stack.  */
5277
5278 void
5279 release_static_tracepoint_marker (struct static_tracepoint_marker *marker)
5280 {
5281   xfree (marker->str_id);
5282   marker->str_id = NULL;
5283 }
5284
5285 /* Print MARKER to gdb_stdout.  */
5286
5287 static void
5288 print_one_static_tracepoint_marker (int count,
5289                                     struct static_tracepoint_marker *marker)
5290 {
5291   struct command_line *l;
5292   struct symbol *sym;
5293
5294   char wrap_indent[80];
5295   char extra_field_indent[80];
5296   struct ui_out *uiout = current_uiout;
5297   struct cleanup *bkpt_chain;
5298   VEC(breakpoint_p) *tracepoints;
5299
5300   struct symtab_and_line sal;
5301
5302   init_sal (&sal);
5303
5304   sal.pc = marker->address;
5305
5306   tracepoints = static_tracepoints_here (marker->address);
5307
5308   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "marker");
5309
5310   /* A counter field to help readability.  This is not a stable
5311      identifier!  */
5312   ui_out_field_int (uiout, "count", count);
5313
5314   ui_out_field_string (uiout, "marker-id", marker->str_id);
5315
5316   ui_out_field_fmt (uiout, "enabled", "%c",
5317                     !VEC_empty (breakpoint_p, tracepoints) ? 'y' : 'n');
5318   ui_out_spaces (uiout, 2);
5319
5320   strcpy (wrap_indent, "                                   ");
5321
5322   if (gdbarch_addr_bit (marker->gdbarch) <= 32)
5323     strcat (wrap_indent, "           ");
5324   else
5325     strcat (wrap_indent, "                   ");
5326
5327   strcpy (extra_field_indent, "         ");
5328
5329   ui_out_field_core_addr (uiout, "addr", marker->gdbarch, marker->address);
5330
5331   sal = find_pc_line (marker->address, 0);
5332   sym = find_pc_sect_function (marker->address, NULL);
5333   if (sym)
5334     {
5335       ui_out_text (uiout, "in ");
5336       ui_out_field_string (uiout, "func",
5337                            SYMBOL_PRINT_NAME (sym));
5338       ui_out_wrap_hint (uiout, wrap_indent);
5339       ui_out_text (uiout, " at ");
5340     }
5341   else
5342     ui_out_field_skip (uiout, "func");
5343
5344   if (sal.symtab != NULL)
5345     {
5346       ui_out_field_string (uiout, "file",
5347                            symtab_to_filename_for_display (sal.symtab));
5348       ui_out_text (uiout, ":");
5349
5350       if (ui_out_is_mi_like_p (uiout))
5351         {
5352           const char *fullname = symtab_to_fullname (sal.symtab);
5353
5354           ui_out_field_string (uiout, "fullname", fullname);
5355         }
5356       else
5357         ui_out_field_skip (uiout, "fullname");
5358
5359       ui_out_field_int (uiout, "line", sal.line);
5360     }
5361   else
5362     {
5363       ui_out_field_skip (uiout, "fullname");
5364       ui_out_field_skip (uiout, "line");
5365     }
5366
5367   ui_out_text (uiout, "\n");
5368   ui_out_text (uiout, extra_field_indent);
5369   ui_out_text (uiout, _("Data: \""));
5370   ui_out_field_string (uiout, "extra-data", marker->extra);
5371   ui_out_text (uiout, "\"\n");
5372
5373   if (!VEC_empty (breakpoint_p, tracepoints))
5374     {
5375       struct cleanup *cleanup_chain;
5376       int ix;
5377       struct breakpoint *b;
5378
5379       cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout,
5380                                                            "tracepoints-at");
5381
5382       ui_out_text (uiout, extra_field_indent);
5383       ui_out_text (uiout, _("Probed by static tracepoints: "));
5384       for (ix = 0; VEC_iterate(breakpoint_p, tracepoints, ix, b); ix++)
5385         {
5386           if (ix > 0)
5387             ui_out_text (uiout, ", ");
5388           ui_out_text (uiout, "#");
5389           ui_out_field_int (uiout, "tracepoint-id", b->number);
5390         }
5391
5392       do_cleanups (cleanup_chain);
5393
5394       if (ui_out_is_mi_like_p (uiout))
5395         ui_out_field_int (uiout, "number-of-tracepoints",
5396                           VEC_length(breakpoint_p, tracepoints));
5397       else
5398         ui_out_text (uiout, "\n");
5399     }
5400   VEC_free (breakpoint_p, tracepoints);
5401
5402   do_cleanups (bkpt_chain);
5403 }
5404
5405 static void
5406 info_static_tracepoint_markers_command (char *arg, int from_tty)
5407 {
5408   VEC(static_tracepoint_marker_p) *markers;
5409   struct cleanup *old_chain;
5410   struct static_tracepoint_marker *marker;
5411   struct ui_out *uiout = current_uiout;
5412   int i;
5413
5414   /* We don't have to check target_can_use_agent and agent's capability on
5415      static tracepoint here, in order to be compatible with older GDBserver.
5416      We don't check USE_AGENT is true or not, because static tracepoints
5417      don't work without in-process agent, so we don't bother users to type
5418      `set agent on' when to use static tracepoint.  */
5419
5420   old_chain
5421     = make_cleanup_ui_out_table_begin_end (uiout, 5, -1,
5422                                            "StaticTracepointMarkersTable");
5423
5424   ui_out_table_header (uiout, 7, ui_left, "counter", "Cnt");
5425
5426   ui_out_table_header (uiout, 40, ui_left, "marker-id", "ID");
5427
5428   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");
5429   if (gdbarch_addr_bit (target_gdbarch ()) <= 32)
5430     ui_out_table_header (uiout, 10, ui_left, "addr", "Address");
5431   else
5432     ui_out_table_header (uiout, 18, ui_left, "addr", "Address");
5433   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");
5434
5435   ui_out_table_body (uiout);
5436
5437   markers = target_static_tracepoint_markers_by_strid (NULL);
5438   make_cleanup (VEC_cleanup (static_tracepoint_marker_p), &markers);
5439
5440   for (i = 0;
5441        VEC_iterate (static_tracepoint_marker_p,
5442                     markers, i, marker);
5443        i++)
5444     {
5445       print_one_static_tracepoint_marker (i + 1, marker);
5446       release_static_tracepoint_marker (marker);
5447     }
5448
5449   do_cleanups (old_chain);
5450 }
5451
5452 /* The $_sdata convenience variable is a bit special.  We don't know
5453    for sure type of the value until we actually have a chance to fetch
5454    the data --- the size of the object depends on what has been
5455    collected.  We solve this by making $_sdata be an internalvar that
5456    creates a new value on access.  */
5457
5458 /* Return a new value with the correct type for the sdata object of
5459    the current trace frame.  Return a void value if there's no object
5460    available.  */
5461
5462 static struct value *
5463 sdata_make_value (struct gdbarch *gdbarch, struct internalvar *var,
5464                   void *ignore)
5465 {
5466   LONGEST size;
5467   gdb_byte *buf;
5468
5469   /* We need to read the whole object before we know its size.  */
5470   size = target_read_alloc (&current_target,
5471                             TARGET_OBJECT_STATIC_TRACE_DATA,
5472                             NULL, &buf);
5473   if (size >= 0)
5474     {
5475       struct value *v;
5476       struct type *type;
5477
5478       type = init_vector_type (builtin_type (gdbarch)->builtin_true_char,
5479                                size);
5480       v = allocate_value (type);
5481       memcpy (value_contents_raw (v), buf, size);
5482       xfree (buf);
5483       return v;
5484     }
5485   else
5486     return allocate_value (builtin_type (gdbarch)->builtin_void);
5487 }
5488
5489 #if !defined(HAVE_LIBEXPAT)
5490
5491 struct traceframe_info *
5492 parse_traceframe_info (const char *tframe_info)
5493 {
5494   static int have_warned;
5495
5496   if (!have_warned)
5497     {
5498       have_warned = 1;
5499       warning (_("Can not parse XML trace frame info; XML support "
5500                  "was disabled at compile time"));
5501     }
5502
5503   return NULL;
5504 }
5505
5506 #else /* HAVE_LIBEXPAT */
5507
5508 #include "xml-support.h"
5509
5510 /* Handle the start of a <memory> element.  */
5511
5512 static void
5513 traceframe_info_start_memory (struct gdb_xml_parser *parser,
5514                               const struct gdb_xml_element *element,
5515                               void *user_data, VEC(gdb_xml_value_s) *attributes)
5516 {
5517   struct traceframe_info *info = user_data;
5518   struct mem_range *r = VEC_safe_push (mem_range_s, info->memory, NULL);
5519   ULONGEST *start_p, *length_p;
5520
5521   start_p = xml_find_attribute (attributes, "start")->value;
5522   length_p = xml_find_attribute (attributes, "length")->value;
5523
5524   r->start = *start_p;
5525   r->length = *length_p;
5526 }
5527
5528 /* Discard the constructed trace frame info (if an error occurs).  */
5529
5530 static void
5531 free_result (void *p)
5532 {
5533   struct traceframe_info *result = p;
5534
5535   free_traceframe_info (result);
5536 }
5537
5538 /* The allowed elements and attributes for an XML memory map.  */
5539
5540 static const struct gdb_xml_attribute memory_attributes[] = {
5541   { "start", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
5542   { "length", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
5543   { NULL, GDB_XML_AF_NONE, NULL, NULL }
5544 };
5545
5546 static const struct gdb_xml_element traceframe_info_children[] = {
5547   { "memory", memory_attributes, NULL,
5548     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
5549     traceframe_info_start_memory, NULL },
5550   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
5551 };
5552
5553 static const struct gdb_xml_element traceframe_info_elements[] = {
5554   { "traceframe-info", NULL, traceframe_info_children, GDB_XML_EF_NONE,
5555     NULL, NULL },
5556   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
5557 };
5558
5559 /* Parse a traceframe-info XML document.  */
5560
5561 struct traceframe_info *
5562 parse_traceframe_info (const char *tframe_info)
5563 {
5564   struct traceframe_info *result;
5565   struct cleanup *back_to;
5566
5567   result = XCNEW (struct traceframe_info);
5568   back_to = make_cleanup (free_result, result);
5569
5570   if (gdb_xml_parse_quick (_("trace frame info"),
5571                            "traceframe-info.dtd", traceframe_info_elements,
5572                            tframe_info, result) == 0)
5573     {
5574       /* Parsed successfully, keep the result.  */
5575       discard_cleanups (back_to);
5576
5577       return result;
5578     }
5579
5580   do_cleanups (back_to);
5581   return NULL;
5582 }
5583
5584 #endif /* HAVE_LIBEXPAT */
5585
5586 /* Returns the traceframe_info object for the current traceframe.
5587    This is where we avoid re-fetching the object from the target if we
5588    already have it cached.  */
5589
5590 static struct traceframe_info *
5591 get_traceframe_info (void)
5592 {
5593   if (traceframe_info == NULL)
5594     traceframe_info = target_traceframe_info ();
5595
5596   return traceframe_info;
5597 }
5598
5599 /* If the target supports the query, return in RESULT the set of
5600    collected memory in the current traceframe, found within the LEN
5601    bytes range starting at MEMADDR.  Returns true if the target
5602    supports the query, otherwise returns false, and RESULT is left
5603    undefined.  */
5604
5605 int
5606 traceframe_available_memory (VEC(mem_range_s) **result,
5607                              CORE_ADDR memaddr, ULONGEST len)
5608 {
5609   struct traceframe_info *info = get_traceframe_info ();
5610
5611   if (info != NULL)
5612     {
5613       struct mem_range *r;
5614       int i;
5615
5616       *result = NULL;
5617
5618       for (i = 0; VEC_iterate (mem_range_s, info->memory, i, r); i++)
5619         if (mem_ranges_overlap (r->start, r->length, memaddr, len))
5620           {
5621             ULONGEST lo1, hi1, lo2, hi2;
5622             struct mem_range *nr;
5623
5624             lo1 = memaddr;
5625             hi1 = memaddr + len;
5626
5627             lo2 = r->start;
5628             hi2 = r->start + r->length;
5629
5630             nr = VEC_safe_push (mem_range_s, *result, NULL);
5631
5632             nr->start = max (lo1, lo2);
5633             nr->length = min (hi1, hi2) - nr->start;
5634           }
5635
5636       normalize_mem_ranges (*result);
5637       return 1;
5638     }
5639
5640   return 0;
5641 }
5642
5643 /* Implementation of `sdata' variable.  */
5644
5645 static const struct internalvar_funcs sdata_funcs =
5646 {
5647   sdata_make_value,
5648   NULL,
5649   NULL
5650 };
5651
5652 /* module initialization */
5653 void
5654 _initialize_tracepoint (void)
5655 {
5656   struct cmd_list_element *c;
5657
5658   /* Explicitly create without lookup, since that tries to create a
5659      value with a void typed value, and when we get here, gdbarch
5660      isn't initialized yet.  At this point, we're quite sure there
5661      isn't another convenience variable of the same name.  */
5662   create_internalvar_type_lazy ("_sdata", &sdata_funcs, NULL);
5663
5664   traceframe_number = -1;
5665   tracepoint_number = -1;
5666
5667   if (tracepoint_list.list == NULL)
5668     {
5669       tracepoint_list.listsize = 128;
5670       tracepoint_list.list = xmalloc
5671         (tracepoint_list.listsize * sizeof (struct memrange));
5672     }
5673   if (tracepoint_list.aexpr_list == NULL)
5674     {
5675       tracepoint_list.aexpr_listsize = 128;
5676       tracepoint_list.aexpr_list = xmalloc
5677         (tracepoint_list.aexpr_listsize * sizeof (struct agent_expr *));
5678     }
5679
5680   if (stepping_list.list == NULL)
5681     {
5682       stepping_list.listsize = 128;
5683       stepping_list.list = xmalloc
5684         (stepping_list.listsize * sizeof (struct memrange));
5685     }
5686
5687   if (stepping_list.aexpr_list == NULL)
5688     {
5689       stepping_list.aexpr_listsize = 128;
5690       stepping_list.aexpr_list = xmalloc
5691         (stepping_list.aexpr_listsize * sizeof (struct agent_expr *));
5692     }
5693
5694   add_info ("scope", scope_info,
5695             _("List the variables local to a scope"));
5696
5697   add_cmd ("tracepoints", class_trace, NULL,
5698            _("Tracing of program execution without stopping the program."),
5699            &cmdlist);
5700
5701   add_com ("tdump", class_trace, trace_dump_command,
5702            _("Print everything collected at the current tracepoint."));
5703
5704   add_com ("tsave", class_trace, trace_save_command, _("\
5705 Save the trace data to a file.\n\
5706 Use the '-ctf' option to save the data to CTF format.\n\
5707 Use the '-r' option to direct the target to save directly to the file,\n\
5708 using its own filesystem."));
5709
5710   c = add_com ("tvariable", class_trace, trace_variable_command,_("\
5711 Define a trace state variable.\n\
5712 Argument is a $-prefixed name, optionally followed\n\
5713 by '=' and an expression that sets the initial value\n\
5714 at the start of tracing."));
5715   set_cmd_completer (c, expression_completer);
5716
5717   add_cmd ("tvariable", class_trace, delete_trace_variable_command, _("\
5718 Delete one or more trace state variables.\n\
5719 Arguments are the names of the variables to delete.\n\
5720 If no arguments are supplied, delete all variables."), &deletelist);
5721   /* FIXME add a trace variable completer.  */
5722
5723   add_info ("tvariables", tvariables_info, _("\
5724 Status of trace state variables and their values.\n\
5725 "));
5726
5727   add_info ("static-tracepoint-markers",
5728             info_static_tracepoint_markers_command, _("\
5729 List target static tracepoints markers.\n\
5730 "));
5731
5732   add_prefix_cmd ("tfind", class_trace, trace_find_command, _("\
5733 Select a trace frame;\n\
5734 No argument means forward by one frame; '-' means backward by one frame."),
5735                   &tfindlist, "tfind ", 1, &cmdlist);
5736
5737   add_cmd ("outside", class_trace, trace_find_outside_command, _("\
5738 Select a trace frame whose PC is outside the given range (exclusive).\n\
5739 Usage: tfind outside addr1, addr2"),
5740            &tfindlist);
5741
5742   add_cmd ("range", class_trace, trace_find_range_command, _("\
5743 Select a trace frame whose PC is in the given range (inclusive).\n\
5744 Usage: tfind range addr1,addr2"),
5745            &tfindlist);
5746
5747   add_cmd ("line", class_trace, trace_find_line_command, _("\
5748 Select a trace frame by source line.\n\
5749 Argument can be a line number (with optional source file),\n\
5750 a function name, or '*' followed by an address.\n\
5751 Default argument is 'the next source line that was traced'."),
5752            &tfindlist);
5753
5754   add_cmd ("tracepoint", class_trace, trace_find_tracepoint_command, _("\
5755 Select a trace frame by tracepoint number.\n\
5756 Default is the tracepoint for the current trace frame."),
5757            &tfindlist);
5758
5759   add_cmd ("pc", class_trace, trace_find_pc_command, _("\
5760 Select a trace frame by PC.\n\
5761 Default is the current PC, or the PC of the current trace frame."),
5762            &tfindlist);
5763
5764   add_cmd ("end", class_trace, trace_find_end_command, _("\
5765 De-select any trace frame and resume 'live' debugging."),
5766            &tfindlist);
5767
5768   add_alias_cmd ("none", "end", class_trace, 0, &tfindlist);
5769
5770   add_cmd ("start", class_trace, trace_find_start_command,
5771            _("Select the first trace frame in the trace buffer."),
5772            &tfindlist);
5773
5774   add_com ("tstatus", class_trace, trace_status_command,
5775            _("Display the status of the current trace data collection."));
5776
5777   add_com ("tstop", class_trace, trace_stop_command, _("\
5778 Stop trace data collection.\n\
5779 Usage: tstop [ <notes> ... ]\n\
5780 Any arguments supplied are recorded with the trace as a stop reason and\n\
5781 reported by tstatus (if the target supports trace notes)."));
5782
5783   add_com ("tstart", class_trace, trace_start_command, _("\
5784 Start trace data collection.\n\
5785 Usage: tstart [ <notes> ... ]\n\
5786 Any arguments supplied are recorded with the trace as a note and\n\
5787 reported by tstatus (if the target supports trace notes)."));
5788
5789   add_com ("end", class_trace, end_actions_pseudocommand, _("\
5790 Ends a list of commands or actions.\n\
5791 Several GDB commands allow you to enter a list of commands or actions.\n\
5792 Entering \"end\" on a line by itself is the normal way to terminate\n\
5793 such a list.\n\n\
5794 Note: the \"end\" command cannot be used at the gdb prompt."));
5795
5796   add_com ("while-stepping", class_trace, while_stepping_pseudocommand, _("\
5797 Specify single-stepping behavior at a tracepoint.\n\
5798 Argument is number of instructions to trace in single-step mode\n\
5799 following the tracepoint.  This command is normally followed by\n\
5800 one or more \"collect\" commands, to specify what to collect\n\
5801 while single-stepping.\n\n\
5802 Note: this command can only be used in a tracepoint \"actions\" list."));
5803
5804   add_com_alias ("ws", "while-stepping", class_alias, 0);
5805   add_com_alias ("stepping", "while-stepping", class_alias, 0);
5806
5807   add_com ("collect", class_trace, collect_pseudocommand, _("\
5808 Specify one or more data items to be collected at a tracepoint.\n\
5809 Accepts a comma-separated list of (one or more) expressions.  GDB will\n\
5810 collect all data (variables, registers) referenced by that expression.\n\
5811 Also accepts the following special arguments:\n\
5812     $regs   -- all registers.\n\
5813     $args   -- all function arguments.\n\
5814     $locals -- all variables local to the block/function scope.\n\
5815     $_sdata -- static tracepoint data (ignored for non-static tracepoints).\n\
5816 Note: this command can only be used in a tracepoint \"actions\" list."));
5817
5818   add_com ("teval", class_trace, teval_pseudocommand, _("\
5819 Specify one or more expressions to be evaluated at a tracepoint.\n\
5820 Accepts a comma-separated list of (one or more) expressions.\n\
5821 The result of each evaluation will be discarded.\n\
5822 Note: this command can only be used in a tracepoint \"actions\" list."));
5823
5824   add_com ("actions", class_trace, trace_actions_command, _("\
5825 Specify the actions to be taken at a tracepoint.\n\
5826 Tracepoint actions may include collecting of specified data,\n\
5827 single-stepping, or enabling/disabling other tracepoints,\n\
5828 depending on target's capabilities."));
5829
5830   default_collect = xstrdup ("");
5831   add_setshow_string_cmd ("default-collect", class_trace,
5832                           &default_collect, _("\
5833 Set the list of expressions to collect by default"), _("\
5834 Show the list of expressions to collect by default"), NULL,
5835                           NULL, NULL,
5836                           &setlist, &showlist);
5837
5838   add_setshow_boolean_cmd ("disconnected-tracing", no_class,
5839                            &disconnected_tracing, _("\
5840 Set whether tracing continues after GDB disconnects."), _("\
5841 Show whether tracing continues after GDB disconnects."), _("\
5842 Use this to continue a tracing run even if GDB disconnects\n\
5843 or detaches from the target.  You can reconnect later and look at\n\
5844 trace data collected in the meantime."),
5845                            set_disconnected_tracing,
5846                            NULL,
5847                            &setlist,
5848                            &showlist);
5849
5850   add_setshow_boolean_cmd ("circular-trace-buffer", no_class,
5851                            &circular_trace_buffer, _("\
5852 Set target's use of circular trace buffer."), _("\
5853 Show target's use of circular trace buffer."), _("\
5854 Use this to make the trace buffer into a circular buffer,\n\
5855 which will discard traceframes (oldest first) instead of filling\n\
5856 up and stopping the trace run."),
5857                            set_circular_trace_buffer,
5858                            NULL,
5859                            &setlist,
5860                            &showlist);
5861
5862   add_setshow_zuinteger_unlimited_cmd ("trace-buffer-size", no_class,
5863                                        &trace_buffer_size, _("\
5864 Set requested size of trace buffer."), _("\
5865 Show requested size of trace buffer."), _("\
5866 Use this to choose a size for the trace buffer.  Some targets\n\
5867 may have fixed or limited buffer sizes.  Specifying \"unlimited\" or -1\n\
5868 disables any attempt to set the buffer size and lets the target choose."),
5869                                        set_trace_buffer_size, NULL,
5870                                        &setlist, &showlist);
5871
5872   add_setshow_string_cmd ("trace-user", class_trace,
5873                           &trace_user, _("\
5874 Set the user name to use for current and future trace runs"), _("\
5875 Show the user name to use for current and future trace runs"), NULL,
5876                           set_trace_user, NULL,
5877                           &setlist, &showlist);
5878
5879   add_setshow_string_cmd ("trace-notes", class_trace,
5880                           &trace_notes, _("\
5881 Set notes string to use for current and future trace runs"), _("\
5882 Show the notes string to use for current and future trace runs"), NULL,
5883                           set_trace_notes, NULL,
5884                           &setlist, &showlist);
5885
5886   add_setshow_string_cmd ("trace-stop-notes", class_trace,
5887                           &trace_stop_notes, _("\
5888 Set notes string to use for future tstop commands"), _("\
5889 Show the notes string to use for future tstop commands"), NULL,
5890                           set_trace_stop_notes, NULL,
5891                           &setlist, &showlist);
5892
5893   init_tfile_ops ();
5894
5895   add_target_with_completer (&tfile_ops, filename_completer);
5896 }