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