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