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