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