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