OSDN Git Service

8ec81a3a1d2289819c9b5b31da72788ff4a37ffe
[pf3gnuchains/pf3gnuchains3x.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 "remote.h"
36 extern int remote_supports_cond_tracepoints (void);
37 extern int remote_supports_fast_tracepoints (void);
38 extern char *unpack_varlen_hex (char *buff, ULONGEST *result);
39 #include "linespec.h"
40 #include "regcache.h"
41 #include "completer.h"
42 #include "block.h"
43 #include "dictionary.h"
44 #include "observer.h"
45 #include "user-regs.h"
46 #include "valprint.h"
47 #include "gdbcore.h"
48 #include "objfiles.h"
49
50 #include "ax.h"
51 #include "ax-gdb.h"
52
53 /* readline include files */
54 #include "readline/readline.h"
55 #include "readline/history.h"
56
57 /* readline defines this.  */
58 #undef savestring
59
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif
63
64 /* Maximum length of an agent aexpression.
65    This accounts for the fact that packets are limited to 400 bytes
66    (which includes everything -- including the checksum), and assumes
67    the worst case of maximum length for each of the pieces of a
68    continuation packet.
69
70    NOTE: expressions get mem2hex'ed otherwise this would be twice as
71    large.  (400 - 31)/2 == 184 */
72 #define MAX_AGENT_EXPR_LEN      184
73
74 /* A hook used to notify the UI of tracepoint operations.  */
75
76 void (*deprecated_trace_find_hook) (char *arg, int from_tty);
77 void (*deprecated_trace_start_stop_hook) (int start, int from_tty);
78
79 extern void (*deprecated_readline_begin_hook) (char *, ...);
80 extern char *(*deprecated_readline_hook) (char *);
81 extern void (*deprecated_readline_end_hook) (void);
82
83 /* GDB commands implemented in other modules:
84  */  
85
86 extern void output_command (char *, int);
87
88 /* 
89    Tracepoint.c:
90
91    This module defines the following debugger commands:
92    trace            : set a tracepoint on a function, line, or address.
93    info trace       : list all debugger-defined tracepoints.
94    delete trace     : delete one or more tracepoints.
95    enable trace     : enable one or more tracepoints.
96    disable trace    : disable one or more tracepoints.
97    actions          : specify actions to be taken at a tracepoint.
98    passcount        : specify a pass count for a tracepoint.
99    tstart           : start a trace experiment.
100    tstop            : stop a trace experiment.
101    tstatus          : query the status of a trace experiment.
102    tfind            : find a trace frame in the trace buffer.
103    tdump            : print everything collected at the current tracepoint.
104    save-tracepoints : write tracepoint setup into a file.
105
106    This module defines the following user-visible debugger variables:
107    $trace_frame : sequence number of trace frame currently being debugged.
108    $trace_line  : source line of trace frame currently being debugged.
109    $trace_file  : source file of trace frame currently being debugged.
110    $tracepoint  : tracepoint number of trace frame currently being debugged.
111  */
112
113
114 /* ======= Important global variables: ======= */
115
116 /* The list of all trace state variables.  We don't retain pointers to
117    any of these for any reason - API is by name or number only - so it
118    works to have a vector of objects.  */
119
120 typedef struct trace_state_variable tsv_s;
121 DEF_VEC_O(tsv_s);
122
123 static VEC(tsv_s) *tvariables;
124
125 /* The next integer to assign to a variable.  */
126
127 static int next_tsv_number = 1;
128
129 /* Number of last traceframe collected.  */
130 static int traceframe_number;
131
132 /* Tracepoint for last traceframe collected.  */
133 static int tracepoint_number;
134
135 /* Symbol for function for last traceframe collected */
136 static struct symbol *traceframe_fun;
137
138 /* Symtab and line for last traceframe collected */
139 static struct symtab_and_line traceframe_sal;
140
141 /* Tracing command lists */
142 static struct cmd_list_element *tfindlist;
143
144 /* List of expressions to collect by default at each tracepoint hit.  */
145 static char *default_collect = "";
146
147 static char *target_buf;
148 static long target_buf_size;
149   
150 /* ======= Important command functions: ======= */
151 static void trace_actions_command (char *, int);
152 static void trace_start_command (char *, int);
153 static void trace_stop_command (char *, int);
154 static void trace_status_command (char *, int);
155 static void trace_find_command (char *, int);
156 static void trace_find_pc_command (char *, int);
157 static void trace_find_tracepoint_command (char *, int);
158 static void trace_find_line_command (char *, int);
159 static void trace_find_range_command (char *, int);
160 static void trace_find_outside_command (char *, int);
161 static void tracepoint_save_command (char *, int);
162 static void trace_dump_command (char *, int);
163
164 /* support routines */
165
166 struct collection_list;
167 static void add_aexpr (struct collection_list *, struct agent_expr *);
168 static char *mem2hex (gdb_byte *, char *, int);
169 static void add_register (struct collection_list *collection,
170                           unsigned int regno);
171 static struct cleanup *make_cleanup_free_actions (struct breakpoint *t);
172 static void free_actions_list (char **actions_list);
173 static void free_actions_list_cleanup_wrapper (void *);
174
175 extern void _initialize_tracepoint (void);
176
177 /* Utility: returns true if "target remote" */
178 static int
179 target_is_remote (void)
180 {
181   if (current_target.to_shortname &&
182       (strcmp (current_target.to_shortname, "remote") == 0
183        || strcmp (current_target.to_shortname, "extended-remote") == 0))
184     return 1;
185   else
186     return 0;
187 }
188
189 /* Utility: generate error from an incoming stub packet.  */
190 static void
191 trace_error (char *buf)
192 {
193   if (*buf++ != 'E')
194     return;                     /* not an error msg */
195   switch (*buf)
196     {
197     case '1':                   /* malformed packet error */
198       if (*++buf == '0')        /*   general case: */
199         error (_("tracepoint.c: error in outgoing packet."));
200       else
201         error (_("tracepoint.c: error in outgoing packet at field #%ld."),
202                strtol (buf, NULL, 16));
203     case '2':
204       error (_("trace API error 0x%s."), ++buf);
205     default:
206       error (_("Target returns error code '%s'."), buf);
207     }
208 }
209
210 /* Utility: wait for reply from stub, while accepting "O" packets.  */
211 static char *
212 remote_get_noisy_reply (char **buf_p,
213                         long *sizeof_buf)
214 {
215   do                            /* Loop on reply from remote stub.  */
216     {
217       char *buf;
218       QUIT;                     /* allow user to bail out with ^C */
219       getpkt (buf_p, sizeof_buf, 0);
220       buf = *buf_p;
221       if (buf[0] == 0)
222         error (_("Target does not support this command."));
223       else if (buf[0] == 'E')
224         trace_error (buf);
225       else if (buf[0] == 'O' &&
226                buf[1] != 'K')
227         remote_console_output (buf + 1);        /* 'O' message from stub */
228       else
229         return buf;             /* here's the actual reply */
230     }
231   while (1);
232 }
233
234 /* Set traceframe number to NUM.  */
235 static void
236 set_traceframe_num (int num)
237 {
238   traceframe_number = num;
239   set_internalvar_integer (lookup_internalvar ("trace_frame"), num);
240 }
241
242 /* Set tracepoint number to NUM.  */
243 static void
244 set_tracepoint_num (int num)
245 {
246   tracepoint_number = num;
247   set_internalvar_integer (lookup_internalvar ("tracepoint"), num);
248 }
249
250 /* Set externally visible debug variables for querying/printing
251    the traceframe context (line, function, file) */
252
253 static void
254 set_traceframe_context (struct frame_info *trace_frame)
255 {
256   CORE_ADDR trace_pc;
257
258   if (trace_frame == NULL)              /* Cease debugging any trace buffers.  */
259     {
260       traceframe_fun = 0;
261       traceframe_sal.pc = traceframe_sal.line = 0;
262       traceframe_sal.symtab = NULL;
263       clear_internalvar (lookup_internalvar ("trace_func"));
264       clear_internalvar (lookup_internalvar ("trace_file"));
265       set_internalvar_integer (lookup_internalvar ("trace_line"), -1);
266       return;
267     }
268
269   /* Save as globals for internal use.  */
270   trace_pc = get_frame_pc (trace_frame);
271   traceframe_sal = find_pc_line (trace_pc, 0);
272   traceframe_fun = find_pc_function (trace_pc);
273
274   /* Save linenumber as "$trace_line", a debugger variable visible to
275      users.  */
276   set_internalvar_integer (lookup_internalvar ("trace_line"),
277                            traceframe_sal.line);
278
279   /* Save func name as "$trace_func", a debugger variable visible to
280      users.  */
281   if (traceframe_fun == NULL
282       || SYMBOL_LINKAGE_NAME (traceframe_fun) == NULL)
283     clear_internalvar (lookup_internalvar ("trace_func"));
284   else
285     set_internalvar_string (lookup_internalvar ("trace_func"),
286                             SYMBOL_LINKAGE_NAME (traceframe_fun));
287
288   /* Save file name as "$trace_file", a debugger variable visible to
289      users.  */
290   if (traceframe_sal.symtab == NULL
291       || traceframe_sal.symtab->filename == NULL)
292     clear_internalvar (lookup_internalvar ("trace_file"));
293   else
294     set_internalvar_string (lookup_internalvar ("trace_file"),
295                             traceframe_sal.symtab->filename);
296 }
297
298 /* Create a new trace state variable with the given name.  */
299
300 struct trace_state_variable *
301 create_trace_state_variable (const char *name)
302 {
303   struct trace_state_variable tsv;
304
305   memset (&tsv, 0, sizeof (tsv));
306   tsv.name = name;
307   tsv.number = next_tsv_number++;
308   return VEC_safe_push (tsv_s, tvariables, &tsv);
309 }
310
311 /* Look for a trace state variable of the given name.  */
312
313 struct trace_state_variable *
314 find_trace_state_variable (const char *name)
315 {
316   struct trace_state_variable *tsv;
317   int ix;
318
319   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
320     if (strcmp (name, tsv->name) == 0)
321       return tsv;
322
323   return NULL;
324 }
325
326 void
327 delete_trace_state_variable (const char *name)
328 {
329   struct trace_state_variable *tsv;
330   int ix;
331
332   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
333     if (strcmp (name, tsv->name) == 0)
334       {
335         VEC_unordered_remove (tsv_s, tvariables, ix);
336         return;
337       }
338
339   warning (_("No trace variable named \"$%s\", not deleting"), name);
340 }
341
342 /* The 'tvariable' command collects a name and optional expression to
343    evaluate into an initial value.  */
344
345 void
346 trace_variable_command (char *args, int from_tty)
347 {
348   struct expression *expr;
349   struct cleanup *old_chain;
350   struct internalvar *intvar = NULL;
351   LONGEST initval = 0;
352   struct trace_state_variable *tsv;
353
354   if (!args || !*args)
355     error_no_arg (_("trace state variable name"));
356
357   /* All the possible valid arguments are expressions.  */
358   expr = parse_expression (args);
359   old_chain = make_cleanup (free_current_contents, &expr);
360
361   if (expr->nelts == 0)
362     error (_("No expression?"));
363
364   /* Only allow two syntaxes; "$name" and "$name=value".  */
365   if (expr->elts[0].opcode == OP_INTERNALVAR)
366     {
367       intvar = expr->elts[1].internalvar;
368     }
369   else if (expr->elts[0].opcode == BINOP_ASSIGN
370            && expr->elts[1].opcode == OP_INTERNALVAR)
371     {
372       intvar = expr->elts[2].internalvar;
373       initval = value_as_long (evaluate_subexpression_type (expr, 4));
374     }
375   else
376     error (_("Syntax must be $NAME [ = EXPR ]"));
377
378   if (!intvar)
379     error (_("No name given"));
380
381   if (strlen (internalvar_name (intvar)) <= 0)
382     error (_("Must supply a non-empty variable name"));
383
384   /* If the variable already exists, just change its initial value.  */
385   tsv = find_trace_state_variable (internalvar_name (intvar));
386   if (tsv)
387     {
388       tsv->initial_value = initval;
389       printf_filtered (_("Trace state variable $%s now has initial value %s.\n"),
390                        tsv->name, plongest (tsv->initial_value));
391       return;
392     }
393
394   /* Create a new variable.  */
395   tsv = create_trace_state_variable (internalvar_name (intvar));
396   tsv->initial_value = initval;
397
398   printf_filtered (_("Trace state variable $%s created, with initial value %s.\n"),
399                    tsv->name, plongest (tsv->initial_value));
400
401   do_cleanups (old_chain);
402 }
403
404 void
405 delete_trace_variable_command (char *args, int from_tty)
406 {
407   int i, ix;
408   char **argv;
409   struct cleanup *back_to;
410   struct trace_state_variable *tsv;
411
412   if (args == NULL)
413     {
414       if (query (_("Delete all trace state variables? ")))
415         VEC_free (tsv_s, tvariables);
416       dont_repeat ();
417       return;
418     }
419
420   argv = gdb_buildargv (args);
421   back_to = make_cleanup_freeargv (argv);
422
423   for (i = 0; argv[i] != NULL; i++)
424     {
425       if (*argv[i] == '$')
426         delete_trace_state_variable (argv[i] + 1);
427       else
428         warning (_("Name \"%s\" not prefixed with '$', ignoring"), argv[i]);
429     }
430
431   do_cleanups (back_to);
432
433   dont_repeat ();
434 }
435
436 /* List all the trace state variables.  */
437
438 static void
439 tvariables_info (char *args, int from_tty)
440 {
441   struct trace_state_variable *tsv;
442   int ix;
443   char *reply;
444   ULONGEST tval;
445
446   if (target_is_remote ())
447     {
448       char buf[20];
449
450       for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
451         {
452           /* We don't know anything about the value until we get a
453              valid packet.  */
454           tsv->value_known = 0;
455           sprintf (buf, "qTV:%x", tsv->number);
456           putpkt (buf);
457           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
458           if (reply && *reply)
459             {
460               if (*reply == 'V')
461                 {
462                   unpack_varlen_hex (reply + 1, &tval);
463                   tsv->value = (LONGEST) tval;
464                   tsv->value_known = 1;
465                 }
466               /* FIXME say anything about oddball replies? */
467             }
468         }
469     }
470
471   if (VEC_length (tsv_s, tvariables) == 0)
472     {
473       printf_filtered (_("No trace state variables.\n"));
474       return;
475     }
476
477   printf_filtered (_("Name\t\t  Initial\tCurrent\n"));
478
479   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
480     {
481       printf_filtered ("$%s", tsv->name);
482       print_spaces_filtered (17 - strlen (tsv->name), gdb_stdout);
483       printf_filtered ("%s ", plongest (tsv->initial_value));
484       print_spaces_filtered (11 - strlen (plongest (tsv->initial_value)), gdb_stdout);
485       if (tsv->value_known)
486         printf_filtered ("  %s", plongest (tsv->value));
487       else if (trace_running_p || traceframe_number >= 0)
488         /* The value is/was defined, but we don't have it.  */
489         printf_filtered (_("  <unknown>"));
490       else
491         /* It is not meaningful to ask about the value.  */
492         printf_filtered (_("  <undefined>"));
493       printf_filtered ("\n");
494     }
495 }
496
497 /* ACTIONS functions: */
498
499 /* Prototypes for action-parsing utility commands  */
500 static void read_actions (struct breakpoint *);
501
502 /* The three functions:
503    collect_pseudocommand, 
504    while_stepping_pseudocommand, and 
505    end_actions_pseudocommand
506    are placeholders for "commands" that are actually ONLY to be used
507    within a tracepoint action list.  If the actual function is ever called,
508    it means that somebody issued the "command" at the top level,
509    which is always an error.  */
510
511 void
512 end_actions_pseudocommand (char *args, int from_tty)
513 {
514   error (_("This command cannot be used at the top level."));
515 }
516
517 void
518 while_stepping_pseudocommand (char *args, int from_tty)
519 {
520   error (_("This command can only be used in a tracepoint actions list."));
521 }
522
523 static void
524 collect_pseudocommand (char *args, int from_tty)
525 {
526   error (_("This command can only be used in a tracepoint actions list."));
527 }
528
529 static void
530 teval_pseudocommand (char *args, int from_tty)
531 {
532   error (_("This command can only be used in a tracepoint actions list."));
533 }
534
535 /* Enter a list of actions for a tracepoint.  */
536 static void
537 trace_actions_command (char *args, int from_tty)
538 {
539   struct breakpoint *t;
540   char tmpbuf[128];
541   char *end_msg = "End with a line saying just \"end\".";
542
543   t = get_tracepoint_by_number (&args, 0, 1);
544   if (t)
545     {
546       sprintf (tmpbuf, "Enter actions for tracepoint %d, one per line.",
547                t->number);
548
549       if (from_tty)
550         {
551           if (deprecated_readline_begin_hook)
552             (*deprecated_readline_begin_hook) ("%s  %s\n", tmpbuf, end_msg);
553           else if (input_from_terminal_p ())
554             printf_filtered ("%s\n%s\n", tmpbuf, end_msg);
555         }
556
557       free_actions (t);
558       t->step_count = 0;        /* read_actions may set this */
559       read_actions (t);
560
561       if (deprecated_readline_end_hook)
562         (*deprecated_readline_end_hook) ();
563       /* tracepoints_changed () */
564     }
565   /* else just return */
566 }
567
568 /* worker function */
569 static void
570 read_actions (struct breakpoint *t)
571 {
572   char *line;
573   char *prompt1 = "> ", *prompt2 = "  > ";
574   char *prompt = prompt1;
575   enum actionline_type linetype;
576   extern FILE *instream;
577   struct action_line *next = NULL, *temp;
578   struct cleanup *old_chain;
579
580   /* Control-C quits instantly if typed while in this loop
581      since it should not wait until the user types a newline.  */
582   immediate_quit++;
583   /* FIXME: kettenis/20010823: Something is wrong here.  In this file
584      STOP_SIGNAL is never defined.  So this code has been left out, at
585      least for quite a while now.  Replacing STOP_SIGNAL with SIGTSTP
586      leads to compilation failures since the variable job_control
587      isn't declared.  Leave this alone for now.  */
588 #ifdef STOP_SIGNAL
589   if (job_control)
590     signal (STOP_SIGNAL, handle_stop_sig);
591 #endif
592   old_chain = make_cleanup_free_actions (t);
593   while (1)
594     {
595       /* Make sure that all output has been output.  Some machines may
596          let you get away with leaving out some of the gdb_flush, but
597          not all.  */
598       wrap_here ("");
599       gdb_flush (gdb_stdout);
600       gdb_flush (gdb_stderr);
601
602       if (deprecated_readline_hook && instream == NULL)
603         line = (*deprecated_readline_hook) (prompt);
604       else if (instream == stdin && ISATTY (instream))
605         {
606           line = gdb_readline_wrapper (prompt);
607           if (line && *line)    /* add it to command history */
608             add_history (line);
609         }
610       else
611         line = gdb_readline (0);
612
613       if (!line)
614         {
615           line = xstrdup ("end");
616           printf_filtered ("end\n");
617         }
618       
619       linetype = validate_actionline (&line, t);
620       if (linetype == BADLINE)
621         continue;               /* already warned -- collect another line */
622
623       temp = xmalloc (sizeof (struct action_line));
624       temp->next = NULL;
625       temp->action = line;
626
627       if (next == NULL)         /* first action for this tracepoint? */
628         t->actions = next = temp;
629       else
630         {
631           next->next = temp;
632           next = temp;
633         }
634
635       if (linetype == STEPPING) /* begin "while-stepping" */
636         {
637           if (prompt == prompt2)
638             {
639               warning (_("Already processing 'while-stepping'"));
640               continue;
641             }
642           else
643             prompt = prompt2;   /* change prompt for stepping actions */
644         }
645       else if (linetype == END)
646         {
647           if (prompt == prompt2)
648             {
649               prompt = prompt1; /* end of single-stepping actions */
650             }
651           else
652             {                   /* end of actions */
653               if (t->actions->next == NULL)
654                 {
655                   /* An "end" all by itself with no other actions
656                      means this tracepoint has no actions.
657                      Discard empty list.  */
658                   free_actions (t);
659                 }
660               break;
661             }
662         }
663     }
664 #ifdef STOP_SIGNAL
665   if (job_control)
666     signal (STOP_SIGNAL, SIG_DFL);
667 #endif
668   immediate_quit--;
669   discard_cleanups (old_chain);
670 }
671
672 /* worker function */
673 enum actionline_type
674 validate_actionline (char **line, struct breakpoint *t)
675 {
676   struct cmd_list_element *c;
677   struct expression *exp = NULL;
678   struct cleanup *old_chain = NULL;
679   char *p;
680
681   /* if EOF is typed, *line is NULL */
682   if (*line == NULL)
683     return END;
684
685   for (p = *line; isspace ((int) *p);)
686     p++;
687
688   /* Symbol lookup etc.  */
689   if (*p == '\0')       /* empty line: just prompt for another line.  */
690     return BADLINE;
691
692   if (*p == '#')                /* comment line */
693     return GENERIC;
694
695   c = lookup_cmd (&p, cmdlist, "", -1, 1);
696   if (c == 0)
697     {
698       warning (_("'%s' is not an action that I know, or is ambiguous."), 
699                p);
700       return BADLINE;
701     }
702
703   if (cmd_cfunc_eq (c, collect_pseudocommand))
704     {
705       struct agent_expr *aexpr;
706       struct agent_reqs areqs;
707
708       do
709         {                       /* repeat over a comma-separated list */
710           QUIT;                 /* allow user to bail out with ^C */
711           while (isspace ((int) *p))
712             p++;
713
714           if (*p == '$')        /* look for special pseudo-symbols */
715             {
716               if ((0 == strncasecmp ("reg", p + 1, 3)) ||
717                   (0 == strncasecmp ("arg", p + 1, 3)) ||
718                   (0 == strncasecmp ("loc", p + 1, 3)))
719                 {
720                   p = strchr (p, ',');
721                   continue;
722                 }
723               /* else fall thru, treat p as an expression and parse it!  */
724             }
725           exp = parse_exp_1 (&p, block_for_pc (t->loc->address), 1);
726           old_chain = make_cleanup (free_current_contents, &exp);
727
728           if (exp->elts[0].opcode == OP_VAR_VALUE)
729             {
730               if (SYMBOL_CLASS (exp->elts[2].symbol) == LOC_CONST)
731                 {
732                   warning (_("constant %s (value %ld) will not be collected."),
733                            SYMBOL_PRINT_NAME (exp->elts[2].symbol),
734                            SYMBOL_VALUE (exp->elts[2].symbol));
735                   return BADLINE;
736                 }
737               else if (SYMBOL_CLASS (exp->elts[2].symbol) == LOC_OPTIMIZED_OUT)
738                 {
739                   warning (_("%s is optimized away and cannot be collected."),
740                            SYMBOL_PRINT_NAME (exp->elts[2].symbol));
741                   return BADLINE;
742                 }
743             }
744
745           /* We have something to collect, make sure that the expr to
746              bytecode translator can handle it and that it's not too
747              long.  */
748           aexpr = gen_trace_for_expr (t->loc->address, exp);
749           make_cleanup_free_agent_expr (aexpr);
750
751           if (aexpr->len > MAX_AGENT_EXPR_LEN)
752             error (_("expression too complicated, try simplifying"));
753
754           ax_reqs (aexpr, &areqs);
755           (void) make_cleanup (xfree, areqs.reg_mask);
756
757           if (areqs.flaw != agent_flaw_none)
758             error (_("malformed expression"));
759
760           if (areqs.min_height < 0)
761             error (_("gdb: Internal error: expression has min height < 0"));
762
763           if (areqs.max_height > 20)
764             error (_("expression too complicated, try simplifying"));
765
766           do_cleanups (old_chain);
767         }
768       while (p && *p++ == ',');
769       return GENERIC;
770     }
771   else if (cmd_cfunc_eq (c, teval_pseudocommand))
772     {
773       struct agent_expr *aexpr;
774
775       do
776         {                       /* repeat over a comma-separated list */
777           QUIT;                 /* allow user to bail out with ^C */
778           while (isspace ((int) *p))
779             p++;
780
781           /* Only expressions are allowed for this action.  */
782           exp = parse_exp_1 (&p, block_for_pc (t->loc->address), 1);
783           old_chain = make_cleanup (free_current_contents, &exp);
784
785           /* We have something to evaluate, make sure that the expr to
786              bytecode translator can handle it and that it's not too
787              long.  */
788           aexpr = gen_eval_for_expr (t->loc->address, exp);
789           make_cleanup_free_agent_expr (aexpr);
790
791           if (aexpr->len > MAX_AGENT_EXPR_LEN)
792             error (_("expression too complicated, try simplifying"));
793
794           do_cleanups (old_chain);
795         }
796       while (p && *p++ == ',');
797       return GENERIC;
798     }
799   else if (cmd_cfunc_eq (c, while_stepping_pseudocommand))
800     {
801       char *steparg;            /* in case warning is necessary */
802
803       while (isspace ((int) *p))
804         p++;
805       steparg = p;
806
807       if (*p == '\0' ||
808           (t->step_count = strtol (p, &p, 0)) == 0)
809         {
810           warning (_("'%s': bad step-count; command ignored."), *line);
811           return BADLINE;
812         }
813       return STEPPING;
814     }
815   else if (cmd_cfunc_eq (c, end_actions_pseudocommand))
816     return END;
817   else
818     {
819       warning (_("'%s' is not a supported tracepoint action."), *line);
820       return BADLINE;
821     }
822 }
823
824 /* worker function */
825 void
826 free_actions (struct breakpoint *t)
827 {
828   struct action_line *line, *next;
829
830   for (line = t->actions; line; line = next)
831     {
832       next = line->next;
833       if (line->action)
834         xfree (line->action);
835       xfree (line);
836     }
837   t->actions = NULL;
838 }
839
840 static void
841 do_free_actions_cleanup (void *t)
842 {
843   free_actions (t);
844 }
845
846 static struct cleanup *
847 make_cleanup_free_actions (struct breakpoint *t)
848 {
849   return make_cleanup (do_free_actions_cleanup, t);
850 }
851
852 enum {
853   memrange_absolute = -1
854 };
855
856 struct memrange
857 {
858   int type;             /* memrange_absolute for absolute memory range,
859                            else basereg number */
860   bfd_signed_vma start;
861   bfd_signed_vma end;
862 };
863
864 struct collection_list
865   {
866     unsigned char regs_mask[32];        /* room for up to 256 regs */
867     long listsize;
868     long next_memrange;
869     struct memrange *list;
870     long aexpr_listsize;        /* size of array pointed to by expr_list elt */
871     long next_aexpr_elt;
872     struct agent_expr **aexpr_list;
873
874   }
875 tracepoint_list, stepping_list;
876
877 /* MEMRANGE functions: */
878
879 static int memrange_cmp (const void *, const void *);
880
881 /* compare memranges for qsort */
882 static int
883 memrange_cmp (const void *va, const void *vb)
884 {
885   const struct memrange *a = va, *b = vb;
886
887   if (a->type < b->type)
888     return -1;
889   if (a->type > b->type)
890     return 1;
891   if (a->type == memrange_absolute)
892     {
893       if ((bfd_vma) a->start < (bfd_vma) b->start)
894         return -1;
895       if ((bfd_vma) a->start > (bfd_vma) b->start)
896         return 1;
897     }
898   else
899     {
900       if (a->start < b->start)
901         return -1;
902       if (a->start > b->start)
903         return 1;
904     }
905   return 0;
906 }
907
908 /* Sort the memrange list using qsort, and merge adjacent memranges.  */
909 static void
910 memrange_sortmerge (struct collection_list *memranges)
911 {
912   int a, b;
913
914   qsort (memranges->list, memranges->next_memrange,
915          sizeof (struct memrange), memrange_cmp);
916   if (memranges->next_memrange > 0)
917     {
918       for (a = 0, b = 1; b < memranges->next_memrange; b++)
919         {
920           if (memranges->list[a].type == memranges->list[b].type &&
921               memranges->list[b].start - memranges->list[a].end <=
922               MAX_REGISTER_SIZE)
923             {
924               /* memrange b starts before memrange a ends; merge them.  */
925               if (memranges->list[b].end > memranges->list[a].end)
926                 memranges->list[a].end = memranges->list[b].end;
927               continue;         /* next b, same a */
928             }
929           a++;                  /* next a */
930           if (a != b)
931             memcpy (&memranges->list[a], &memranges->list[b],
932                     sizeof (struct memrange));
933         }
934       memranges->next_memrange = a + 1;
935     }
936 }
937
938 /* Add a register to a collection list.  */
939 static void
940 add_register (struct collection_list *collection, unsigned int regno)
941 {
942   if (info_verbose)
943     printf_filtered ("collect register %d\n", regno);
944   if (regno >= (8 * sizeof (collection->regs_mask)))
945     error (_("Internal: register number %d too large for tracepoint"),
946            regno);
947   collection->regs_mask[regno / 8] |= 1 << (regno % 8);
948 }
949
950 /* Add a memrange to a collection list */
951 static void
952 add_memrange (struct collection_list *memranges, 
953               int type, bfd_signed_vma base,
954               unsigned long len)
955 {
956   if (info_verbose)
957     {
958       printf_filtered ("(%d,", type);
959       printf_vma (base);
960       printf_filtered (",%ld)\n", len);
961     }
962
963   /* type: memrange_absolute == memory, other n == basereg */
964   memranges->list[memranges->next_memrange].type = type;
965   /* base: addr if memory, offset if reg relative.  */
966   memranges->list[memranges->next_memrange].start = base;
967   /* len: we actually save end (base + len) for convenience */
968   memranges->list[memranges->next_memrange].end = base + len;
969   memranges->next_memrange++;
970   if (memranges->next_memrange >= memranges->listsize)
971     {
972       memranges->listsize *= 2;
973       memranges->list = xrealloc (memranges->list,
974                                   memranges->listsize);
975     }
976
977   if (type != memrange_absolute)                /* Better collect the base register!  */
978     add_register (memranges, type);
979 }
980
981 /* Add a symbol to a collection list.  */
982 static void
983 collect_symbol (struct collection_list *collect, 
984                 struct symbol *sym,
985                 struct gdbarch *gdbarch,
986                 long frame_regno, long frame_offset,
987                 CORE_ADDR scope)
988 {
989   unsigned long len;
990   unsigned int reg;
991   bfd_signed_vma offset;
992
993   len = TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym)));
994   switch (SYMBOL_CLASS (sym))
995     {
996     default:
997       printf_filtered ("%s: don't know symbol class %d\n",
998                        SYMBOL_PRINT_NAME (sym),
999                        SYMBOL_CLASS (sym));
1000       break;
1001     case LOC_CONST:
1002       printf_filtered ("constant %s (value %ld) will not be collected.\n",
1003                        SYMBOL_PRINT_NAME (sym), SYMBOL_VALUE (sym));
1004       break;
1005     case LOC_STATIC:
1006       offset = SYMBOL_VALUE_ADDRESS (sym);
1007       if (info_verbose)
1008         {
1009           char tmp[40];
1010
1011           sprintf_vma (tmp, offset);
1012           printf_filtered ("LOC_STATIC %s: collect %ld bytes at %s.\n",
1013                            SYMBOL_PRINT_NAME (sym), len,
1014                            tmp /* address */);
1015         }
1016       add_memrange (collect, memrange_absolute, offset, len);
1017       break;
1018     case LOC_REGISTER:
1019       reg = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
1020       if (info_verbose)
1021         printf_filtered ("LOC_REG[parm] %s: ", 
1022                          SYMBOL_PRINT_NAME (sym));
1023       add_register (collect, reg);
1024       /* Check for doubles stored in two registers.  */
1025       /* FIXME: how about larger types stored in 3 or more regs?  */
1026       if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_FLT &&
1027           len > register_size (gdbarch, reg))
1028         add_register (collect, reg + 1);
1029       break;
1030     case LOC_REF_ARG:
1031       printf_filtered ("Sorry, don't know how to do LOC_REF_ARG yet.\n");
1032       printf_filtered ("       (will not collect %s)\n",
1033                        SYMBOL_PRINT_NAME (sym));
1034       break;
1035     case LOC_ARG:
1036       reg = frame_regno;
1037       offset = frame_offset + SYMBOL_VALUE (sym);
1038       if (info_verbose)
1039         {
1040           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
1041                            SYMBOL_PRINT_NAME (sym), len);
1042           printf_vma (offset);
1043           printf_filtered (" from frame ptr reg %d\n", reg);
1044         }
1045       add_memrange (collect, reg, offset, len);
1046       break;
1047     case LOC_REGPARM_ADDR:
1048       reg = SYMBOL_VALUE (sym);
1049       offset = 0;
1050       if (info_verbose)
1051         {
1052           printf_filtered ("LOC_REGPARM_ADDR %s: Collect %ld bytes at offset ",
1053                            SYMBOL_PRINT_NAME (sym), len);
1054           printf_vma (offset);
1055           printf_filtered (" from reg %d\n", reg);
1056         }
1057       add_memrange (collect, reg, offset, len);
1058       break;
1059     case LOC_LOCAL:
1060       reg = frame_regno;
1061       offset = frame_offset + SYMBOL_VALUE (sym);
1062       if (info_verbose)
1063         {
1064           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
1065                            SYMBOL_PRINT_NAME (sym), len);
1066           printf_vma (offset);
1067           printf_filtered (" from frame ptr reg %d\n", reg);
1068         }
1069       add_memrange (collect, reg, offset, len);
1070       break;
1071     case LOC_UNRESOLVED:
1072       printf_filtered ("Don't know LOC_UNRESOLVED %s\n", 
1073                        SYMBOL_PRINT_NAME (sym));
1074       break;
1075     case LOC_OPTIMIZED_OUT:
1076       printf_filtered ("%s has been optimized out of existence.\n",
1077                        SYMBOL_PRINT_NAME (sym));
1078       break;
1079
1080     case LOC_COMPUTED:
1081       {
1082         struct agent_expr *aexpr;
1083         struct cleanup *old_chain1 = NULL;
1084         struct agent_reqs areqs;
1085
1086         aexpr = gen_trace_for_var (scope, sym);
1087
1088         old_chain1 = make_cleanup_free_agent_expr (aexpr);
1089
1090         ax_reqs (aexpr, &areqs);
1091         if (areqs.flaw != agent_flaw_none)
1092           error (_("malformed expression"));
1093         
1094         if (areqs.min_height < 0)
1095           error (_("gdb: Internal error: expression has min height < 0"));
1096         if (areqs.max_height > 20)
1097           error (_("expression too complicated, try simplifying"));
1098
1099         discard_cleanups (old_chain1);
1100         add_aexpr (collect, aexpr);
1101
1102         /* take care of the registers */
1103         if (areqs.reg_mask_len > 0)
1104           {
1105             int ndx1, ndx2;
1106
1107             for (ndx1 = 0; ndx1 < areqs.reg_mask_len; ndx1++)
1108               {
1109                 QUIT;   /* allow user to bail out with ^C */
1110                 if (areqs.reg_mask[ndx1] != 0)
1111                   {
1112                     /* assume chars have 8 bits */
1113                     for (ndx2 = 0; ndx2 < 8; ndx2++)
1114                       if (areqs.reg_mask[ndx1] & (1 << ndx2))
1115                         /* it's used -- record it */
1116                         add_register (collect, 
1117                                       ndx1 * 8 + ndx2);
1118                   }
1119               }
1120           }
1121       }
1122       break;
1123     }
1124 }
1125
1126 /* Add all locals (or args) symbols to collection list */
1127 static void
1128 add_local_symbols (struct collection_list *collect,
1129                    struct gdbarch *gdbarch, CORE_ADDR pc,
1130                    long frame_regno, long frame_offset, int type)
1131 {
1132   struct symbol *sym;
1133   struct block *block;
1134   struct dict_iterator iter;
1135   int count = 0;
1136
1137   block = block_for_pc (pc);
1138   while (block != 0)
1139     {
1140       QUIT;                     /* allow user to bail out with ^C */
1141       ALL_BLOCK_SYMBOLS (block, iter, sym)
1142         {
1143           if (SYMBOL_IS_ARGUMENT (sym)
1144               ? type == 'A'     /* collecting Arguments */
1145               : type == 'L')    /* collecting Locals */
1146             {
1147               count++;
1148               collect_symbol (collect, sym, gdbarch,
1149                               frame_regno, frame_offset, pc);
1150             }
1151         }
1152       if (BLOCK_FUNCTION (block))
1153         break;
1154       else
1155         block = BLOCK_SUPERBLOCK (block);
1156     }
1157   if (count == 0)
1158     warning (_("No %s found in scope."), 
1159              type == 'L' ? "locals" : "args");
1160 }
1161
1162 /* worker function */
1163 static void
1164 clear_collection_list (struct collection_list *list)
1165 {
1166   int ndx;
1167
1168   list->next_memrange = 0;
1169   for (ndx = 0; ndx < list->next_aexpr_elt; ndx++)
1170     {
1171       free_agent_expr (list->aexpr_list[ndx]);
1172       list->aexpr_list[ndx] = NULL;
1173     }
1174   list->next_aexpr_elt = 0;
1175   memset (list->regs_mask, 0, sizeof (list->regs_mask));
1176 }
1177
1178 /* reduce a collection list to string form (for gdb protocol) */
1179 static char **
1180 stringify_collection_list (struct collection_list *list, char *string)
1181 {
1182   char temp_buf[2048];
1183   char tmp2[40];
1184   int count;
1185   int ndx = 0;
1186   char *(*str_list)[];
1187   char *end;
1188   long i;
1189
1190   count = 1 + list->next_memrange + list->next_aexpr_elt + 1;
1191   str_list = (char *(*)[]) xmalloc (count * sizeof (char *));
1192
1193   for (i = sizeof (list->regs_mask) - 1; i > 0; i--)
1194     if (list->regs_mask[i] != 0)        /* skip leading zeroes in regs_mask */
1195       break;
1196   if (list->regs_mask[i] != 0)  /* prepare to send regs_mask to the stub */
1197     {
1198       if (info_verbose)
1199         printf_filtered ("\nCollecting registers (mask): 0x");
1200       end = temp_buf;
1201       *end++ = 'R';
1202       for (; i >= 0; i--)
1203         {
1204           QUIT;                 /* allow user to bail out with ^C */
1205           if (info_verbose)
1206             printf_filtered ("%02X", list->regs_mask[i]);
1207           sprintf (end, "%02X", list->regs_mask[i]);
1208           end += 2;
1209         }
1210       (*str_list)[ndx] = xstrdup (temp_buf);
1211       ndx++;
1212     }
1213   if (info_verbose)
1214     printf_filtered ("\n");
1215   if (list->next_memrange > 0 && info_verbose)
1216     printf_filtered ("Collecting memranges: \n");
1217   for (i = 0, count = 0, end = temp_buf; i < list->next_memrange; i++)
1218     {
1219       QUIT;                     /* allow user to bail out with ^C */
1220       sprintf_vma (tmp2, list->list[i].start);
1221       if (info_verbose)
1222         {
1223           printf_filtered ("(%d, %s, %ld)\n", 
1224                            list->list[i].type, 
1225                            tmp2, 
1226                            (long) (list->list[i].end - list->list[i].start));
1227         }
1228       if (count + 27 > MAX_AGENT_EXPR_LEN)
1229         {
1230           (*str_list)[ndx] = savestring (temp_buf, count);
1231           ndx++;
1232           count = 0;
1233           end = temp_buf;
1234         }
1235
1236       {
1237         bfd_signed_vma length = list->list[i].end - list->list[i].start;
1238
1239         /* The "%X" conversion specifier expects an unsigned argument,
1240            so passing -1 (memrange_absolute) to it directly gives you
1241            "FFFFFFFF" (or more, depending on sizeof (unsigned)).
1242            Special-case it.  */
1243         if (list->list[i].type == memrange_absolute)
1244           sprintf (end, "M-1,%s,%lX", tmp2, (long) length);
1245         else
1246           sprintf (end, "M%X,%s,%lX", list->list[i].type, tmp2, (long) length);
1247       }
1248
1249       count += strlen (end);
1250       end = temp_buf + count;
1251     }
1252
1253   for (i = 0; i < list->next_aexpr_elt; i++)
1254     {
1255       QUIT;                     /* allow user to bail out with ^C */
1256       if ((count + 10 + 2 * list->aexpr_list[i]->len) > MAX_AGENT_EXPR_LEN)
1257         {
1258           (*str_list)[ndx] = savestring (temp_buf, count);
1259           ndx++;
1260           count = 0;
1261           end = temp_buf;
1262         }
1263       sprintf (end, "X%08X,", list->aexpr_list[i]->len);
1264       end += 10;                /* 'X' + 8 hex digits + ',' */
1265       count += 10;
1266
1267       end = mem2hex (list->aexpr_list[i]->buf, 
1268                      end, list->aexpr_list[i]->len);
1269       count += 2 * list->aexpr_list[i]->len;
1270     }
1271
1272   if (count != 0)
1273     {
1274       (*str_list)[ndx] = savestring (temp_buf, count);
1275       ndx++;
1276       count = 0;
1277       end = temp_buf;
1278     }
1279   (*str_list)[ndx] = NULL;
1280
1281   if (ndx == 0)
1282     {
1283       xfree (str_list);
1284       return NULL;
1285     }
1286   else
1287     return *str_list;
1288 }
1289
1290 static void
1291 free_actions_list_cleanup_wrapper (void *al)
1292 {
1293   free_actions_list (al);
1294 }
1295
1296 static void
1297 free_actions_list (char **actions_list)
1298 {
1299   int ndx;
1300
1301   if (actions_list == 0)
1302     return;
1303
1304   for (ndx = 0; actions_list[ndx]; ndx++)
1305     xfree (actions_list[ndx]);
1306
1307   xfree (actions_list);
1308 }
1309
1310 /* Render all actions into gdb protocol.  */
1311 static void
1312 encode_actions (struct breakpoint *t, char ***tdp_actions,
1313                 char ***stepping_actions)
1314 {
1315   static char tdp_buff[2048], step_buff[2048];
1316   char *action_exp;
1317   struct expression *exp = NULL;
1318   struct action_line *action;
1319   int i;
1320   struct value *tempval;
1321   struct collection_list *collect;
1322   struct cmd_list_element *cmd;
1323   struct agent_expr *aexpr;
1324   int frame_reg;
1325   LONGEST frame_offset;
1326   char *default_collect_line = NULL;
1327   struct action_line *default_collect_action = NULL;
1328
1329   clear_collection_list (&tracepoint_list);
1330   clear_collection_list (&stepping_list);
1331   collect = &tracepoint_list;
1332
1333   *tdp_actions = NULL;
1334   *stepping_actions = NULL;
1335
1336   gdbarch_virtual_frame_pointer (t->gdbarch,
1337                                  t->loc->address, &frame_reg, &frame_offset);
1338
1339   action = t->actions;
1340
1341   /* If there are default expressions to collect, make up a collect
1342      action and prepend to the action list to encode.  Note that since
1343      validation is per-tracepoint (local var "xyz" might be valid for
1344      one tracepoint and not another, etc), we make up the action on
1345      the fly, and don't cache it.  */
1346   if (*default_collect)
1347     {
1348       char *line;
1349       enum actionline_type linetype;
1350
1351       default_collect_line = xmalloc (12 + strlen (default_collect));
1352       sprintf (default_collect_line, "collect %s", default_collect);
1353       line = default_collect_line;
1354       linetype = validate_actionline (&line, t);
1355       if (linetype != BADLINE)
1356         {
1357           default_collect_action = xmalloc (sizeof (struct action_line));
1358           default_collect_action->next = t->actions;
1359           default_collect_action->action = line;
1360           action = default_collect_action;
1361         }
1362     }
1363
1364   for (; action; action = action->next)
1365     {
1366       QUIT;                     /* allow user to bail out with ^C */
1367       action_exp = action->action;
1368       while (isspace ((int) *action_exp))
1369         action_exp++;
1370
1371       if (*action_exp == '#')   /* comment line */
1372         return;
1373
1374       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
1375       if (cmd == 0)
1376         error (_("Bad action list item: %s"), action_exp);
1377
1378       if (cmd_cfunc_eq (cmd, collect_pseudocommand))
1379         {
1380           do
1381             {                   /* repeat over a comma-separated list */
1382               QUIT;             /* allow user to bail out with ^C */
1383               while (isspace ((int) *action_exp))
1384                 action_exp++;
1385
1386               if (0 == strncasecmp ("$reg", action_exp, 4))
1387                 {
1388                   for (i = 0; i < gdbarch_num_regs (t->gdbarch); i++)
1389                     add_register (collect, i);
1390                   action_exp = strchr (action_exp, ',');        /* more? */
1391                 }
1392               else if (0 == strncasecmp ("$arg", action_exp, 4))
1393                 {
1394                   add_local_symbols (collect,
1395                                      t->gdbarch,
1396                                      t->loc->address,
1397                                      frame_reg,
1398                                      frame_offset,
1399                                      'A');
1400                   action_exp = strchr (action_exp, ',');        /* more? */
1401                 }
1402               else if (0 == strncasecmp ("$loc", action_exp, 4))
1403                 {
1404                   add_local_symbols (collect,
1405                                      t->gdbarch,
1406                                      t->loc->address,
1407                                      frame_reg,
1408                                      frame_offset,
1409                                      'L');
1410                   action_exp = strchr (action_exp, ',');        /* more? */
1411                 }
1412               else
1413                 {
1414                   unsigned long addr, len;
1415                   struct cleanup *old_chain = NULL;
1416                   struct cleanup *old_chain1 = NULL;
1417                   struct agent_reqs areqs;
1418
1419                   exp = parse_exp_1 (&action_exp, 
1420                                      block_for_pc (t->loc->address), 1);
1421                   old_chain = make_cleanup (free_current_contents, &exp);
1422
1423                   switch (exp->elts[0].opcode)
1424                     {
1425                     case OP_REGISTER:
1426                       {
1427                         const char *name = &exp->elts[2].string;
1428
1429                         i = user_reg_map_name_to_regnum (t->gdbarch,
1430                                                          name, strlen (name));
1431                         if (i == -1)
1432                           internal_error (__FILE__, __LINE__,
1433                                           _("Register $%s not available"),
1434                                           name);
1435                         if (info_verbose)
1436                           printf_filtered ("OP_REGISTER: ");
1437                         add_register (collect, i);
1438                         break;
1439                       }
1440
1441                     case UNOP_MEMVAL:
1442                       /* safe because we know it's a simple expression */
1443                       tempval = evaluate_expression (exp);
1444                       addr = value_address (tempval);
1445                       len = TYPE_LENGTH (check_typedef (exp->elts[1].type));
1446                       add_memrange (collect, memrange_absolute, addr, len);
1447                       break;
1448
1449                     case OP_VAR_VALUE:
1450                       collect_symbol (collect,
1451                                       exp->elts[2].symbol,
1452                                       t->gdbarch,
1453                                       frame_reg,
1454                                       frame_offset,
1455                                       t->loc->address);
1456                       break;
1457
1458                     default:    /* full-fledged expression */
1459                       aexpr = gen_trace_for_expr (t->loc->address, exp);
1460
1461                       old_chain1 = make_cleanup_free_agent_expr (aexpr);
1462
1463                       ax_reqs (aexpr, &areqs);
1464                       if (areqs.flaw != agent_flaw_none)
1465                         error (_("malformed expression"));
1466
1467                       if (areqs.min_height < 0)
1468                         error (_("gdb: Internal error: expression has min height < 0"));
1469                       if (areqs.max_height > 20)
1470                         error (_("expression too complicated, try simplifying"));
1471
1472                       discard_cleanups (old_chain1);
1473                       add_aexpr (collect, aexpr);
1474
1475                       /* take care of the registers */
1476                       if (areqs.reg_mask_len > 0)
1477                         {
1478                           int ndx1;
1479                           int ndx2;
1480
1481                           for (ndx1 = 0; ndx1 < areqs.reg_mask_len; ndx1++)
1482                             {
1483                               QUIT;     /* allow user to bail out with ^C */
1484                               if (areqs.reg_mask[ndx1] != 0)
1485                                 {
1486                                   /* assume chars have 8 bits */
1487                                   for (ndx2 = 0; ndx2 < 8; ndx2++)
1488                                     if (areqs.reg_mask[ndx1] & (1 << ndx2))
1489                                       /* it's used -- record it */
1490                                       add_register (collect, 
1491                                                     ndx1 * 8 + ndx2);
1492                                 }
1493                             }
1494                         }
1495                       break;
1496                     }           /* switch */
1497                   do_cleanups (old_chain);
1498                 }               /* do */
1499             }
1500           while (action_exp && *action_exp++ == ',');
1501         }                       /* if */
1502       else if (cmd_cfunc_eq (cmd, teval_pseudocommand))
1503         {
1504           do
1505             {                   /* repeat over a comma-separated list */
1506               QUIT;             /* allow user to bail out with ^C */
1507               while (isspace ((int) *action_exp))
1508                 action_exp++;
1509
1510                 {
1511                   unsigned long addr, len;
1512                   struct cleanup *old_chain = NULL;
1513                   struct cleanup *old_chain1 = NULL;
1514                   struct agent_reqs areqs;
1515
1516                   exp = parse_exp_1 (&action_exp, 
1517                                      block_for_pc (t->loc->address), 1);
1518                   old_chain = make_cleanup (free_current_contents, &exp);
1519
1520                   aexpr = gen_eval_for_expr (t->loc->address, exp);
1521                   old_chain1 = make_cleanup_free_agent_expr (aexpr);
1522
1523                   ax_reqs (aexpr, &areqs);
1524                   if (areqs.flaw != agent_flaw_none)
1525                     error (_("malformed expression"));
1526
1527                   if (areqs.min_height < 0)
1528                     error (_("gdb: Internal error: expression has min height < 0"));
1529                   if (areqs.max_height > 20)
1530                     error (_("expression too complicated, try simplifying"));
1531
1532                   discard_cleanups (old_chain1);
1533                   /* Even though we're not officially collecting, add
1534                      to the collect list anyway.  */
1535                   add_aexpr (collect, aexpr);
1536
1537                   do_cleanups (old_chain);
1538                 }               /* do */
1539             }
1540           while (action_exp && *action_exp++ == ',');
1541         }                       /* if */
1542       else if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
1543         {
1544           collect = &stepping_list;
1545         }
1546       else if (cmd_cfunc_eq (cmd, end_actions_pseudocommand))
1547         {
1548           if (collect == &stepping_list)        /* end stepping actions */
1549             collect = &tracepoint_list;
1550           else
1551             break;              /* end tracepoint actions */
1552         }
1553     }                           /* for */
1554   memrange_sortmerge (&tracepoint_list);
1555   memrange_sortmerge (&stepping_list);
1556
1557   *tdp_actions = stringify_collection_list (&tracepoint_list, 
1558                                             tdp_buff);
1559   *stepping_actions = stringify_collection_list (&stepping_list, 
1560                                                  step_buff);
1561
1562   xfree (default_collect_line);
1563   xfree (default_collect_action);
1564 }
1565
1566 static void
1567 add_aexpr (struct collection_list *collect, struct agent_expr *aexpr)
1568 {
1569   if (collect->next_aexpr_elt >= collect->aexpr_listsize)
1570     {
1571       collect->aexpr_list =
1572         xrealloc (collect->aexpr_list,
1573                 2 * collect->aexpr_listsize * sizeof (struct agent_expr *));
1574       collect->aexpr_listsize *= 2;
1575     }
1576   collect->aexpr_list[collect->next_aexpr_elt] = aexpr;
1577   collect->next_aexpr_elt++;
1578 }
1579
1580 /* Set "transparent" memory ranges
1581
1582    Allow trace mechanism to treat text-like sections
1583    (and perhaps all read-only sections) transparently, 
1584    i.e. don't reject memory requests from these address ranges
1585    just because they haven't been collected.  */
1586
1587 static void
1588 remote_set_transparent_ranges (void)
1589 {
1590   asection *s;
1591   bfd_size_type size;
1592   bfd_vma lma;
1593   int anysecs = 0;
1594
1595   if (!exec_bfd)
1596     return;                     /* No information to give.  */
1597
1598   strcpy (target_buf, "QTro");
1599   for (s = exec_bfd->sections; s; s = s->next)
1600     {
1601       char tmp1[40], tmp2[40];
1602
1603       if ((s->flags & SEC_LOAD) == 0 ||
1604       /* (s->flags & SEC_CODE)     == 0 || */
1605           (s->flags & SEC_READONLY) == 0)
1606         continue;
1607
1608       anysecs = 1;
1609       lma = s->lma;
1610       size = bfd_get_section_size (s);
1611       sprintf_vma (tmp1, lma);
1612       sprintf_vma (tmp2, lma + size);
1613       sprintf (target_buf + strlen (target_buf), 
1614                ":%s,%s", tmp1, tmp2);
1615     }
1616   if (anysecs)
1617     {
1618       putpkt (target_buf);
1619       getpkt (&target_buf, &target_buf_size, 0);
1620     }
1621 }
1622
1623 /* tstart command:
1624
1625    Tell target to clear any previous trace experiment.
1626    Walk the list of tracepoints, and send them (and their actions)
1627    to the target.  If no errors, 
1628    Tell target to start a new trace experiment.  */
1629
1630 void download_tracepoint (struct breakpoint *t);
1631
1632 static void
1633 trace_start_command (char *args, int from_tty)
1634 {
1635   char buf[2048];
1636   VEC(breakpoint_p) *tp_vec = NULL;
1637   int ix;
1638   struct breakpoint *t;
1639   struct trace_state_variable *tsv;
1640
1641   dont_repeat ();       /* Like "run", dangerous to repeat accidentally.  */
1642
1643   if (target_is_remote ())
1644     {
1645       putpkt ("QTinit");
1646       remote_get_noisy_reply (&target_buf, &target_buf_size);
1647       if (strcmp (target_buf, "OK"))
1648         error (_("Target does not support this command."));
1649
1650       tp_vec = all_tracepoints ();
1651       for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, t); ix++)
1652         {
1653           download_tracepoint (t);
1654         }
1655       VEC_free (breakpoint_p, tp_vec);
1656
1657       /* Init any trace state variables that start with nonzero values.  */
1658
1659       for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
1660         {
1661           if (tsv->initial_value != 0)
1662             {
1663               sprintf (buf, "QTDV:%x:%s",
1664                        tsv->number, phex ((ULONGEST) tsv->initial_value, 8));
1665               putpkt (buf);
1666               remote_get_noisy_reply (&target_buf, &target_buf_size);
1667             }
1668         }
1669
1670       /* Tell target to treat text-like sections as transparent.  */
1671       remote_set_transparent_ranges ();
1672       /* Now insert traps and begin collecting data.  */
1673       putpkt ("QTStart");
1674       remote_get_noisy_reply (&target_buf, &target_buf_size);
1675       if (strcmp (target_buf, "OK"))
1676         error (_("Bogus reply from target: %s"), target_buf);
1677       set_traceframe_num (-1);  /* All old traceframes invalidated.  */
1678       set_tracepoint_num (-1);
1679       set_traceframe_context (NULL);
1680       trace_running_p = 1;
1681       if (deprecated_trace_start_stop_hook)
1682         deprecated_trace_start_stop_hook (1, from_tty);
1683
1684     }
1685   else
1686     error (_("Trace can only be run on remote targets."));
1687 }
1688
1689 /* Send the definition of a single tracepoint to the target.  */
1690
1691 void
1692 download_tracepoint (struct breakpoint *t)
1693 {
1694   CORE_ADDR tpaddr;
1695   char tmp[40];
1696   char buf[2048];
1697   char **tdp_actions;
1698   char **stepping_actions;
1699   int ndx;
1700   struct cleanup *old_chain = NULL;
1701   struct agent_expr *aexpr;
1702   struct cleanup *aexpr_chain = NULL;
1703
1704   tpaddr = t->loc->address;
1705   sprintf_vma (tmp, (t->loc ? tpaddr : 0));
1706   sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", t->number, 
1707            tmp, /* address */
1708            (t->enable_state == bp_enabled ? 'E' : 'D'),
1709            t->step_count, t->pass_count);
1710   /* Fast tracepoints are mostly handled by the target, but we can
1711      tell the target how big of an instruction block should be moved
1712      around.  */
1713   if (t->type == bp_fast_tracepoint)
1714     {
1715       /* Only test for support at download time; we may not know
1716          target capabilities at definition time.  */
1717       if (remote_supports_fast_tracepoints ())
1718         {
1719           int isize;
1720
1721           if (gdbarch_fast_tracepoint_valid_at (get_current_arch (),
1722                                                 tpaddr, &isize, NULL))
1723             sprintf (buf + strlen (buf), ":F%x", isize);
1724           else
1725             /* If it passed validation at definition but fails now,
1726                something is very wrong.  */
1727             internal_error (__FILE__, __LINE__,
1728                             "Fast tracepoint not valid during download");
1729         }
1730       else
1731         /* Fast tracepoints are functionally identical to regular
1732            tracepoints, so don't take lack of support as a reason to
1733            give up on the trace run.  */
1734         warning (_("Target does not support fast tracepoints, downloading %d as regular tracepoint"), t->number);
1735     }
1736   /* If the tracepoint has a conditional, make it into an agent
1737      expression and append to the definition.  */
1738   if (t->loc->cond)
1739     {
1740       /* Only test support at download time, we may not know target
1741          capabilities at definition time.  */
1742       if (remote_supports_cond_tracepoints ())
1743         {
1744           aexpr = gen_eval_for_expr (t->loc->address, t->loc->cond);
1745           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
1746           sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
1747           mem2hex (aexpr->buf, buf + strlen (buf), aexpr->len);
1748           do_cleanups (aexpr_chain);
1749         }
1750       else
1751         warning (_("Target does not support conditional tracepoints, ignoring tp %d cond"), t->number);
1752     }
1753
1754   if (t->actions || *default_collect)
1755     strcat (buf, "-");
1756   putpkt (buf);
1757   remote_get_noisy_reply (&target_buf, &target_buf_size);
1758   if (strcmp (target_buf, "OK"))
1759     error (_("Target does not support tracepoints."));
1760
1761   if (!t->actions && !*default_collect)
1762     return;
1763
1764   encode_actions (t, &tdp_actions, &stepping_actions);
1765   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
1766                             tdp_actions);
1767   (void) make_cleanup (free_actions_list_cleanup_wrapper, stepping_actions);
1768
1769   /* do_single_steps (t); */
1770   if (tdp_actions)
1771     {
1772       for (ndx = 0; tdp_actions[ndx]; ndx++)
1773         {
1774           QUIT; /* allow user to bail out with ^C */
1775           sprintf (buf, "QTDP:-%x:%s:%s%c",
1776                    t->number, tmp, /* address */
1777                    tdp_actions[ndx],
1778                    ((tdp_actions[ndx + 1] || stepping_actions)
1779                     ? '-' : 0));
1780           putpkt (buf);
1781           remote_get_noisy_reply (&target_buf,
1782                                   &target_buf_size);
1783           if (strcmp (target_buf, "OK"))
1784             error (_("Error on target while setting tracepoints."));
1785         }
1786     }
1787   if (stepping_actions)
1788     {
1789       for (ndx = 0; stepping_actions[ndx]; ndx++)
1790         {
1791           QUIT; /* allow user to bail out with ^C */
1792           sprintf (buf, "QTDP:-%x:%s:%s%s%s",
1793                    t->number, tmp, /* address */
1794                    ((ndx == 0) ? "S" : ""),
1795                    stepping_actions[ndx],
1796                    (stepping_actions[ndx + 1] ? "-" : ""));
1797           putpkt (buf);
1798           remote_get_noisy_reply (&target_buf,
1799                                   &target_buf_size);
1800           if (strcmp (target_buf, "OK"))
1801             error (_("Error on target while setting tracepoints."));
1802         }
1803     }
1804   do_cleanups (old_chain);
1805 }
1806
1807 /* tstop command */
1808 static void
1809 trace_stop_command (char *args, int from_tty)
1810 {
1811   if (target_is_remote ())
1812     {
1813       putpkt ("QTStop");
1814       remote_get_noisy_reply (&target_buf, &target_buf_size);
1815       if (strcmp (target_buf, "OK"))
1816         error (_("Bogus reply from target: %s"), target_buf);
1817       trace_running_p = 0;
1818       if (deprecated_trace_start_stop_hook)
1819         deprecated_trace_start_stop_hook (0, from_tty);
1820     }
1821   else
1822     error (_("Trace can only be run on remote targets."));
1823 }
1824
1825 unsigned long trace_running_p;
1826
1827 /* tstatus command */
1828 static void
1829 trace_status_command (char *args, int from_tty)
1830 {
1831   if (target_is_remote ())
1832     {
1833       putpkt ("qTStatus");
1834       remote_get_noisy_reply (&target_buf, &target_buf_size);
1835
1836       if (target_buf[0] != 'T' ||
1837           (target_buf[1] != '0' && target_buf[1] != '1'))
1838         error (_("Bogus reply from target: %s"), target_buf);
1839
1840       /* exported for use by the GUI */
1841       trace_running_p = (target_buf[1] == '1');
1842
1843       if (trace_running_p)
1844         printf_filtered (_("Trace is running on the target.\n"));
1845       else
1846         printf_filtered (_("Trace is not running on the target.\n"));
1847
1848       if (traceframe_number >= 0)
1849         printf_filtered (_("Looking at trace frame %d, tracepoint %d.\n"),
1850                          traceframe_number, tracepoint_number);
1851       else
1852         printf_filtered (_("Not looking at any trace frame.\n"));
1853
1854     }
1855   else
1856     error (_("Trace can only be run on remote targets."));
1857 }
1858
1859 /* Worker function for the various flavors of the tfind command.  */
1860 static void
1861 finish_tfind_command (char **msg,
1862                       long *sizeof_msg,
1863                       int from_tty)
1864 {
1865   int target_frameno = -1, target_tracept = -1;
1866   struct frame_id old_frame_id;
1867   char *reply;
1868
1869   old_frame_id = get_frame_id (get_current_frame ());
1870
1871   putpkt (*msg);
1872   reply = remote_get_noisy_reply (msg, sizeof_msg);
1873
1874   while (reply && *reply)
1875     switch (*reply)
1876       {
1877       case 'F':
1878         if ((target_frameno = (int) strtol (++reply, &reply, 16)) == -1)
1879           {
1880             /* A request for a non-existant trace frame has failed.
1881                Our response will be different, depending on FROM_TTY:
1882
1883                If FROM_TTY is true, meaning that this command was 
1884                typed interactively by the user, then give an error
1885                and DO NOT change the state of traceframe_number etc.
1886
1887                However if FROM_TTY is false, meaning that we're either
1888                in a script, a loop, or a user-defined command, then 
1889                DON'T give an error, but DO change the state of
1890                traceframe_number etc. to invalid.
1891
1892                The rationalle is that if you typed the command, you
1893                might just have committed a typo or something, and you'd
1894                like to NOT lose your current debugging state.  However
1895                if you're in a user-defined command or especially in a
1896                loop, then you need a way to detect that the command
1897                failed WITHOUT aborting.  This allows you to write
1898                scripts that search thru the trace buffer until the end,
1899                and then continue on to do something else.  */
1900
1901             if (from_tty)
1902               error (_("Target failed to find requested trace frame."));
1903             else
1904               {
1905                 if (info_verbose)
1906                   printf_filtered ("End of trace buffer.\n");
1907                 /* The following will not recurse, since it's
1908                    special-cased.  */
1909                 trace_find_command ("-1", from_tty);
1910                 reply = NULL;   /* Break out of loop 
1911                                    (avoid recursive nonsense).  */
1912               }
1913           }
1914         break;
1915       case 'T':
1916         if ((target_tracept = (int) strtol (++reply, &reply, 16)) == -1)
1917           error (_("Target failed to find requested trace frame."));
1918         break;
1919       case 'O':         /* "OK"? */
1920         if (reply[1] == 'K' && reply[2] == '\0')
1921           reply += 2;
1922         else
1923           error (_("Bogus reply from target: %s"), reply);
1924         break;
1925       default:
1926         error (_("Bogus reply from target: %s"), reply);
1927       }
1928
1929   reinit_frame_cache ();
1930   registers_changed ();
1931   set_traceframe_num (target_frameno);
1932   set_tracepoint_num (target_tracept);
1933   if (target_frameno == -1)
1934     set_traceframe_context (NULL);
1935   else
1936     set_traceframe_context (get_current_frame ());
1937
1938   if (from_tty)
1939     {
1940       enum print_what print_what;
1941
1942       /* NOTE: in immitation of the step command, try to determine
1943          whether we have made a transition from one function to
1944          another.  If so, we'll print the "stack frame" (ie. the new
1945          function and it's arguments) -- otherwise we'll just show the
1946          new source line.  */
1947
1948       if (frame_id_eq (old_frame_id,
1949                        get_frame_id (get_current_frame ())))
1950         print_what = SRC_LINE;
1951       else
1952         print_what = SRC_AND_LOC;
1953
1954       print_stack_frame (get_selected_frame (NULL), 1, print_what);
1955       do_displays ();
1956     }
1957 }
1958
1959 /* trace_find_command takes a trace frame number n, 
1960    sends "QTFrame:<n>" to the target, 
1961    and accepts a reply that may contain several optional pieces
1962    of information: a frame number, a tracepoint number, and an
1963    indication of whether this is a trap frame or a stepping frame.
1964
1965    The minimal response is just "OK" (which indicates that the 
1966    target does not give us a frame number or a tracepoint number).
1967    Instead of that, the target may send us a string containing
1968    any combination of:
1969    F<hexnum>    (gives the selected frame number)
1970    T<hexnum>    (gives the selected tracepoint number)
1971  */
1972
1973 /* tfind command */
1974 static void
1975 trace_find_command (char *args, int from_tty)
1976 { /* this should only be called with a numeric argument */
1977   int frameno = -1;
1978
1979   if (target_is_remote ())
1980     {
1981       if (trace_running_p)
1982         error ("May not look at trace frames while trace is running.");
1983
1984       if (deprecated_trace_find_hook)
1985         deprecated_trace_find_hook (args, from_tty);
1986
1987       if (args == 0 || *args == 0)
1988         { /* TFIND with no args means find NEXT trace frame.  */
1989           if (traceframe_number == -1)
1990             frameno = 0;        /* "next" is first one */
1991           else
1992             frameno = traceframe_number + 1;
1993         }
1994       else if (0 == strcmp (args, "-"))
1995         {
1996           if (traceframe_number == -1)
1997             error (_("not debugging trace buffer"));
1998           else if (from_tty && traceframe_number == 0)
1999             error (_("already at start of trace buffer"));
2000
2001           frameno = traceframe_number - 1;
2002         }
2003       else
2004         frameno = parse_and_eval_long (args);
2005
2006       if (frameno < -1)
2007         error (_("invalid input (%d is less than zero)"), frameno);
2008
2009       sprintf (target_buf, "QTFrame:%x", frameno);
2010       finish_tfind_command (&target_buf, &target_buf_size, from_tty);
2011     }
2012   else
2013     error (_("Trace can only be run on remote targets."));
2014 }
2015
2016 /* tfind end */
2017 static void
2018 trace_find_end_command (char *args, int from_tty)
2019 {
2020   trace_find_command ("-1", from_tty);
2021 }
2022
2023 /* tfind none */
2024 static void
2025 trace_find_none_command (char *args, int from_tty)
2026 {
2027   trace_find_command ("-1", from_tty);
2028 }
2029
2030 /* tfind start */
2031 static void
2032 trace_find_start_command (char *args, int from_tty)
2033 {
2034   trace_find_command ("0", from_tty);
2035 }
2036
2037 /* tfind pc command */
2038 static void
2039 trace_find_pc_command (char *args, int from_tty)
2040 {
2041   CORE_ADDR pc;
2042   char tmp[40];
2043
2044   if (target_is_remote ())
2045     {
2046       if (trace_running_p)
2047         error ("May not look at trace frames while trace is running.");
2048
2049       if (args == 0 || *args == 0)
2050         pc = regcache_read_pc (get_current_regcache ());
2051       else
2052         pc = parse_and_eval_address (args);
2053
2054       sprintf_vma (tmp, pc);
2055       sprintf (target_buf, "QTFrame:pc:%s", tmp);
2056       finish_tfind_command (&target_buf, &target_buf_size, from_tty);
2057     }
2058   else
2059     error (_("Trace can only be run on remote targets."));
2060 }
2061
2062 /* tfind tracepoint command */
2063 static void
2064 trace_find_tracepoint_command (char *args, int from_tty)
2065 {
2066   int tdp;
2067
2068   if (target_is_remote ())
2069     {
2070       if (trace_running_p)
2071         error ("May not look at trace frames while trace is running.");
2072
2073       if (args == 0 || *args == 0)
2074         {
2075           if (tracepoint_number == -1)
2076             error (_("No current tracepoint -- please supply an argument."));
2077           else
2078             tdp = tracepoint_number;    /* default is current TDP */
2079         }
2080       else
2081         tdp = parse_and_eval_long (args);
2082
2083       sprintf (target_buf, "QTFrame:tdp:%x", tdp);
2084       finish_tfind_command (&target_buf, &target_buf_size, from_tty);
2085     }
2086   else
2087     error (_("Trace can only be run on remote targets."));
2088 }
2089
2090 /* TFIND LINE command:
2091
2092    This command will take a sourceline for argument, just like BREAK
2093    or TRACE (ie. anything that "decode_line_1" can handle).
2094
2095    With no argument, this command will find the next trace frame 
2096    corresponding to a source line OTHER THAN THE CURRENT ONE.  */
2097
2098 static void
2099 trace_find_line_command (char *args, int from_tty)
2100 {
2101   static CORE_ADDR start_pc, end_pc;
2102   struct symtabs_and_lines sals;
2103   struct symtab_and_line sal;
2104   struct cleanup *old_chain;
2105   char   startpc_str[40], endpc_str[40];
2106
2107   if (target_is_remote ())
2108     {
2109       if (trace_running_p)
2110         error ("May not look at trace frames while trace is running.");
2111
2112       if (args == 0 || *args == 0)
2113         {
2114           sal = find_pc_line (get_frame_pc (get_current_frame ()), 0);
2115           sals.nelts = 1;
2116           sals.sals = (struct symtab_and_line *)
2117             xmalloc (sizeof (struct symtab_and_line));
2118           sals.sals[0] = sal;
2119         }
2120       else
2121         {
2122           sals = decode_line_spec (args, 1);
2123           sal = sals.sals[0];
2124         }
2125
2126       old_chain = make_cleanup (xfree, sals.sals);
2127       if (sal.symtab == 0)
2128         {
2129           struct gdbarch *gdbarch = get_current_arch ();
2130
2131           printf_filtered ("TFIND: No line number information available");
2132           if (sal.pc != 0)
2133             {
2134               /* This is useful for "info line *0x7f34".  If we can't
2135                  tell the user about a source line, at least let them
2136                  have the symbolic address.  */
2137               printf_filtered (" for address ");
2138               wrap_here ("  ");
2139               print_address (gdbarch, sal.pc, gdb_stdout);
2140               printf_filtered (";\n -- will attempt to find by PC. \n");
2141             }
2142           else
2143             {
2144               printf_filtered (".\n");
2145               return;           /* No line, no PC; what can we do?  */
2146             }
2147         }
2148       else if (sal.line > 0
2149                && find_line_pc_range (sal, &start_pc, &end_pc))
2150         {
2151           struct gdbarch *gdbarch = get_objfile_arch (sal.symtab->objfile);
2152
2153           if (start_pc == end_pc)
2154             {
2155               printf_filtered ("Line %d of \"%s\"",
2156                                sal.line, sal.symtab->filename);
2157               wrap_here ("  ");
2158               printf_filtered (" is at address ");
2159               print_address (gdbarch, start_pc, gdb_stdout);
2160               wrap_here ("  ");
2161               printf_filtered (" but contains no code.\n");
2162               sal = find_pc_line (start_pc, 0);
2163               if (sal.line > 0 &&
2164                   find_line_pc_range (sal, &start_pc, &end_pc) &&
2165                   start_pc != end_pc)
2166                 printf_filtered ("Attempting to find line %d instead.\n",
2167                                  sal.line);
2168               else
2169                 error (_("Cannot find a good line."));
2170             }
2171         }
2172       else
2173         /* Is there any case in which we get here, and have an address
2174            which the user would want to see?  If we have debugging
2175            symbols and no line numbers?  */
2176         error (_("Line number %d is out of range for \"%s\"."),
2177                sal.line, sal.symtab->filename);
2178
2179       sprintf_vma (startpc_str, start_pc);
2180       sprintf_vma (endpc_str, end_pc - 1);
2181       /* Find within range of stated line.  */
2182       if (args && *args)
2183         sprintf (target_buf, "QTFrame:range:%s:%s", 
2184                  startpc_str, endpc_str);
2185       /* Find OUTSIDE OF range of CURRENT line.  */
2186       else
2187         sprintf (target_buf, "QTFrame:outside:%s:%s", 
2188                  startpc_str, endpc_str);
2189       finish_tfind_command (&target_buf, &target_buf_size,
2190                             from_tty);
2191       do_cleanups (old_chain);
2192     }
2193   else
2194     error (_("Trace can only be run on remote targets."));
2195 }
2196
2197 /* tfind range command */
2198 static void
2199 trace_find_range_command (char *args, int from_tty)
2200 {
2201   static CORE_ADDR start, stop;
2202   char start_str[40], stop_str[40];
2203   char *tmp;
2204
2205   if (target_is_remote ())
2206     {
2207       if (trace_running_p)
2208         error ("May not look at trace frames while trace is running.");
2209
2210       if (args == 0 || *args == 0)
2211         { /* XXX FIXME: what should default behavior be?  */
2212           printf_filtered ("Usage: tfind range <startaddr>,<endaddr>\n");
2213           return;
2214         }
2215
2216       if (0 != (tmp = strchr (args, ',')))
2217         {
2218           *tmp++ = '\0';        /* terminate start address */
2219           while (isspace ((int) *tmp))
2220             tmp++;
2221           start = parse_and_eval_address (args);
2222           stop = parse_and_eval_address (tmp);
2223         }
2224       else
2225         {                       /* no explicit end address? */
2226           start = parse_and_eval_address (args);
2227           stop = start + 1;     /* ??? */
2228         }
2229
2230       sprintf_vma (start_str, start);
2231       sprintf_vma (stop_str, stop);
2232       sprintf (target_buf, "QTFrame:range:%s:%s", start_str, stop_str);
2233       finish_tfind_command (&target_buf, &target_buf_size, from_tty);
2234     }
2235   else
2236     error (_("Trace can only be run on remote targets."));
2237 }
2238
2239 /* tfind outside command */
2240 static void
2241 trace_find_outside_command (char *args, int from_tty)
2242 {
2243   CORE_ADDR start, stop;
2244   char start_str[40], stop_str[40];
2245   char *tmp;
2246
2247   if (target_is_remote ())
2248     {
2249       if (trace_running_p)
2250         error ("May not look at trace frames while trace is running.");
2251
2252       if (args == 0 || *args == 0)
2253         { /* XXX FIXME: what should default behavior be? */
2254           printf_filtered ("Usage: tfind outside <startaddr>,<endaddr>\n");
2255           return;
2256         }
2257
2258       if (0 != (tmp = strchr (args, ',')))
2259         {
2260           *tmp++ = '\0';        /* terminate start address */
2261           while (isspace ((int) *tmp))
2262             tmp++;
2263           start = parse_and_eval_address (args);
2264           stop = parse_and_eval_address (tmp);
2265         }
2266       else
2267         {                       /* no explicit end address? */
2268           start = parse_and_eval_address (args);
2269           stop = start + 1;     /* ??? */
2270         }
2271
2272       sprintf_vma (start_str, start);
2273       sprintf_vma (stop_str, stop);
2274       sprintf (target_buf, "QTFrame:outside:%s:%s", start_str, stop_str);
2275       finish_tfind_command (&target_buf, &target_buf_size, from_tty);
2276     }
2277   else
2278     error (_("Trace can only be run on remote targets."));
2279 }
2280
2281 /* info scope command: list the locals for a scope.  */
2282 static void
2283 scope_info (char *args, int from_tty)
2284 {
2285   struct symtabs_and_lines sals;
2286   struct symbol *sym;
2287   struct minimal_symbol *msym;
2288   struct block *block;
2289   char **canonical, *symname, *save_args = args;
2290   struct dict_iterator iter;
2291   int j, count = 0;
2292   struct gdbarch *gdbarch;
2293   int regno;
2294
2295   if (args == 0 || *args == 0)
2296     error (_("requires an argument (function, line or *addr) to define a scope"));
2297
2298   sals = decode_line_1 (&args, 1, NULL, 0, &canonical, NULL);
2299   if (sals.nelts == 0)
2300     return;             /* presumably decode_line_1 has already warned */
2301
2302   /* Resolve line numbers to PC */
2303   resolve_sal_pc (&sals.sals[0]);
2304   block = block_for_pc (sals.sals[0].pc);
2305
2306   while (block != 0)
2307     {
2308       QUIT;                     /* allow user to bail out with ^C */
2309       ALL_BLOCK_SYMBOLS (block, iter, sym)
2310         {
2311           QUIT;                 /* allow user to bail out with ^C */
2312           if (count == 0)
2313             printf_filtered ("Scope for %s:\n", save_args);
2314           count++;
2315
2316           symname = SYMBOL_PRINT_NAME (sym);
2317           if (symname == NULL || *symname == '\0')
2318             continue;           /* probably botched, certainly useless */
2319
2320           gdbarch = get_objfile_arch (SYMBOL_SYMTAB (sym)->objfile);
2321
2322           printf_filtered ("Symbol %s is ", symname);
2323           switch (SYMBOL_CLASS (sym))
2324             {
2325             default:
2326             case LOC_UNDEF:     /* messed up symbol? */
2327               printf_filtered ("a bogus symbol, class %d.\n",
2328                                SYMBOL_CLASS (sym));
2329               count--;          /* don't count this one */
2330               continue;
2331             case LOC_CONST:
2332               printf_filtered ("a constant with value %ld (0x%lx)",
2333                                SYMBOL_VALUE (sym), SYMBOL_VALUE (sym));
2334               break;
2335             case LOC_CONST_BYTES:
2336               printf_filtered ("constant bytes: ");
2337               if (SYMBOL_TYPE (sym))
2338                 for (j = 0; j < TYPE_LENGTH (SYMBOL_TYPE (sym)); j++)
2339                   fprintf_filtered (gdb_stdout, " %02x",
2340                                     (unsigned) SYMBOL_VALUE_BYTES (sym)[j]);
2341               break;
2342             case LOC_STATIC:
2343               printf_filtered ("in static storage at address ");
2344               printf_filtered ("%s", paddress (gdbarch,
2345                                                SYMBOL_VALUE_ADDRESS (sym)));
2346               break;
2347             case LOC_REGISTER:
2348               /* GDBARCH is the architecture associated with the objfile
2349                  the symbol is defined in; the target architecture may be
2350                  different, and may provide additional registers.  However,
2351                  we do not know the target architecture at this point.
2352                  We assume the objfile architecture will contain all the
2353                  standard registers that occur in debug info in that
2354                  objfile.  */
2355               regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
2356
2357               if (SYMBOL_IS_ARGUMENT (sym))
2358                 printf_filtered ("an argument in register $%s",
2359                                  gdbarch_register_name (gdbarch, regno));
2360               else
2361                 printf_filtered ("a local variable in register $%s",
2362                                  gdbarch_register_name (gdbarch, regno));
2363               break;
2364             case LOC_ARG:
2365               printf_filtered ("an argument at stack/frame offset %ld",
2366                                SYMBOL_VALUE (sym));
2367               break;
2368             case LOC_LOCAL:
2369               printf_filtered ("a local variable at frame offset %ld",
2370                                SYMBOL_VALUE (sym));
2371               break;
2372             case LOC_REF_ARG:
2373               printf_filtered ("a reference argument at offset %ld",
2374                                SYMBOL_VALUE (sym));
2375               break;
2376             case LOC_REGPARM_ADDR:
2377               /* Note comment at LOC_REGISTER.  */
2378               regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
2379               printf_filtered ("the address of an argument, in register $%s",
2380                                gdbarch_register_name (gdbarch, regno));
2381               break;
2382             case LOC_TYPEDEF:
2383               printf_filtered ("a typedef.\n");
2384               continue;
2385             case LOC_LABEL:
2386               printf_filtered ("a label at address ");
2387               printf_filtered ("%s", paddress (gdbarch,
2388                                                SYMBOL_VALUE_ADDRESS (sym)));
2389               break;
2390             case LOC_BLOCK:
2391               printf_filtered ("a function at address ");
2392               printf_filtered ("%s",
2393                 paddress (gdbarch, BLOCK_START (SYMBOL_BLOCK_VALUE (sym))));
2394               break;
2395             case LOC_UNRESOLVED:
2396               msym = lookup_minimal_symbol (SYMBOL_LINKAGE_NAME (sym),
2397                                             NULL, NULL);
2398               if (msym == NULL)
2399                 printf_filtered ("Unresolved Static");
2400               else
2401                 {
2402                   printf_filtered ("static storage at address ");
2403                   printf_filtered ("%s",
2404                     paddress (gdbarch, SYMBOL_VALUE_ADDRESS (msym)));
2405                 }
2406               break;
2407             case LOC_OPTIMIZED_OUT:
2408               printf_filtered ("optimized out.\n");
2409               continue;
2410             case LOC_COMPUTED:
2411               SYMBOL_COMPUTED_OPS (sym)->describe_location (sym, gdb_stdout);
2412               break;
2413             }
2414           if (SYMBOL_TYPE (sym))
2415             printf_filtered (", length %d.\n",
2416                              TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym))));
2417         }
2418       if (BLOCK_FUNCTION (block))
2419         break;
2420       else
2421         block = BLOCK_SUPERBLOCK (block);
2422     }
2423   if (count <= 0)
2424     printf_filtered ("Scope for %s contains no locals or arguments.\n",
2425                      save_args);
2426 }
2427
2428 /* worker function (cleanup) */
2429 static void
2430 replace_comma (void *data)
2431 {
2432   char *comma = data;
2433   *comma = ',';
2434 }
2435
2436 /* tdump command */
2437 static void
2438 trace_dump_command (char *args, int from_tty)
2439 {
2440   struct regcache *regcache;
2441   struct gdbarch *gdbarch;
2442   struct breakpoint *t;
2443   struct action_line *action;
2444   char *action_exp, *next_comma;
2445   struct cleanup *old_cleanups;
2446   int stepping_actions = 0;
2447   int stepping_frame = 0;
2448
2449   if (!target_is_remote ())
2450     {
2451       error (_("Trace can only be run on remote targets."));
2452       return;
2453     }
2454
2455   if (tracepoint_number == -1)
2456     {
2457       warning (_("No current trace frame."));
2458       return;
2459     }
2460
2461   t = get_tracepoint (tracepoint_number);
2462
2463   if (t == NULL)
2464     error (_("No known tracepoint matches 'current' tracepoint #%d."),
2465            tracepoint_number);
2466
2467   old_cleanups = make_cleanup (null_cleanup, NULL);
2468
2469   printf_filtered ("Data collected at tracepoint %d, trace frame %d:\n",
2470                    tracepoint_number, traceframe_number);
2471
2472   /* The current frame is a trap frame if the frame PC is equal
2473      to the tracepoint PC.  If not, then the current frame was
2474      collected during single-stepping.  */
2475
2476   regcache = get_current_regcache ();
2477   gdbarch = get_regcache_arch (regcache);
2478
2479   stepping_frame = (t->loc->address != (regcache_read_pc (regcache)
2480                                    - gdbarch_decr_pc_after_break (gdbarch)));
2481
2482   for (action = t->actions; action; action = action->next)
2483     {
2484       struct cmd_list_element *cmd;
2485
2486       QUIT;                     /* allow user to bail out with ^C */
2487       action_exp = action->action;
2488       while (isspace ((int) *action_exp))
2489         action_exp++;
2490
2491       /* The collection actions to be done while stepping are
2492          bracketed by the commands "while-stepping" and "end".  */
2493
2494       if (*action_exp == '#')   /* comment line */
2495         continue;
2496
2497       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
2498       if (cmd == 0)
2499         error (_("Bad action list item: %s"), action_exp);
2500
2501       if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
2502         stepping_actions = 1;
2503       else if (cmd_cfunc_eq (cmd, end_actions_pseudocommand))
2504         stepping_actions = 0;
2505       else if (cmd_cfunc_eq (cmd, collect_pseudocommand))
2506         {
2507           /* Display the collected data.
2508              For the trap frame, display only what was collected at
2509              the trap.  Likewise for stepping frames, display only
2510              what was collected while stepping.  This means that the
2511              two boolean variables, STEPPING_FRAME and
2512              STEPPING_ACTIONS should be equal.  */
2513           if (stepping_frame == stepping_actions)
2514             {
2515               do
2516                 {               /* repeat over a comma-separated list */
2517                   QUIT;         /* allow user to bail out with ^C */
2518                   if (*action_exp == ',')
2519                     action_exp++;
2520                   while (isspace ((int) *action_exp))
2521                     action_exp++;
2522
2523                   next_comma = strchr (action_exp, ',');
2524
2525                   if (0 == strncasecmp (action_exp, "$reg", 4))
2526                     registers_info (NULL, from_tty);
2527                   else if (0 == strncasecmp (action_exp, "$loc", 4))
2528                     locals_info (NULL, from_tty);
2529                   else if (0 == strncasecmp (action_exp, "$arg", 4))
2530                     args_info (NULL, from_tty);
2531                   else
2532                     {           /* variable */
2533                       if (next_comma)
2534                         {
2535                           make_cleanup (replace_comma, next_comma);
2536                           *next_comma = '\0';
2537                         }
2538                       printf_filtered ("%s = ", action_exp);
2539                       output_command (action_exp, from_tty);
2540                       printf_filtered ("\n");
2541                     }
2542                   if (next_comma)
2543                     *next_comma = ',';
2544                   action_exp = next_comma;
2545                 }
2546               while (action_exp && *action_exp == ',');
2547             }
2548         }
2549     }
2550   discard_cleanups (old_cleanups);
2551 }
2552
2553 /* Convert the memory pointed to by mem into hex, placing result in buf.
2554  * Return a pointer to the last char put in buf (null)
2555  * "stolen" from sparc-stub.c
2556  */
2557
2558 static const char hexchars[] = "0123456789abcdef";
2559
2560 static char *
2561 mem2hex (gdb_byte *mem, char *buf, int count)
2562 {
2563   gdb_byte ch;
2564
2565   while (count-- > 0)
2566     {
2567       ch = *mem++;
2568
2569       *buf++ = hexchars[ch >> 4];
2570       *buf++ = hexchars[ch & 0xf];
2571     }
2572
2573   *buf = 0;
2574
2575   return buf;
2576 }
2577
2578 int
2579 get_traceframe_number (void)
2580 {
2581   return traceframe_number;
2582 }
2583
2584
2585 /* module initialization */
2586 void
2587 _initialize_tracepoint (void)
2588 {
2589   struct cmd_list_element *c;
2590
2591   traceframe_number = -1;
2592   tracepoint_number = -1;
2593
2594   if (tracepoint_list.list == NULL)
2595     {
2596       tracepoint_list.listsize = 128;
2597       tracepoint_list.list = xmalloc
2598         (tracepoint_list.listsize * sizeof (struct memrange));
2599     }
2600   if (tracepoint_list.aexpr_list == NULL)
2601     {
2602       tracepoint_list.aexpr_listsize = 128;
2603       tracepoint_list.aexpr_list = xmalloc
2604         (tracepoint_list.aexpr_listsize * sizeof (struct agent_expr *));
2605     }
2606
2607   if (stepping_list.list == NULL)
2608     {
2609       stepping_list.listsize = 128;
2610       stepping_list.list = xmalloc
2611         (stepping_list.listsize * sizeof (struct memrange));
2612     }
2613
2614   if (stepping_list.aexpr_list == NULL)
2615     {
2616       stepping_list.aexpr_listsize = 128;
2617       stepping_list.aexpr_list = xmalloc
2618         (stepping_list.aexpr_listsize * sizeof (struct agent_expr *));
2619     }
2620
2621   add_info ("scope", scope_info,
2622             _("List the variables local to a scope"));
2623
2624   add_cmd ("tracepoints", class_trace, NULL,
2625            _("Tracing of program execution without stopping the program."),
2626            &cmdlist);
2627
2628   add_com ("tdump", class_trace, trace_dump_command,
2629            _("Print everything collected at the current tracepoint."));
2630
2631   c = add_com ("tvariable", class_trace, trace_variable_command,_("\
2632 Define a trace state variable.\n\
2633 Argument is a $-prefixed name, optionally followed\n\
2634 by '=' and an expression that sets the initial value\n\
2635 at the start of tracing."));
2636   set_cmd_completer (c, expression_completer);
2637
2638   add_cmd ("tvariable", class_trace, delete_trace_variable_command, _("\
2639 Delete one or more trace state variables.\n\
2640 Arguments are the names of the variables to delete.\n\
2641 If no arguments are supplied, delete all variables."), &deletelist);
2642   /* FIXME add a trace variable completer */
2643
2644   add_info ("tvariables", tvariables_info, _("\
2645 Status of trace state variables and their values.\n\
2646 "));
2647
2648   add_prefix_cmd ("tfind", class_trace, trace_find_command, _("\
2649 Select a trace frame;\n\
2650 No argument means forward by one frame; '-' means backward by one frame."),
2651                   &tfindlist, "tfind ", 1, &cmdlist);
2652
2653   add_cmd ("outside", class_trace, trace_find_outside_command, _("\
2654 Select a trace frame whose PC is outside the given range.\n\
2655 Usage: tfind outside addr1, addr2"),
2656            &tfindlist);
2657
2658   add_cmd ("range", class_trace, trace_find_range_command, _("\
2659 Select a trace frame whose PC is in the given range.\n\
2660 Usage: tfind range addr1,addr2"),
2661            &tfindlist);
2662
2663   add_cmd ("line", class_trace, trace_find_line_command, _("\
2664 Select a trace frame by source line.\n\
2665 Argument can be a line number (with optional source file), \n\
2666 a function name, or '*' followed by an address.\n\
2667 Default argument is 'the next source line that was traced'."),
2668            &tfindlist);
2669
2670   add_cmd ("tracepoint", class_trace, trace_find_tracepoint_command, _("\
2671 Select a trace frame by tracepoint number.\n\
2672 Default is the tracepoint for the current trace frame."),
2673            &tfindlist);
2674
2675   add_cmd ("pc", class_trace, trace_find_pc_command, _("\
2676 Select a trace frame by PC.\n\
2677 Default is the current PC, or the PC of the current trace frame."),
2678            &tfindlist);
2679
2680   add_cmd ("end", class_trace, trace_find_end_command, _("\
2681 Synonym for 'none'.\n\
2682 De-select any trace frame and resume 'live' debugging."),
2683            &tfindlist);
2684
2685   add_cmd ("none", class_trace, trace_find_none_command,
2686            _("De-select any trace frame and resume 'live' debugging."),
2687            &tfindlist);
2688
2689   add_cmd ("start", class_trace, trace_find_start_command,
2690            _("Select the first trace frame in the trace buffer."),
2691            &tfindlist);
2692
2693   add_com ("tstatus", class_trace, trace_status_command,
2694            _("Display the status of the current trace data collection."));
2695
2696   add_com ("tstop", class_trace, trace_stop_command,
2697            _("Stop trace data collection."));
2698
2699   add_com ("tstart", class_trace, trace_start_command,
2700            _("Start trace data collection."));
2701
2702   add_com ("end", class_trace, end_actions_pseudocommand, _("\
2703 Ends a list of commands or actions.\n\
2704 Several GDB commands allow you to enter a list of commands or actions.\n\
2705 Entering \"end\" on a line by itself is the normal way to terminate\n\
2706 such a list.\n\n\
2707 Note: the \"end\" command cannot be used at the gdb prompt."));
2708
2709   add_com ("while-stepping", class_trace, while_stepping_pseudocommand, _("\
2710 Specify single-stepping behavior at a tracepoint.\n\
2711 Argument is number of instructions to trace in single-step mode\n\
2712 following the tracepoint.  This command is normally followed by\n\
2713 one or more \"collect\" commands, to specify what to collect\n\
2714 while single-stepping.\n\n\
2715 Note: this command can only be used in a tracepoint \"actions\" list."));
2716
2717   add_com_alias ("ws", "while-stepping", class_alias, 0);
2718   add_com_alias ("stepping", "while-stepping", class_alias, 0);
2719
2720   add_com ("collect", class_trace, collect_pseudocommand, _("\
2721 Specify one or more data items to be collected at a tracepoint.\n\
2722 Accepts a comma-separated list of (one or more) expressions.  GDB will\n\
2723 collect all data (variables, registers) referenced by that expression.\n\
2724 Also accepts the following special arguments:\n\
2725     $regs   -- all registers.\n\
2726     $args   -- all function arguments.\n\
2727     $locals -- all variables local to the block/function scope.\n\
2728 Note: this command can only be used in a tracepoint \"actions\" list."));
2729
2730   add_com ("teval", class_trace, teval_pseudocommand, _("\
2731 Specify one or more expressions to be evaluated at a tracepoint.\n\
2732 Accepts a comma-separated list of (one or more) expressions.\n\
2733 The result of each evaluation will be discarded.\n\
2734 Note: this command can only be used in a tracepoint \"actions\" list."));
2735
2736   add_com ("actions", class_trace, trace_actions_command, _("\
2737 Specify the actions to be taken at a tracepoint.\n\
2738 Tracepoint actions may include collecting of specified data, \n\
2739 single-stepping, or enabling/disabling other tracepoints, \n\
2740 depending on target's capabilities."));
2741
2742   default_collect = xstrdup ("");
2743   add_setshow_string_cmd ("default-collect", class_trace,
2744                           &default_collect, _("\
2745 Set the list of expressions to collect by default"), _("\
2746 Show the list of expressions to collect by default"), NULL,
2747                           NULL, NULL,
2748                           &setlist, &showlist);
2749
2750   target_buf_size = 2048;
2751   target_buf = xmalloc (target_buf_size);
2752 }