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