1076530cdb0d7a9598f7b84ee4aaf3eba1fd35de
[external/binutils.git] / gdb / gdbserver / tracepoint.c
1 /* Tracepoint code for remote server for GDB.
2    Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include "server.h"
20 #include <ctype.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <sys/time.h>
24
25 static void trace_debug_1 (const char *, ...) ATTR_FORMAT (printf, 1, 2);
26
27 static void
28 trace_debug_1 (const char *fmt, ...)
29 {
30   char buf[1024];
31   va_list ap;
32
33   va_start (ap, fmt);
34   vsprintf (buf, fmt, ap);
35   fprintf (stderr, "gdbserver/tracepoint: %s\n", buf);
36   va_end (ap);
37 }
38
39 #define trace_debug(FMT, args...)               \
40   do {                                          \
41     if (debug_threads)                          \
42       trace_debug_1 ((FMT), ##args);            \
43   } while (0)
44
45 static int
46 tracepoint_handler (CORE_ADDR address)
47 {
48   trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
49                paddress (address));
50   return 0;
51 }
52
53 /* This enum must exactly match what is documented in
54    gdb/doc/agentexpr.texi, including all the numerical values.  */
55
56 enum gdb_agent_op
57   {
58     gdb_agent_op_float = 0x01,
59     gdb_agent_op_add = 0x02,
60     gdb_agent_op_sub = 0x03,
61     gdb_agent_op_mul = 0x04,
62     gdb_agent_op_div_signed = 0x05,
63     gdb_agent_op_div_unsigned = 0x06,
64     gdb_agent_op_rem_signed = 0x07,
65     gdb_agent_op_rem_unsigned = 0x08,
66     gdb_agent_op_lsh = 0x09,
67     gdb_agent_op_rsh_signed = 0x0a,
68     gdb_agent_op_rsh_unsigned = 0x0b,
69     gdb_agent_op_trace = 0x0c,
70     gdb_agent_op_trace_quick = 0x0d,
71     gdb_agent_op_log_not = 0x0e,
72     gdb_agent_op_bit_and = 0x0f,
73     gdb_agent_op_bit_or = 0x10,
74     gdb_agent_op_bit_xor = 0x11,
75     gdb_agent_op_bit_not = 0x12,
76     gdb_agent_op_equal = 0x13,
77     gdb_agent_op_less_signed = 0x14,
78     gdb_agent_op_less_unsigned = 0x15,
79     gdb_agent_op_ext = 0x16,
80     gdb_agent_op_ref8 = 0x17,
81     gdb_agent_op_ref16 = 0x18,
82     gdb_agent_op_ref32 = 0x19,
83     gdb_agent_op_ref64 = 0x1a,
84     gdb_agent_op_ref_float = 0x1b,
85     gdb_agent_op_ref_double = 0x1c,
86     gdb_agent_op_ref_long_double = 0x1d,
87     gdb_agent_op_l_to_d = 0x1e,
88     gdb_agent_op_d_to_l = 0x1f,
89     gdb_agent_op_if_goto = 0x20,
90     gdb_agent_op_goto = 0x21,
91     gdb_agent_op_const8 = 0x22,
92     gdb_agent_op_const16 = 0x23,
93     gdb_agent_op_const32 = 0x24,
94     gdb_agent_op_const64 = 0x25,
95     gdb_agent_op_reg = 0x26,
96     gdb_agent_op_end = 0x27,
97     gdb_agent_op_dup = 0x28,
98     gdb_agent_op_pop = 0x29,
99     gdb_agent_op_zero_ext = 0x2a,
100     gdb_agent_op_swap = 0x2b,
101     gdb_agent_op_getv = 0x2c,
102     gdb_agent_op_setv = 0x2d,
103     gdb_agent_op_tracev = 0x2e,
104     gdb_agent_op_trace16 = 0x30,
105     gdb_agent_op_last
106   };
107
108 static const char *gdb_agent_op_names [gdb_agent_op_last] =
109   {
110     "?undef?",
111     "float",
112     "add",
113     "sub",
114     "mul",
115     "div_signed",
116     "div_unsigned",
117     "rem_signed",
118     "rem_unsigned",
119     "lsh",
120     "rsh_signed",
121     "rsh_unsigned",
122     "trace",
123     "trace_quick",
124     "log_not",
125     "bit_and",
126     "bit_or",
127     "bit_xor",
128     "bit_not",
129     "equal",
130     "less_signed",
131     "less_unsigned",
132     "ext",
133     "ref8",
134     "ref16",
135     "ref32",
136     "ref64",
137     "ref_float",
138     "ref_double",
139     "ref_long_double",
140     "l_to_d",
141     "d_to_l",
142     "if_goto",
143     "goto",
144     "const8",
145     "const16",
146     "const32",
147     "const64",
148     "reg",
149     "end",
150     "dup",
151     "pop",
152     "zero_ext",
153     "swap",
154     "getv",
155     "setv",
156     "tracev",
157     "?undef?",
158     "trace16",
159   };
160
161 struct agent_expr
162 {
163   int length;
164
165   unsigned char *bytes;
166 };
167
168 /* Base action.  Concrete actions inherit this.  */
169
170 struct tracepoint_action
171 {
172   char type;
173 };
174
175 /* An 'M' (collect memory) action.  */
176 struct collect_memory_action
177 {
178   struct tracepoint_action base;
179
180   ULONGEST addr;
181   ULONGEST len;
182   int basereg;
183 };
184
185 /* An 'R' (collect registers) action.  */
186
187 struct collect_registers_action
188 {
189   struct tracepoint_action base;
190 };
191
192 /* An 'X' (evaluate expression) action.  */
193
194 struct eval_expr_action
195 {
196   struct tracepoint_action base;
197
198   struct agent_expr *expr;
199 };
200
201 /* An 'L' (collect static trace data) action.  */
202 struct collect_static_trace_data_action
203 {
204   struct tracepoint_action base;
205 };
206
207 /* This structure describes a piece of the source-level definition of
208    the tracepoint.  The contents are not interpreted by the target,
209    but preserved verbatim for uploading upon reconnection.  */
210
211 struct source_string
212 {
213   /* The type of string, such as "cond" for a conditional.  */
214   char *type;
215
216   /* The source-level string itself.  For the sake of target
217      debugging, we store it in plaintext, even though it is always
218      transmitted in hex.  */
219   char *str;
220
221   /* Link to the next one in the list.  We link them in the order
222      received, in case some make up an ordered list of commands or
223      some such.  */
224   struct source_string *next;
225 };
226
227 struct tracepoint_hit_ctx;
228
229 /* The definition of a tracepoint.  */
230
231 /* Tracepoints may have multiple locations, each at a different
232    address.  This can occur with optimizations, template
233    instantiation, etc.  Since the locations may be in different
234    scopes, the conditions and actions may be different for each
235    location.  Our target version of tracepoints is more like GDB's
236    notion of "breakpoint locations", but we have almost nothing that
237    is not per-location, so we bother having two kinds of objects.  The
238    key consequence is that numbers are not unique, and that it takes
239    both number and address to identify a tracepoint uniquely.  */
240
241 struct tracepoint
242 {
243   /* The number of the tracepoint, as specified by GDB.  Several
244      tracepoint objects here may share a number.  */
245   int number;
246
247   /* Address at which the tracepoint is supposed to trigger.  Several
248      tracepoints may share an address.  */
249   CORE_ADDR address;
250
251   /* True if the tracepoint is currently enabled.  */
252   int enabled;
253
254   /* The number of single steps that will be performed after each
255      tracepoint hit.  */
256   long step_count;
257
258   /* The number of times the tracepoint may be hit before it will
259      terminate the entire tracing run.  */
260   long pass_count;
261
262   /* Pointer to the agent expression that is the tracepoint's
263      conditional, or NULL if the tracepoint is unconditional.  */
264   struct agent_expr *cond;
265
266   /* The list of actions to take when the tracepoint triggers.  */
267   int numactions;
268   struct tracepoint_action **actions;
269   /* Same, but in string/packet form.  */
270   char **actions_str;
271
272   /* The list of actions to take while in a stepping loop.  */
273   int num_step_actions;
274   struct tracepoint_action **step_actions;
275   /* Same, but in string/packet form.  */
276   char **step_actions_str;
277
278   /* Count of the times we've hit this tracepoint during the run.
279      Note that while-stepping steps are not counted as "hits".  */
280   long hit_count;
281
282   /* The collection of strings that describe the tracepoint as it was
283      entered into GDB.  These are not used by the target, but are
284      reported back to GDB upon reconnection.  */
285   struct source_string *source_strings;
286
287   /* Handle returned by the breakpoint module when we inserted the
288      trap.  NULL if we haven't inserted it yet.  */
289   void *handle;
290
291   /* Link to the next tracepoint in the list.  */
292   struct tracepoint *next;
293 };
294
295 /* Given `while-stepping', a thread may be collecting data for more
296    than one tracepoint simultaneously.  On the other hand, the same
297    tracepoint with a while-stepping action may be hit by more than one
298    thread simultaneously (but not quite, each thread could be handling
299    a different step).  Each thread holds a list of these objects,
300    representing the current step of each while-stepping action being
301    collected.  */
302
303 struct wstep_state
304 {
305   struct wstep_state *next;
306
307   /* The tracepoint number.  */
308   int tp_number;
309   /* The tracepoint's address.  */
310   CORE_ADDR tp_address;
311
312   /* The number of the current step in this 'while-stepping'
313      action.  */
314   long current_step;
315 };
316
317 /* The linked list of all tracepoints.  */
318
319 static struct tracepoint *tracepoints;
320
321 /* Pointer to the last tracepoint in the list, new tracepoints are
322    linked in at the end.  */
323
324 static struct tracepoint *last_tracepoint;
325
326 /* The first tracepoint to exceed its pass count.  */
327
328 static struct tracepoint *stopping_tracepoint;
329
330 /* True if the trace buffer is full or otherwise no longer usable.  */
331
332 static int trace_buffer_is_full;
333
334 /* Enumeration of the different kinds of things that can happen during
335    agent expression evaluation.  */
336
337 enum eval_result_type
338   {
339     expr_eval_no_error,
340     expr_eval_empty_expression,
341     expr_eval_empty_stack,
342     expr_eval_stack_overflow,
343     expr_eval_stack_underflow,
344     expr_eval_unhandled_opcode,
345     expr_eval_unrecognized_opcode,
346     expr_eval_divide_by_zero,
347     expr_eval_invalid_goto
348   };
349
350 static enum eval_result_type expr_eval_result = expr_eval_no_error;
351
352 static const char *eval_result_names[] =
353   {
354     "terror:in the attic",  /* this should never be reported */
355     "terror:empty expression",
356     "terror:empty stack",
357     "terror:stack overflow",
358     "terror:stack underflow",
359     "terror:unhandled opcode",
360     "terror:unrecognized opcode",
361     "terror:divide by zero"
362   };
363
364 /* The tracepoint in which the error occurred.  */
365
366 static struct tracepoint *error_tracepoint;
367
368 struct trace_state_variable
369 {
370   /* This is the name of the variable as used in GDB.  The target
371      doesn't use the name, but needs to have it for saving and
372      reconnection purposes.  */
373   char *name;
374
375   /* This number identifies the variable uniquely.  Numbers may be
376      assigned either by the target (in the case of builtin variables),
377      or by GDB, and are presumed unique during the course of a trace
378      experiment.  */
379   int number;
380
381   /* The variable's initial value, a 64-bit signed integer always.  */
382   LONGEST initial_value;
383
384   /* The variable's value, a 64-bit signed integer always.  */
385   LONGEST value;
386
387   /* Pointer to a getter function, used to supply computed values.  */
388   LONGEST (*getter) (void);
389
390   /* Link to the next variable.  */
391   struct trace_state_variable *next;
392 };
393
394 /* Linked list of all trace state variables.  */
395
396 static struct trace_state_variable *trace_state_variables;
397
398 /* The results of tracing go into a fixed-size space known as the
399    "trace buffer".  Because usage follows a limited number of
400    patterns, we manage it ourselves rather than with malloc.  Basic
401    rules are that we create only one trace frame at a time, each is
402    variable in size, they are never moved once created, and we only
403    discard if we are doing a circular buffer, and then only the oldest
404    ones.  Each trace frame includes its own size, so we don't need to
405    link them together, and the trace frame number is relative to the
406    first one, so we don't need to record numbers.  A trace frame also
407    records the number of the tracepoint that created it.  The data
408    itself is a series of blocks, each introduced by a single character
409    and with a defined format.  Each type of block has enough
410    type/length info to allow scanners to jump quickly from one block
411    to the next without reading each byte in the block.  */
412
413 /* Trace buffer management would be simple - advance a free pointer
414    from beginning to end, then stop - were it not for the circular
415    buffer option, which is a useful way to prevent a trace run from
416    stopping prematurely because the buffer filled up.  In the circular
417    case, the location of the first trace frame (trace_buffer_start)
418    moves as old trace frames are discarded.  Also, since we grow trace
419    frames incrementally as actions are performed, we wrap around to
420    the beginning of the trace buffer.  This is per-block, so each
421    block within a trace frame remains contiguous.  Things get messy
422    when the wrapped-around trace frame is the one being discarded; the
423    free space ends up in two parts at opposite ends of the buffer.  */
424
425 #ifndef ATTR_PACKED
426 #  if defined(__GNUC__)
427 #    define ATTR_PACKED __attribute__ ((packed))
428 #  else
429 #    define ATTR_PACKED /* nothing */
430 #  endif
431 #endif
432
433 /* The data collected at a tracepoint hit.  This object should be as
434    small as possible, since there may be a great many of them.  We do
435    not need to keep a frame number, because they are all sequential
436    and there are no deletions; so the Nth frame in the buffer is
437    always frame number N.  */
438
439 struct traceframe
440 {
441   /* Number of the tracepoint that collected this traceframe.  A value
442      of 0 indicates the current end of the trace buffer.  We make this
443      a 16-bit field because it's never going to happen that GDB's
444      numbering of tracepoints reaches 32,000.  */
445   int tpnum : 16;
446
447   /* The size of the data in this trace frame.  We limit this to 32
448      bits, even on a 64-bit target, because it's just implausible that
449      one is validly going to collect 4 gigabytes of data at a single
450      tracepoint hit.  */
451   unsigned int data_size : 32;
452
453   /* The base of the trace data, which is contiguous from this point.  */
454   unsigned char data[0];
455
456 } ATTR_PACKED traceframe_t;
457
458 /* The traceframe to be used as the source of data to send back to
459    GDB.  A value of -1 means to get data from the live program.  */
460
461 int current_traceframe = -1;
462
463 /* This flag is true if the trace buffer is circular, meaning that
464    when it fills, the oldest trace frames are discarded in order to
465    make room.  */
466
467 static int circular_trace_buffer;
468
469 /* Pointer to the block of memory that traceframes all go into.  */
470
471 static unsigned char *trace_buffer_lo;
472
473 /* Pointer to the end of the trace buffer, more precisely to the byte
474    after the end of the buffer.  */
475
476 static unsigned char *trace_buffer_hi;
477
478 /* Pointer to the first trace frame in the buffer.  In the
479    non-circular case, this is equal to trace_buffer_lo, otherwise it
480    moves around in the buffer.  */
481
482 static unsigned char *trace_buffer_start;
483
484 /* Pointer to the free part of the trace buffer.  Note that we clear
485    several bytes at and after this pointer, so that traceframe
486    scans/searches terminate properly.  */
487
488 static unsigned char *trace_buffer_free;
489
490 /* Pointer to the byte after the end of the free part.  Note that this
491    may be smaller than trace_buffer_free in the circular case, and
492    means that the free part is in two pieces.  Initially it is equal
493    to trace_buffer_hi, then is generally equivalent to
494    trace_buffer_start.  */
495
496 static unsigned char *trace_buffer_end_free;
497
498 /* Pointer to the wraparound.  If not equal to trace_buffer_hi, then
499    this is the point at which the trace data breaks, and resumes at
500    trace_buffer_lo.  */
501
502 static unsigned char *trace_buffer_wrap;
503
504 /* Macro that returns a pointer to the first traceframe in the buffer.  */
505
506 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
507
508 /* Macro that returns a pointer to the next traceframe in the buffer.
509    If the computed location is beyond the wraparound point, subtract
510    the offset of the wraparound.  */
511
512 #define NEXT_TRACEFRAME_1(TF) \
513   (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
514
515 #define NEXT_TRACEFRAME(TF) \
516   ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF)  \
517                           - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
518                              ? (trace_buffer_wrap - trace_buffer_lo)    \
519                              : 0)))
520
521 /* The difference between these counters represents the total number
522    of complete traceframes present in the trace buffer.  */
523
524 static unsigned int traceframe_write_count;
525 static unsigned int traceframe_read_count;
526
527 /* Convenience macro.  */
528
529 #define traceframe_count \
530   ((unsigned int) (traceframe_write_count - traceframe_read_count))
531
532 /* The count of all traceframes created in the current run, including
533    ones that were discarded to make room.  */
534
535 static int traceframes_created;
536
537 /* Read-only regions are address ranges whose contents don't change,
538    and so can be read from target memory even while looking at a trace
539    frame.  Without these, disassembly for instance will likely fail,
540    because the program code is not usually collected into a trace
541    frame.  This data structure does not need to be very complicated or
542    particularly efficient, it's only going to be used occasionally,
543    and only by some commands.  */
544
545 struct readonly_region
546 {
547   /* The bounds of the region.  */
548   CORE_ADDR start, end;
549
550   /* Link to the next one.  */
551   struct readonly_region *next;
552 };
553
554 /* Linked list of readonly regions.  This list stays in effect from
555    one tstart to the next.  */
556
557 static struct readonly_region *readonly_regions;
558
559 /* The global that controls tracing overall.  */
560
561 int tracing;
562
563 /* Controls whether tracing should continue after GDB disconnects.  */
564
565 int disconnected_tracing;
566
567 /* The reason for the last tracing run to have stopped.  We initialize
568    to a distinct string so that GDB can distinguish between "stopped
569    after running" and "stopped because never run" cases.  */
570
571 static const char *tracing_stop_reason = "tnotrun";
572
573 static int tracing_stop_tpnum;
574
575 /* Functions local to this file.  */
576
577 /* Base "class" for tracepoint type specific data to be passed down to
578    collect_data_at_tracepoint. */
579 struct tracepoint_hit_ctx
580 {
581   /* empty */
582 };
583
584 /* Trap tracepoint specific data to be passed down to
585    collect_data_at_tracepoint.  */
586
587 struct trap_tracepoint_ctx
588 {
589   struct tracepoint_hit_ctx base;
590
591   struct regcache *regcache;
592 };
593
594 static struct agent_expr *parse_agent_expr (char **actparm);
595 static char *unparse_agent_expr (struct agent_expr *aexpr);
596 static enum eval_result_type eval_agent_expr (struct tracepoint_hit_ctx *ctx,
597                                               struct traceframe *tframe,
598                                               struct agent_expr *aexpr,
599                                               ULONGEST *rslt);
600
601 static int agent_mem_read (struct traceframe *tframe,
602                            unsigned char *to, CORE_ADDR from, ULONGEST len);
603 static int agent_tsv_read (struct traceframe *tframe, int n);
604
605 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
606 static int traceframe_read_tsv (int num, LONGEST *val);
607
608 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
609                                          struct tracepoint *tpoint);
610
611 static void clear_readonly_regions (void);
612 static void clear_installed_tracepoints (void);
613
614 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
615                                         CORE_ADDR stop_pc,
616                                         struct tracepoint *tpoint);
617
618 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
619                                   CORE_ADDR stop_pc,
620                                   struct tracepoint *tpoint, int current_step);
621
622 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
623                                      CORE_ADDR stop_pc,
624                                      struct tracepoint *tpoint,
625                                      struct traceframe *tframe,
626                                      struct tracepoint_action *taction);
627
628 /* Record that an error occurred during expression evaluation.  */
629
630 static void
631 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
632                          enum eval_result_type rtype)
633 {
634   trace_debug ("Tracepoint %d at %s %s eval reports error %d",
635                tpoint->number, paddress (tpoint->address), which, rtype);
636
637   expr_eval_result = rtype;
638   error_tracepoint = tpoint;
639 }
640
641 /* Trace buffer management.  */
642
643 static void
644 clear_trace_buffer (void)
645 {
646   trace_buffer_start = trace_buffer_lo;
647   trace_buffer_free = trace_buffer_lo;
648   trace_buffer_end_free = trace_buffer_hi;
649   trace_buffer_wrap = trace_buffer_hi;
650   /* A traceframe with zeroed fields marks the end of trace data.  */
651   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
652   ((struct traceframe *) trace_buffer_free)->data_size = 0;
653   traceframe_read_count = traceframe_write_count = 0;
654   traceframes_created = 0;
655 }
656
657 static void
658 init_trace_buffer (unsigned char *buf, int bufsize)
659 {
660   trace_buffer_lo = buf;
661   trace_buffer_hi = trace_buffer_lo + bufsize;
662
663   clear_trace_buffer ();
664 }
665
666 /* Carve out a piece of the trace buffer, returning NULL in case of
667    failure.  */
668
669 static void *
670 trace_buffer_alloc (size_t amt)
671 {
672   unsigned char *rslt;
673   struct traceframe *oldest;
674   unsigned char *new_start;
675
676   trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
677                (long) amt, (long) sizeof (struct traceframe));
678
679   /* Account for the EOB marker.  */
680   amt += sizeof (struct traceframe);
681
682   /* Offsets are easier to grok for debugging than raw addresses,
683      especially for the small trace buffer sizes that are useful for
684      testing.  */
685   trace_debug ("Trace buffer start=%d free=%d endfree=%d wrap=%d hi=%d",
686                (int) (trace_buffer_start - trace_buffer_lo),
687                (int) (trace_buffer_free - trace_buffer_lo),
688                (int) (trace_buffer_end_free - trace_buffer_lo),
689                (int) (trace_buffer_wrap - trace_buffer_lo),
690                (int) (trace_buffer_hi - trace_buffer_lo));
691
692   /* The algorithm here is to keep trying to get a contiguous block of
693      the requested size, possibly discarding older traceframes to free
694      up space.  Since free space might come in one or two pieces,
695      depending on whether discarded traceframes wrapped around at the
696      high end of the buffer, we test both pieces after each
697      discard.  */
698   while (1)
699     {
700       /* First, if we have two free parts, try the upper one first.  */
701       if (trace_buffer_end_free < trace_buffer_free)
702         {
703           if (trace_buffer_free + amt <= trace_buffer_hi)
704             /* We have enough in the upper part.  */
705             break;
706           else
707             {
708               /* Our high part of free space wasn't enough.  Give up
709                  on it for now, set wraparound.  We will recover the
710                  space later, if/when the wrapped-around traceframe is
711                  discarded.  */
712               trace_debug ("Upper part too small, setting wraparound");
713               trace_buffer_wrap = trace_buffer_free;
714               trace_buffer_free = trace_buffer_lo;
715             }
716         }
717
718       /* The normal case.  */
719       if (trace_buffer_free + amt <= trace_buffer_end_free)
720         break;
721
722       /* If we're here, then neither part is big enough, and
723          non-circular trace buffers are now full.  */
724       if (!circular_trace_buffer)
725         {
726           trace_debug ("Not enough space in the trace buffer");
727           return NULL;
728         }
729
730       trace_debug ("Need more space in the trace buffer");
731
732       /* If we have a circular buffer, we can try discarding the
733          oldest traceframe and see if that helps.  */
734       oldest = FIRST_TRACEFRAME ();
735       if (oldest->tpnum == 0)
736         {
737           /* Not good; we have no traceframes to free.  Perhaps we're
738              asking for a block that is larger than the buffer?  In
739              any case, give up.  */
740           trace_debug ("No traceframes to discard");
741           return NULL;
742         }
743
744       --traceframe_write_count;
745
746       new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
747       /* If we freed the traceframe that wrapped around, go back
748          to the non-wrap case.  */
749       if (new_start < trace_buffer_start)
750         {
751           trace_debug ("Discarding past the wraparound");
752           trace_buffer_wrap = trace_buffer_hi;
753         }
754       trace_buffer_start = new_start;
755       trace_buffer_end_free = trace_buffer_start;
756
757       trace_debug ("Discarded a traceframe\n"
758                    "Trace buffer, start=%d free=%d endfree=%d wrap=%d hi=%d",
759                    (int) (trace_buffer_start - trace_buffer_lo),
760                    (int) (trace_buffer_free - trace_buffer_lo),
761                    (int) (trace_buffer_end_free - trace_buffer_lo),
762                    (int) (trace_buffer_wrap - trace_buffer_lo),
763                    (int) (trace_buffer_hi - trace_buffer_lo));
764
765       /* Now go back around the loop.  The discard might have resulted
766          in either one or two pieces of free space, so we want to try
767          both before freeing any more traceframes.  */
768     }
769
770   /* If we get here, we know we can provide the asked-for space.  */
771
772   rslt = trace_buffer_free;
773
774   /* Adjust the request back down, now that we know we have space for
775      the marker.  */
776   trace_buffer_free += (amt - sizeof (struct traceframe));
777
778   /* We have a new piece of the trace buffer.  Hurray!  */
779
780   /* Add an EOB marker just past this allocation.  */
781   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
782   ((struct traceframe *) trace_buffer_free)->data_size = 0;
783
784   /* Adjust the request back down, now that we know we have space for
785      the marker.  */
786   amt -= sizeof (struct traceframe);
787
788   if (debug_threads)
789     {
790       trace_debug ("Allocated %d bytes", (int) amt);
791       trace_debug ("Trace buffer start=%d free=%d endfree=%d wrap=%d hi=%d",
792                    (int) (trace_buffer_start - trace_buffer_lo),
793                    (int) (trace_buffer_free - trace_buffer_lo),
794                    (int) (trace_buffer_end_free - trace_buffer_lo),
795                    (int) (trace_buffer_wrap - trace_buffer_lo),
796                    (int) (trace_buffer_hi - trace_buffer_lo));
797     }
798
799   return rslt;
800 }
801
802 /* Return the total free space.  This is not necessarily the largest
803    block we can allocate, because of the two-part case.  */
804
805 static int
806 free_space (void)
807 {
808   if (trace_buffer_free <= trace_buffer_end_free)
809     return trace_buffer_end_free - trace_buffer_free;
810   else
811     return ((trace_buffer_end_free - trace_buffer_lo)
812             + (trace_buffer_hi - trace_buffer_free));
813 }
814
815 /* An 'S' in continuation packets indicates remainder are for
816    while-stepping.  */
817
818 static int seen_step_action_flag;
819
820 /* Create a tracepoint (location) with given number and address.  */
821
822 static struct tracepoint *
823 add_tracepoint (int num, CORE_ADDR addr)
824 {
825   struct tracepoint *tpoint;
826
827   tpoint = xmalloc (sizeof (struct tracepoint));
828   tpoint->number = num;
829   tpoint->address = addr;
830   tpoint->numactions = 0;
831   tpoint->actions = NULL;
832   tpoint->actions_str = NULL;
833   tpoint->cond = NULL;
834   tpoint->num_step_actions = 0;
835   tpoint->step_actions = NULL;
836   tpoint->step_actions_str = NULL;
837   tpoint->source_strings = NULL;
838   tpoint->handle = NULL;
839   tpoint->next = NULL;
840
841   if (!last_tracepoint)
842     tracepoints = tpoint;
843   else
844     last_tracepoint->next = tpoint;
845   last_tracepoint = tpoint;
846
847   seen_step_action_flag = 0;
848
849   return tpoint;
850 }
851
852 /* Return the tracepoint with the given number and address, or NULL.  */
853
854 static struct tracepoint *
855 find_tracepoint (int id, CORE_ADDR addr)
856 {
857   struct tracepoint *tpoint;
858
859   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
860     if (tpoint->number == id && tpoint->address == addr)
861       return tpoint;
862
863   return NULL;
864 }
865
866 /* There may be several tracepoints with the same number (because they
867    are "locations", in GDB parlance); return the next one after the
868    given tracepoint, or search from the beginning of the list if the
869    first argument is NULL.  */
870
871 static struct tracepoint *
872 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
873 {
874   struct tracepoint *tpoint;
875
876   if (prev_tp)
877     tpoint = prev_tp->next;
878   else
879     tpoint = tracepoints;
880   for (; tpoint; tpoint = tpoint->next)
881     if (tpoint->number == num)
882       return tpoint;
883
884   return NULL;
885 }
886
887 static char *
888 save_string (const char *str, size_t len)
889 {
890   char *s;
891
892   s = xmalloc (len + 1);
893   memcpy (s, str, len);
894   s[len] = '\0';
895
896   return s;
897 }
898
899 /* Append another action to perform when the tracepoint triggers.  */
900
901 static void
902 add_tracepoint_action (struct tracepoint *tpoint, char *packet)
903 {
904   char *act;
905
906   if (*packet == 'S')
907     {
908       seen_step_action_flag = 1;
909       ++packet;
910     }
911
912   act = packet;
913
914   while (*act)
915     {
916       char *act_start = act;
917       struct tracepoint_action *action = NULL;
918
919       switch (*act)
920         {
921         case 'M':
922           {
923             struct collect_memory_action *maction;
924             ULONGEST basereg;
925             int is_neg;
926
927             maction = xmalloc (sizeof *maction);
928             maction->base.type = *act;
929             action = &maction->base;
930
931             ++act;
932             is_neg = (*act == '-');
933             if (*act == '-')
934               ++act;
935             act = unpack_varlen_hex (act, &basereg);
936             ++act;
937             act = unpack_varlen_hex (act, &maction->addr);
938             ++act;
939             act = unpack_varlen_hex (act, &maction->len);
940             maction->basereg = (is_neg
941                                 ? - (int) basereg
942                                 : (int) basereg);
943             trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
944                          pulongest (maction->len),
945                          paddress (maction->addr), maction->basereg);
946             break;
947           }
948         case 'R':
949           {
950             struct collect_registers_action *raction;
951
952             raction = xmalloc (sizeof *raction);
953             raction->base.type = *act;
954             action = &raction->base;
955
956             trace_debug ("Want to collect registers");
957             ++act;
958             /* skip past hex digits of mask for now */
959             while (isxdigit(*act))
960               ++act;
961             break;
962           }
963         case 'S':
964           trace_debug ("Unexpected step action, ignoring");
965           ++act;
966           break;
967         case 'X':
968           {
969             struct eval_expr_action *xaction;
970
971             xaction = xmalloc (sizeof (*xaction));
972             xaction->base.type = *act;
973             action = &xaction->base;
974
975             trace_debug ("Want to evaluate expression");
976             xaction->expr = parse_agent_expr (&act);
977             break;
978           }
979         default:
980           trace_debug ("unknown trace action '%c', ignoring...", *act);
981           break;
982         case '-':
983           break;
984         }
985
986       if (action == NULL)
987         break;
988
989       if (seen_step_action_flag)
990         {
991           tpoint->num_step_actions++;
992
993           tpoint->step_actions
994             = xrealloc (tpoint->step_actions,
995                         (sizeof (*tpoint->step_actions)
996                          * tpoint->num_step_actions));
997           tpoint->step_actions_str
998             = xrealloc (tpoint->step_actions_str,
999                         (sizeof (*tpoint->step_actions_str)
1000                          * tpoint->num_step_actions));
1001           tpoint->step_actions[tpoint->num_step_actions - 1] = action;
1002           tpoint->step_actions_str[tpoint->num_step_actions - 1]
1003             = save_string (act_start, act - act_start);
1004         }
1005       else
1006         {
1007           tpoint->numactions++;
1008           tpoint->actions
1009             = xrealloc (tpoint->actions,
1010                         sizeof (*tpoint->actions) * tpoint->numactions);
1011           tpoint->actions_str
1012             = xrealloc (tpoint->actions_str,
1013                         sizeof (*tpoint->actions_str) * tpoint->numactions);
1014           tpoint->actions[tpoint->numactions - 1] = action;
1015           tpoint->actions_str[tpoint->numactions - 1]
1016             = save_string (act_start, act - act_start);
1017         }
1018     }
1019 }
1020
1021 /* Find or create a trace state variable with the given number.  */
1022
1023 static struct trace_state_variable *
1024 get_trace_state_variable (int num)
1025 {
1026   struct trace_state_variable *tsv;
1027
1028   /* Search for an existing variable.  */
1029   for (tsv = trace_state_variables; tsv; tsv = tsv->next)
1030     if (tsv->number == num)
1031       return tsv;
1032
1033   return NULL;
1034 }
1035
1036 /* Find or create a trace state variable with the given number.  */
1037
1038 static struct trace_state_variable *
1039 create_trace_state_variable (int num)
1040 {
1041   struct trace_state_variable *tsv;
1042
1043   tsv = get_trace_state_variable (num);
1044   if (tsv != NULL)
1045     return tsv;
1046
1047   /* Create a new variable.  */
1048   tsv = xmalloc (sizeof (struct trace_state_variable));
1049   tsv->number = num;
1050   tsv->initial_value = 0;
1051   tsv->value = 0;
1052   tsv->getter = NULL;
1053   tsv->name = NULL;
1054   tsv->next = trace_state_variables;
1055   trace_state_variables = tsv;
1056
1057   return tsv;
1058 }
1059
1060 static LONGEST
1061 get_trace_state_variable_value (int num)
1062 {
1063   struct trace_state_variable *tsv;
1064
1065   tsv = get_trace_state_variable (num);
1066
1067   if (!tsv)
1068     {
1069       trace_debug ("No trace state variable %d, skipping value get", num);
1070       return 0;
1071     }
1072
1073   /* Call a getter function if we have one.  While it's tempting to
1074      set up something to only call the getter once per tracepoint hit,
1075      it could run afoul of thread races. Better to let the getter
1076      handle it directly, if necessary to worry about it.  */
1077   if (tsv->getter)
1078     tsv->value = (tsv->getter) ();
1079
1080   trace_debug ("get_trace_state_variable_value(%d) ==> %s",
1081                num, plongest (tsv->value));
1082
1083   return tsv->value;
1084 }
1085
1086 static void
1087 set_trace_state_variable_value (int num, LONGEST val)
1088 {
1089   struct trace_state_variable *tsv;
1090
1091   tsv = get_trace_state_variable (num);
1092
1093   if (!tsv)
1094     {
1095       trace_debug ("No trace state variable %d, skipping value set", num);
1096       return;
1097     }
1098
1099   tsv->value = val;
1100 }
1101
1102 static void
1103 set_trace_state_variable_name (int num, const char *name)
1104 {
1105   struct trace_state_variable *tsv;
1106
1107   tsv = get_trace_state_variable (num);
1108
1109   if (!tsv)
1110     {
1111       trace_debug ("No trace state variable %d, skipping name set", num);
1112       return;
1113     }
1114
1115   tsv->name = (char *) name;
1116 }
1117
1118 static void
1119 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
1120 {
1121   struct trace_state_variable *tsv;
1122
1123   tsv = get_trace_state_variable (num);
1124
1125   if (!tsv)
1126     {
1127       trace_debug ("No trace state variable %d, skipping getter set", num);
1128       return;
1129     }
1130
1131   tsv->getter = getter;
1132 }
1133
1134 /* Add a raw traceframe for the given tracepoint.  */
1135
1136 static struct traceframe *
1137 add_traceframe (struct tracepoint *tpoint)
1138 {
1139   struct traceframe *tframe;
1140
1141   tframe = trace_buffer_alloc (sizeof (struct traceframe));
1142
1143   if (tframe == NULL)
1144     return NULL;
1145
1146   tframe->tpnum = tpoint->number;
1147   tframe->data_size = 0;
1148
1149   return tframe;
1150 }
1151
1152 /* Add a block to the traceframe currently being worked on.  */
1153
1154 static unsigned char *
1155 add_traceframe_block (struct traceframe *tframe, int amt)
1156 {
1157   unsigned char *block;
1158
1159   if (!tframe)
1160     return NULL;
1161
1162   block = trace_buffer_alloc (amt);
1163
1164   if (!block)
1165     return NULL;
1166
1167   tframe->data_size += amt;
1168
1169   return block;
1170 }
1171
1172 /* Flag that the current traceframe is finished.  */
1173
1174 static void
1175 finish_traceframe (struct traceframe *tframe)
1176 {
1177   ++traceframe_write_count;
1178   ++traceframes_created;
1179 }
1180
1181 /* Given a traceframe number NUM, find the NUMth traceframe in the
1182    buffer.  */
1183
1184 static struct traceframe *
1185 find_traceframe (int num)
1186 {
1187   struct traceframe *tframe;
1188   int tfnum = 0;
1189
1190   for (tframe = FIRST_TRACEFRAME ();
1191        tframe->tpnum != 0;
1192        tframe = NEXT_TRACEFRAME (tframe))
1193     {
1194       if (tfnum == num)
1195         return tframe;
1196       ++tfnum;
1197     }
1198
1199   return NULL;
1200 }
1201
1202 static CORE_ADDR
1203 get_traceframe_address (struct traceframe *tframe)
1204 {
1205   CORE_ADDR addr;
1206   struct tracepoint *tpoint;
1207
1208   addr = traceframe_get_pc (tframe);
1209
1210   if (addr)
1211     return addr;
1212
1213   /* Fallback strategy, will be incorrect for while-stepping frames
1214      and multi-location tracepoints.  */
1215   tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
1216   return tpoint->address;
1217 }
1218
1219 /* Search for the next traceframe whose address is inside or outside
1220    the given range.  */
1221
1222 static struct traceframe *
1223 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
1224                                int *tfnump)
1225 {
1226   struct traceframe *tframe;
1227   CORE_ADDR tfaddr;
1228
1229   *tfnump = current_traceframe + 1;
1230   tframe = find_traceframe (*tfnump);
1231   /* The search is not supposed to wrap around.  */
1232   if (!tframe)
1233     {
1234       *tfnump = -1;
1235       return NULL;
1236     }
1237
1238   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
1239     {
1240       tfaddr = get_traceframe_address (tframe);
1241       if (inside_p
1242           ? (lo <= tfaddr && tfaddr <= hi)
1243           : (lo > tfaddr || tfaddr > hi))
1244         return tframe;
1245       ++*tfnump;
1246     }
1247
1248   *tfnump = -1;
1249   return NULL;
1250 }
1251
1252 /* Search for the next traceframe recorded by the given tracepoint.
1253    Note that for multi-location tracepoints, this will find whatever
1254    location appears first.  */
1255
1256 static struct traceframe *
1257 find_next_traceframe_by_tracepoint (int num, int *tfnump)
1258 {
1259   struct traceframe *tframe;
1260
1261   *tfnump = current_traceframe + 1;
1262   tframe = find_traceframe (*tfnump);
1263   /* The search is not supposed to wrap around.  */
1264   if (!tframe)
1265     {
1266       *tfnump = -1;
1267       return NULL;
1268     }
1269
1270   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
1271     {
1272       if (tframe->tpnum == num)
1273         return tframe;
1274       ++*tfnump;
1275     }
1276
1277   *tfnump = -1;
1278   return NULL;
1279 }
1280
1281 /* Clear all past trace state.  */
1282
1283 static void
1284 cmd_qtinit (char *packet)
1285 {
1286   struct trace_state_variable *tsv, *prev, *next;
1287
1288   /* Make sure we don't try to read from a trace frame.  */
1289   current_traceframe = -1;
1290
1291   trace_debug ("Initializing the trace");
1292
1293   clear_installed_tracepoints ();
1294   clear_readonly_regions ();
1295
1296   tracepoints = NULL;
1297   last_tracepoint = NULL;
1298
1299   /* Clear out any leftover trace state variables.  Ones with target
1300      defined getters should be kept however.  */
1301   prev = NULL;
1302   tsv = trace_state_variables;
1303   while (tsv)
1304     {
1305       trace_debug ("Looking at var %d", tsv->number);
1306       if (tsv->getter == NULL)
1307         {
1308           next = tsv->next;
1309           if (prev)
1310             prev->next = next;
1311           else
1312             trace_state_variables = next;
1313           trace_debug ("Deleting var %d", tsv->number);
1314           free (tsv);
1315           tsv = next;
1316         }
1317       else
1318         {
1319           prev = tsv;
1320           tsv = tsv->next;
1321         }
1322     }
1323
1324   clear_trace_buffer ();
1325
1326   write_ok (packet);
1327 }
1328
1329 /* Restore the program to its pre-tracing state.  This routine may be called
1330    in error situations, so it needs to be careful about only restoring
1331    from known-valid bits.  */
1332
1333 static void
1334 clear_installed_tracepoints (void)
1335 {
1336   struct tracepoint *tpoint;
1337   struct tracepoint *prev_stpoint;
1338
1339   pause_all (1);
1340   cancel_breakpoints ();
1341
1342   prev_stpoint = NULL;
1343
1344   /* Restore any bytes overwritten by tracepoints.  */
1345   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1346     {
1347       if (!tpoint->enabled)
1348         continue;
1349
1350       /* Catch the case where we might try to remove a tracepoint that
1351          was never actually installed.  */
1352       if (tpoint->handle == NULL)
1353         {
1354           trace_debug ("Tracepoint %d at 0x%s was "
1355                        "never installed, nothing to clear",
1356                        tpoint->number, paddress (tpoint->address));
1357           continue;
1358         }
1359
1360       delete_breakpoint (tpoint->handle);
1361       tpoint->handle = NULL;
1362     }
1363
1364   unpause_all (1);
1365 }
1366
1367 /* Parse a packet that defines a tracepoint.  */
1368
1369 static void
1370 cmd_qtdp (char *own_buf)
1371 {
1372   int tppacket;
1373   ULONGEST num;
1374   ULONGEST addr;
1375   ULONGEST count;
1376   struct tracepoint *tpoint;
1377   char *actparm;
1378   char *packet = own_buf;
1379
1380   packet += strlen ("QTDP:");
1381
1382   /* A hyphen at the beginning marks a packet specifying actions for a
1383      tracepoint already supplied.  */
1384   tppacket = 1;
1385   if (*packet == '-')
1386     {
1387       tppacket = 0;
1388       ++packet;
1389     }
1390   packet = unpack_varlen_hex (packet, &num);
1391   ++packet; /* skip a colon */
1392   packet = unpack_varlen_hex (packet, &addr);
1393   ++packet; /* skip a colon */
1394
1395   /* See if we already have this tracepoint.  */
1396   tpoint = find_tracepoint (num, addr);
1397
1398   if (tppacket)
1399     {
1400       /* Duplicate tracepoints are never allowed.  */
1401       if (tpoint)
1402         {
1403           trace_debug ("Tracepoint error: tracepoint %d"
1404                        " at 0x%s already exists",
1405                        (int) num, paddress (addr));
1406           write_enn (own_buf);
1407           return;
1408         }
1409
1410       tpoint = add_tracepoint (num, addr);
1411
1412       tpoint->enabled = (*packet == 'E');
1413       ++packet; /* skip 'E' */
1414       ++packet; /* skip a colon */
1415       packet = unpack_varlen_hex (packet, &count);
1416       tpoint->step_count = count;
1417       ++packet; /* skip a colon */
1418       packet = unpack_varlen_hex (packet, &count);
1419       tpoint->pass_count = count;
1420       /* See if we have any of the additional optional fields.  */
1421       while (*packet == ':')
1422         {
1423           ++packet;
1424           if (*packet == 'X')
1425             {
1426               actparm = (char *) packet;
1427               tpoint->cond = parse_agent_expr (&actparm);
1428               packet = actparm;
1429             }
1430           else if (*packet == '-')
1431             break;
1432           else if (*packet == '\0')
1433             break;
1434           else
1435             trace_debug ("Unknown optional tracepoint field");
1436         }
1437       if (*packet == '-')
1438         trace_debug ("Also has actions\n");
1439
1440       trace_debug ("Defined tracepoint %d at 0x%s, "
1441                    "enabled %d step %ld pass %ld",
1442                    tpoint->number, paddress (tpoint->address),
1443                    tpoint->enabled,
1444                    tpoint->step_count, tpoint->pass_count);
1445     }
1446   else if (tpoint)
1447     add_tracepoint_action (tpoint, packet);
1448   else
1449     {
1450       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
1451                    (int) num, paddress (addr));
1452       write_enn (own_buf);
1453       return;
1454     }
1455
1456   write_ok (own_buf);
1457 }
1458
1459 static void
1460 cmd_qtdpsrc (char *own_buf)
1461 {
1462   ULONGEST num, addr, start, slen;
1463   struct tracepoint *tpoint;
1464   char *packet = own_buf;
1465   char *saved, *srctype, *src;
1466   size_t nbytes;
1467   struct source_string *last, *newlast;
1468
1469   packet += strlen ("QTDPsrc:");
1470
1471   packet = unpack_varlen_hex (packet, &num);
1472   ++packet; /* skip a colon */
1473   packet = unpack_varlen_hex (packet, &addr);
1474   ++packet; /* skip a colon */
1475
1476   /* See if we already have this tracepoint.  */
1477   tpoint = find_tracepoint (num, addr);
1478
1479   if (!tpoint)
1480     {
1481       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
1482                    (int) num, paddress (addr));
1483       write_enn (own_buf);
1484       return;
1485     }
1486
1487   saved = packet;
1488   packet = strchr (packet, ':');
1489   srctype = xmalloc (packet - saved + 1);
1490   memcpy (srctype, saved, packet - saved);
1491   srctype[packet - saved] = '\0';
1492   ++packet;
1493   packet = unpack_varlen_hex (packet, &start);
1494   ++packet; /* skip a colon */
1495   packet = unpack_varlen_hex (packet, &slen);
1496   ++packet; /* skip a colon */
1497   src = xmalloc (slen + 1);
1498   nbytes = unhexify (src, packet, strlen (packet) / 2);
1499   src[nbytes] = '\0';
1500
1501   newlast = xmalloc (sizeof (struct source_string));
1502   newlast->type = srctype;
1503   newlast->str = src;
1504   newlast->next = NULL;
1505   /* Always add a source string to the end of the list;
1506      this keeps sequences of actions/commands in the right
1507      order.  */
1508   if (tpoint->source_strings)
1509     {
1510       for (last = tpoint->source_strings; last->next; last = last->next)
1511         ;
1512       last->next = newlast;
1513     }
1514   else
1515     tpoint->source_strings = newlast;
1516
1517   write_ok (own_buf);
1518 }
1519
1520 static void
1521 cmd_qtdv (char *own_buf)
1522 {
1523   ULONGEST num, val, builtin;
1524   char *varname;
1525   size_t nbytes;
1526   struct trace_state_variable *tsv;
1527   char *packet = own_buf;
1528
1529   packet += strlen ("QTDV:");
1530
1531   packet = unpack_varlen_hex (packet, &num);
1532   ++packet; /* skip a colon */
1533   packet = unpack_varlen_hex (packet, &val);
1534   ++packet; /* skip a colon */
1535   packet = unpack_varlen_hex (packet, &builtin);
1536   ++packet; /* skip a colon */
1537
1538   nbytes = strlen (packet) / 2;
1539   varname = xmalloc (nbytes + 1);
1540   nbytes = unhexify (varname, packet, nbytes);
1541   varname[nbytes] = '\0';
1542
1543   tsv = create_trace_state_variable (num);
1544   tsv->initial_value = (LONGEST) val;
1545   tsv->name = varname;
1546
1547   set_trace_state_variable_value (num, (LONGEST) val);
1548
1549   write_ok (own_buf);
1550 }
1551
1552 static void
1553 cmd_qtv (char *own_buf)
1554 {
1555   ULONGEST num;
1556   LONGEST val;
1557   int err;
1558   char *packet = own_buf;
1559
1560   packet += strlen ("qTV:");
1561   packet = unpack_varlen_hex (packet, &num);
1562
1563   if (current_traceframe >= 0)
1564     {
1565       err = traceframe_read_tsv ((int) num, &val);
1566       if (err)
1567         {
1568           strcpy (own_buf, "U");
1569           return;
1570         }
1571     }
1572   /* Only make tsv's be undefined before the first trace run.  After a
1573      trace run is over, the user might want to see the last value of
1574      the tsv, and it might not be available in a traceframe.  */
1575   else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
1576     {
1577       strcpy (own_buf, "U");
1578       return;
1579     }
1580   else
1581     val = get_trace_state_variable_value (num);
1582
1583   sprintf (own_buf, "V%s", phex_nz (val, 0));
1584 }
1585
1586 /* Clear out the list of readonly regions.  */
1587
1588 static void
1589 clear_readonly_regions (void)
1590 {
1591   struct readonly_region *roreg;
1592
1593   while (readonly_regions)
1594     {
1595       roreg = readonly_regions;
1596       readonly_regions = readonly_regions->next;
1597       free (roreg);
1598     }
1599 }
1600
1601 /* Parse the collection of address ranges whose contents GDB believes
1602    to be unchanging and so can be read directly from target memory
1603    even while looking at a traceframe.  */
1604
1605 static void
1606 cmd_qtro (char *own_buf)
1607 {
1608   ULONGEST start, end;
1609   struct readonly_region *roreg;
1610   char *packet = own_buf;
1611
1612   trace_debug ("Want to mark readonly regions");
1613
1614   clear_readonly_regions ();
1615
1616   packet += strlen ("QTro");
1617
1618   while (*packet == ':')
1619     {
1620       ++packet;  /* skip a colon */
1621       packet = unpack_varlen_hex (packet, &start);
1622       ++packet;  /* skip a comma */
1623       packet = unpack_varlen_hex (packet, &end);
1624       roreg = xmalloc (sizeof (struct readonly_region));
1625       roreg->start = start;
1626       roreg->end = end;
1627       roreg->next = readonly_regions;
1628       readonly_regions = roreg;
1629       trace_debug ("Added readonly region from 0x%s to 0x%s",
1630                    paddress (roreg->start), paddress (roreg->end));
1631     }
1632
1633   write_ok (own_buf);
1634 }
1635
1636 /* Test to see if the given range is in our list of readonly ranges.
1637    We only test for being entirely within a range, GDB is not going to
1638    send a single memory packet that spans multiple regions.  */
1639
1640 int
1641 in_readonly_region (CORE_ADDR addr, ULONGEST length)
1642 {
1643   struct readonly_region *roreg;
1644
1645   for (roreg = readonly_regions; roreg; roreg = roreg->next)
1646     if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
1647       return 1;
1648
1649   return 0;
1650 }
1651
1652 static void
1653 cmd_qtstart (char *packet)
1654 {
1655   struct tracepoint *tpoint;
1656   int slow_tracepoint_count;
1657
1658   trace_debug ("Starting the trace");
1659
1660   slow_tracepoint_count = 0;
1661
1662   *packet = '\0';
1663
1664   /* Pause all threads temporarily while we patch tracepoints.  */
1665   pause_all (1);
1666
1667   /* Install tracepoints.  */
1668   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1669     {
1670       /* Ensure all the hit counts start at zero.  */
1671       tpoint->hit_count = 0;
1672
1673       if (!tpoint->enabled)
1674         continue;
1675
1676       ++slow_tracepoint_count;
1677
1678       /* Tracepoints are installed as memory breakpoints.  Just go
1679          ahead and install the trap.  The breakpoints module handles
1680          duplicated breakpoints, and the memory read routine handles
1681          un-patching traps from memory reads.  */
1682       tpoint->handle = set_breakpoint_at (tpoint->address, tracepoint_handler);
1683
1684       /* Any failure is sufficient cause to give up.  */
1685       if (tpoint->handle == NULL)
1686         break;
1687     }
1688
1689   /* Any error in tracepoint insertion is unacceptable; better to
1690      address the problem now, than end up with a useless or misleading
1691      trace run.  */
1692   if (tpoint != NULL)
1693     {
1694       clear_installed_tracepoints ();
1695       if (*packet == '\0')
1696         write_enn (packet);
1697       unpause_all (1);
1698       return;
1699     }
1700
1701   stopping_tracepoint = NULL;
1702   trace_buffer_is_full = 0;
1703   expr_eval_result = expr_eval_no_error;
1704   error_tracepoint = NULL;
1705
1706   /* Tracing is now active, hits will now start being logged.  */
1707   tracing = 1;
1708
1709   unpause_all (1);
1710
1711   write_ok (packet);
1712 }
1713
1714 /* End a tracing run, filling in a stop reason to report back to GDB,
1715    and removing the tracepoints from the code.  */
1716
1717 void
1718 stop_tracing (void)
1719 {
1720   if (!tracing)
1721     {
1722       trace_debug ("Tracing is already off, ignoring");
1723       return;
1724     }
1725
1726   trace_debug ("Stopping the trace");
1727
1728   /* Pause all threads before removing breakpoints from memory.  */
1729   pause_all (1);
1730   /* Since we're removing breakpoints, cancel breakpoint hits,
1731      possibly related to the breakpoints we're about to delete.  */
1732   cancel_breakpoints ();
1733
1734   /* Stop logging. Tracepoints can still be hit, but they will not be
1735      recorded.  */
1736   tracing = 0;
1737
1738   tracing_stop_reason = "t???";
1739   tracing_stop_tpnum = 0;
1740   if (stopping_tracepoint)
1741     {
1742       trace_debug ("Stopping the trace because "
1743                    "tracepoint %d was hit %ld times",
1744                    stopping_tracepoint->number,
1745                    stopping_tracepoint->pass_count);
1746       tracing_stop_reason = "tpasscount";
1747       tracing_stop_tpnum = stopping_tracepoint->number;
1748     }
1749   else if (trace_buffer_is_full)
1750     {
1751       trace_debug ("Stopping the trace because the trace buffer is full");
1752       tracing_stop_reason = "tfull";
1753     }
1754   else if (expr_eval_result != expr_eval_no_error)
1755     {
1756       trace_debug ("Stopping the trace because of an expression eval error");
1757       tracing_stop_reason = eval_result_names[expr_eval_result];
1758       tracing_stop_tpnum = error_tracepoint->number;
1759     }
1760   else if (!gdb_connected ())
1761     {
1762       trace_debug ("Stopping the trace because GDB disconnected");
1763       tracing_stop_reason = "tdisconnected";
1764     }
1765   else
1766     {
1767       trace_debug ("Stopping the trace because of a tstop command");
1768       tracing_stop_reason = "tstop";
1769     }
1770
1771   stopping_tracepoint = NULL;
1772   error_tracepoint = NULL;
1773
1774   /* Clear out the tracepoints.  */
1775   clear_installed_tracepoints ();
1776
1777   unpause_all (1);
1778 }
1779
1780 static void
1781 cmd_qtstop (char *packet)
1782 {
1783   stop_tracing ();
1784   write_ok (packet);
1785 }
1786
1787 static void
1788 cmd_qtdisconnected (char *own_buf)
1789 {
1790   ULONGEST setting;
1791   char *packet = own_buf;
1792
1793   packet += strlen ("QTDisconnected:");
1794
1795   unpack_varlen_hex (packet, &setting);
1796
1797   write_ok (own_buf);
1798
1799   disconnected_tracing = setting;
1800 }
1801
1802 static void
1803 cmd_qtframe (char *own_buf)
1804 {
1805   ULONGEST frame, pc, lo, hi, num;
1806   int tfnum, tpnum;
1807   struct traceframe *tframe;
1808   char *packet = own_buf;
1809
1810   packet += strlen ("QTFrame:");
1811
1812   if (strncmp (packet, "pc:", strlen ("pc:")) == 0)
1813     {
1814       packet += strlen ("pc:");
1815       packet = unpack_varlen_hex (packet, &pc);
1816       trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
1817       tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
1818     }
1819   else if (strncmp (packet, "range:", strlen ("range:")) == 0)
1820     {
1821       packet += strlen ("range:");
1822       packet = unpack_varlen_hex (packet, &lo);
1823       ++packet;
1824       packet = unpack_varlen_hex (packet, &hi);
1825       trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
1826                    paddress (lo), paddress (hi));
1827       tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
1828     }
1829   else if (strncmp (packet, "outside:", strlen ("outside:")) == 0)
1830     {
1831       packet += strlen ("outside:");
1832       packet = unpack_varlen_hex (packet, &lo);
1833       ++packet;
1834       packet = unpack_varlen_hex (packet, &hi);
1835       trace_debug ("Want to find next traceframe "
1836                    "outside the range 0x%s to 0x%s",
1837                    paddress (lo), paddress (hi));
1838       tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
1839     }
1840   else if (strncmp (packet, "tdp:", strlen ("tdp:")) == 0)
1841     {
1842       packet += strlen ("tdp:");
1843       packet = unpack_varlen_hex (packet, &num);
1844       tpnum = (int) num;
1845       trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
1846       tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
1847     }
1848   else
1849     {
1850       unpack_varlen_hex (packet, &frame);
1851       tfnum = (int) frame;
1852       if (tfnum == -1)
1853         {
1854           trace_debug ("Want to stop looking at traceframes");
1855           current_traceframe = -1;
1856           write_ok (own_buf);
1857           return;
1858         }
1859       trace_debug ("Want to look at traceframe %d", tfnum);
1860       tframe = find_traceframe (tfnum);
1861     }
1862
1863   if (tframe)
1864     {
1865       current_traceframe = tfnum;
1866       sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
1867     }
1868   else
1869     sprintf (own_buf, "F-1");
1870 }
1871
1872 static void
1873 cmd_qtstatus (char *packet)
1874 {
1875   char *stop_reason_rsp = NULL;
1876
1877   trace_debug ("Returning trace status as %d, stop reason %s",
1878                tracing, tracing_stop_reason);
1879
1880   stop_reason_rsp = (char *) tracing_stop_reason;
1881
1882   /* The user visible error string in terror needs to be hex encoded.
1883      We leave it as plain string in `tracepoint_stop_reason' to ease
1884      debugging.  */
1885   if (strncmp (stop_reason_rsp, "terror:", strlen ("terror:")) == 0)
1886     {
1887       const char *result_name;
1888       int hexstr_len;
1889       char *p;
1890
1891       result_name = stop_reason_rsp + strlen ("terror:");
1892       hexstr_len = strlen (result_name) * 2;
1893       p = stop_reason_rsp = alloca (strlen ("terror:") + hexstr_len + 1);
1894       strcpy (p, "terror:");
1895       p += strlen (p);
1896       convert_int_to_ascii ((gdb_byte *) result_name, p, strlen (result_name));
1897     }
1898
1899   sprintf (packet,
1900            "T%d;"
1901            "%s:%x;"
1902            "tframes:%x;tcreated:%x;"
1903            "tfree:%x;tsize:%s;"
1904            "circular:%d;"
1905            "disconn:%d",
1906            tracing ? 1 : 0,
1907            stop_reason_rsp, tracing_stop_tpnum,
1908            traceframe_count, traceframes_created,
1909            free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
1910            circular_trace_buffer,
1911            disconnected_tracing);
1912 }
1913
1914 /* State variables to help return all the tracepoint bits.  */
1915 static struct tracepoint *cur_tpoint;
1916 static int cur_action;
1917 static int cur_step_action;
1918 static struct source_string *cur_source_string;
1919 static struct trace_state_variable *cur_tsv;
1920
1921 /* Compose a response that is an imitation of the syntax by which the
1922    tracepoint was originally downloaded.  */
1923
1924 static void
1925 response_tracepoint (char *packet, struct tracepoint *tpoint)
1926 {
1927   char *buf;
1928
1929   sprintf (packet, "T%x:%s:%c:%lx:%lx", tpoint->number,
1930            paddress (tpoint->address),
1931            (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
1932            tpoint->pass_count);
1933
1934   if (tpoint->cond)
1935     {
1936       buf = unparse_agent_expr (tpoint->cond);
1937       sprintf (packet + strlen (packet), ":X%x,%s",
1938                tpoint->cond->length, buf);
1939       free (buf);
1940     }
1941 }
1942
1943 /* Compose a response that is an imitation of the syntax by which the
1944    tracepoint action was originally downloaded (with the difference
1945    that due to the way we store the actions, this will output a packet
1946    per action, while GDB could have combined more than one action
1947    per-packet.  */
1948
1949 static void
1950 response_action (char *packet, struct tracepoint *tpoint,
1951                  char *taction, int step)
1952 {
1953   sprintf (packet, "%c%x:%s:%s",
1954            (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
1955            taction);
1956 }
1957
1958 /* Compose a response that is an imitation of the syntax by which the
1959    tracepoint source piece was originally downloaded.  */
1960
1961 static void
1962 response_source (char *packet,
1963                  struct tracepoint *tpoint, struct source_string *src)
1964 {
1965   char *buf;
1966   int len;
1967
1968   len = strlen (src->str);
1969   buf = alloca (len * 2 + 1);
1970   convert_int_to_ascii ((gdb_byte *) src->str, buf, len);
1971
1972   sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
1973            tpoint->number, paddress (tpoint->address),
1974            src->type, 0, len, buf);
1975 }
1976
1977 /* Return the first piece of tracepoint definition, and initialize the
1978    state machine that will iterate through all the tracepoint
1979    bits.  */
1980
1981 static void
1982 cmd_qtfp (char *packet)
1983 {
1984   trace_debug ("Returning first tracepoint definition piece");
1985
1986   cur_tpoint = tracepoints;
1987   cur_action = cur_step_action = -1;
1988   cur_source_string = NULL;
1989
1990   if (cur_tpoint)
1991     response_tracepoint (packet, cur_tpoint);
1992   else
1993     strcpy (packet, "l");
1994 }
1995
1996 /* Return additional pieces of tracepoint definition.  Each action and
1997    stepping action must go into its own packet, because of packet size
1998    limits, and so we use state variables to deliver one piece at a
1999    time.  */
2000
2001 static void
2002 cmd_qtsp (char *packet)
2003 {
2004   trace_debug ("Returning subsequent tracepoint definition piece");
2005
2006   if (!cur_tpoint)
2007     {
2008       /* This case would normally never occur, but be prepared for
2009          GDB misbehavior.  */
2010       strcpy (packet, "l");
2011     }
2012   else if (cur_action < cur_tpoint->numactions - 1)
2013     {
2014       ++cur_action;
2015       response_action (packet, cur_tpoint,
2016                        cur_tpoint->actions_str[cur_action], 0);
2017     }
2018   else if (cur_step_action < cur_tpoint->num_step_actions - 1)
2019     {
2020       ++cur_step_action;
2021       response_action (packet, cur_tpoint,
2022                        cur_tpoint->step_actions_str[cur_step_action], 1);
2023     }
2024   else if ((cur_source_string
2025             ? cur_source_string->next
2026             : cur_tpoint->source_strings))
2027     {
2028       if (cur_source_string)
2029         cur_source_string = cur_source_string->next;
2030       else
2031         cur_source_string = cur_tpoint->source_strings;
2032       response_source (packet, cur_tpoint, cur_source_string);
2033     }
2034   else
2035     {
2036       cur_tpoint = cur_tpoint->next;
2037       cur_action = cur_step_action = -1;
2038       cur_source_string = NULL;
2039       if (cur_tpoint)
2040         response_tracepoint (packet, cur_tpoint);
2041       else
2042         strcpy (packet, "l");
2043     }
2044 }
2045
2046 /* Compose a response that is an imitation of the syntax by which the
2047    trace state variable was originally downloaded.  */
2048
2049 static void
2050 response_tsv (char *packet, struct trace_state_variable *tsv)
2051 {
2052   char *buf = (char *) "";
2053   int namelen;
2054
2055   if (tsv->name)
2056     {
2057       namelen = strlen (tsv->name);
2058       buf = alloca (namelen * 2 + 1);
2059       convert_int_to_ascii ((gdb_byte *) tsv->name, buf, namelen);
2060     }
2061
2062   sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
2063            tsv->getter ? 1 : 0, buf);
2064 }
2065
2066 /* Return the first trace state variable definition, and initialize
2067    the state machine that will iterate through all the tsv bits.  */
2068
2069 static void
2070 cmd_qtfv (char *packet)
2071 {
2072   trace_debug ("Returning first trace state variable definition");
2073
2074   cur_tsv = trace_state_variables;
2075
2076   if (cur_tsv)
2077     response_tsv (packet, cur_tsv);
2078   else
2079     strcpy (packet, "l");
2080 }
2081
2082 /* Return additional trace state variable definitions. */
2083
2084 static void
2085 cmd_qtsv (char *packet)
2086 {
2087   trace_debug ("Returning first trace state variable definition");
2088
2089   if (!cur_tpoint)
2090     {
2091       /* This case would normally never occur, but be prepared for
2092          GDB misbehavior.  */
2093       strcpy (packet, "l");
2094     }
2095   else if (cur_tsv)
2096     {
2097       cur_tsv = cur_tsv->next;
2098       if (cur_tsv)
2099         response_tsv (packet, cur_tsv);
2100       else
2101         strcpy (packet, "l");
2102     }
2103   else
2104     strcpy (packet, "l");
2105 }
2106
2107 /* Respond to qTBuffer packet with a block of raw data from the trace
2108    buffer.  GDB may ask for a lot, but we are allowed to reply with
2109    only as much as will fit within packet limits or whatever.  */
2110
2111 static void
2112 cmd_qtbuffer (char *own_buf)
2113 {
2114   ULONGEST offset, num, tot;
2115   unsigned char *tbp;
2116   char *packet = own_buf;
2117
2118   packet += strlen ("qTBuffer:");
2119
2120   packet = unpack_varlen_hex (packet, &offset);
2121   ++packet; /* skip a comma */
2122   packet = unpack_varlen_hex (packet, &num);
2123
2124   trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
2125                (int) num, pulongest (offset));
2126
2127   tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
2128
2129   /* If we're right at the end, reply specially that we're done.  */
2130   if (offset == tot)
2131     {
2132       strcpy (own_buf, "l");
2133       return;
2134     }
2135
2136   /* Object to any other out-of-bounds request.  */
2137   if (offset > tot)
2138     {
2139       write_enn (own_buf);
2140       return;
2141     }
2142
2143   /* Compute the pointer corresponding to the given offset, accounting
2144      for wraparound.  */
2145   tbp = trace_buffer_start + offset;
2146   if (tbp >= trace_buffer_wrap)
2147     tbp -= (trace_buffer_wrap - trace_buffer_lo);
2148
2149   /* Trim to the remaining bytes if we're close to the end.  */
2150   if (num > tot - offset)
2151     num = tot - offset;
2152
2153   /* Trim to available packet size.  */
2154   if (num >= (PBUFSIZ - 16) / 2 )
2155     num = (PBUFSIZ - 16) / 2;
2156
2157   convert_int_to_ascii (tbp, own_buf, num);
2158   own_buf[num] = '\0';
2159 }
2160
2161 static void
2162 cmd_bigqtbuffer (char *own_buf)
2163 {
2164   ULONGEST val;
2165   char *packet = own_buf;
2166
2167   packet += strlen ("QTBuffer:");
2168
2169   if (strncmp ("circular:", packet, strlen ("circular:")) == 0)
2170     {
2171       packet += strlen ("circular:");
2172       packet = unpack_varlen_hex (packet, &val);
2173       circular_trace_buffer = val;
2174       trace_debug ("Trace buffer is now %s",
2175                    circular_trace_buffer ? "circular" : "linear");
2176       write_ok (own_buf);
2177     }
2178   else
2179     write_enn (own_buf);
2180 }
2181
2182 int
2183 handle_tracepoint_general_set (char *packet)
2184 {
2185   if (strcmp ("QTinit", packet) == 0)
2186     {
2187       cmd_qtinit (packet);
2188       return 1;
2189     }
2190   else if (strncmp ("QTDP:", packet, strlen ("QTDP:")) == 0)
2191     {
2192       cmd_qtdp (packet);
2193       return 1;
2194     }
2195   else if (strncmp ("QTDPsrc:", packet, strlen ("QTDPsrc:")) == 0)
2196     {
2197       cmd_qtdpsrc (packet);
2198       return 1;
2199     }
2200   else if (strncmp ("QTDV:", packet, strlen ("QTDV:")) == 0)
2201     {
2202       cmd_qtdv (packet);
2203       return 1;
2204     }
2205   else if (strncmp ("QTro:", packet, strlen ("QTro:")) == 0)
2206     {
2207       cmd_qtro (packet);
2208       return 1;
2209     }
2210   else if (strcmp ("QTStart", packet) == 0)
2211     {
2212       cmd_qtstart (packet);
2213       return 1;
2214     }
2215   else if (strcmp ("QTStop", packet) == 0)
2216     {
2217       cmd_qtstop (packet);
2218       return 1;
2219     }
2220   else if (strncmp ("QTDisconnected:", packet,
2221                     strlen ("QTDisconnected:")) == 0)
2222     {
2223       cmd_qtdisconnected (packet);
2224       return 1;
2225     }
2226   else if (strncmp ("QTFrame:", packet, strlen ("QTFrame:")) == 0)
2227     {
2228       cmd_qtframe (packet);
2229       return 1;
2230     }
2231   else if (strncmp ("QTBuffer:", packet, strlen ("QTBuffer:")) == 0)
2232     {
2233       cmd_bigqtbuffer (packet);
2234       return 1;
2235     }
2236
2237   return 0;
2238 }
2239
2240 int
2241 handle_tracepoint_query (char *packet)
2242 {
2243   if (strcmp ("qTStatus", packet) == 0)
2244     {
2245       cmd_qtstatus (packet);
2246       return 1;
2247     }
2248   else if (strcmp ("qTfP", packet) == 0)
2249     {
2250       cmd_qtfp (packet);
2251       return 1;
2252     }
2253   else if (strcmp ("qTsP", packet) == 0)
2254     {
2255       cmd_qtsp (packet);
2256       return 1;
2257     }
2258   else if (strcmp ("qTfV", packet) == 0)
2259     {
2260       cmd_qtfv (packet);
2261       return 1;
2262     }
2263   else if (strcmp ("qTsV", packet) == 0)
2264     {
2265       cmd_qtsv (packet);
2266       return 1;
2267     }
2268   else if (strncmp ("qTV:", packet, strlen ("qTV:")) == 0)
2269     {
2270       cmd_qtv (packet);
2271       return 1;
2272     }
2273   else if (strncmp ("qTBuffer:", packet, strlen ("qTBuffer:")) == 0)
2274     {
2275       cmd_qtbuffer (packet);
2276       return 1;
2277     }
2278
2279   return 0;
2280 }
2281
2282 /* Call this when thread TINFO has hit the tracepoint defined by
2283    TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
2284    action.  This adds a while-stepping collecting state item to the
2285    threads' collecting state list, so that we can keep track of
2286    multiple simultaneous while-stepping actions being collected by the
2287    same thread.  This can happen in cases like:
2288
2289     ff0001  INSN1 <-- TP1, while-stepping 10 collect $regs
2290     ff0002  INSN2
2291     ff0003  INSN3 <-- TP2, collect $regs
2292     ff0004  INSN4 <-- TP3, while-stepping 10 collect $regs
2293     ff0005  INSN5
2294
2295    Notice that when instruction INSN5 is reached, the while-stepping
2296    actions of both TP1 and TP3 are still being collected, and that TP2
2297    had been collected meanwhile.  The whole range of ff0001-ff0005
2298    should be single-stepped, due to at least TP1's while-stepping
2299    action covering the whole range.  */
2300
2301 static void
2302 add_while_stepping_state (struct thread_info *tinfo,
2303                           int tp_number, CORE_ADDR tp_address)
2304 {
2305   struct wstep_state *wstep;
2306
2307   wstep = xmalloc (sizeof (*wstep));
2308   wstep->next = tinfo->while_stepping;
2309
2310   wstep->tp_number = tp_number;
2311   wstep->tp_address = tp_address;
2312   wstep->current_step = 0;
2313
2314   tinfo->while_stepping = wstep;
2315 }
2316
2317 /* Release the while-stepping collecting state WSTEP.  */
2318
2319 static void
2320 release_while_stepping_state (struct wstep_state *wstep)
2321 {
2322   free (wstep);
2323 }
2324
2325 /* Release all while-stepping collecting states currently associated
2326    with thread TINFO.  */
2327
2328 void
2329 release_while_stepping_state_list (struct thread_info *tinfo)
2330 {
2331   struct wstep_state *head;
2332
2333   while (tinfo->while_stepping)
2334     {
2335       head = tinfo->while_stepping;
2336       tinfo->while_stepping = head->next;
2337       release_while_stepping_state (head);
2338     }
2339 }
2340
2341 /* If TINFO was handling a 'while-stepping' action, the step has
2342    finished, so collect any step data needed, and check if any more
2343    steps are required.  Return true if the thread was indeed
2344    collecting tracepoint data, false otherwise.  */
2345
2346 int
2347 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
2348 {
2349   struct tracepoint *tpoint;
2350   struct wstep_state *wstep;
2351   struct wstep_state **wstep_link;
2352   struct trap_tracepoint_ctx ctx;
2353
2354   /* Check if we were indeed collecting data for one of more
2355      tracepoints with a 'while-stepping' count.  */
2356   if (tinfo->while_stepping == NULL)
2357     return 0;
2358
2359   if (!tracing)
2360     {
2361       /* We're not even tracing anymore.  Stop this thread from
2362          collecting.  */
2363       release_while_stepping_state_list (tinfo);
2364
2365       /* The thread had stopped due to a single-step request indeed
2366          explained by a tracepoint.  */
2367       return 1;
2368     }
2369
2370   wstep = tinfo->while_stepping;
2371   wstep_link = &tinfo->while_stepping;
2372
2373   trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
2374                target_pid_to_str (tinfo->entry.id),
2375                wstep->tp_number, paddress (wstep->tp_address));
2376
2377   ctx.regcache = get_thread_regcache (tinfo, 1);
2378
2379   while (wstep != NULL)
2380     {
2381       tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
2382       if (tpoint == NULL)
2383         {
2384           trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
2385                        wstep->tp_number, paddress (wstep->tp_address),
2386                        target_pid_to_str (tinfo->entry.id));
2387
2388           /* Unlink.  */
2389           *wstep_link = wstep->next;
2390           release_while_stepping_state (wstep);
2391           continue;
2392         }
2393
2394       /* We've just finished one step.  */
2395       ++wstep->current_step;
2396
2397       /* Collect data.  */
2398       collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
2399                             stop_pc, tpoint, wstep->current_step);
2400
2401       if (wstep->current_step >= tpoint->step_count)
2402         {
2403           /* The requested numbers of steps have occurred.  */
2404           trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
2405                        target_pid_to_str (tinfo->entry.id),
2406                        wstep->tp_number, paddress (wstep->tp_address));
2407
2408           /* Unlink the wstep.  */
2409           *wstep_link = wstep->next;
2410           release_while_stepping_state (wstep);
2411           wstep = *wstep_link;
2412
2413           /* Only check the hit count now, which ensure that we do all
2414              our stepping before stopping the run.  */
2415           if (tpoint->pass_count > 0
2416               && tpoint->hit_count >= tpoint->pass_count
2417               && stopping_tracepoint == NULL)
2418             stopping_tracepoint = tpoint;
2419         }
2420       else
2421         {
2422           /* Keep single-stepping until the requested numbers of steps
2423              have occurred.  */
2424           wstep_link = &wstep->next;
2425           wstep = *wstep_link;
2426         }
2427
2428       if (stopping_tracepoint
2429           || trace_buffer_is_full
2430           || expr_eval_result != expr_eval_no_error)
2431         {
2432           stop_tracing ();
2433           break;
2434         }
2435     }
2436
2437   return 1;
2438 }
2439
2440 /* Return true if TINFO just hit a tracepoint.  Collect data if
2441    so.  */
2442
2443 int
2444 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
2445 {
2446   struct tracepoint *tpoint;
2447   int ret = 0;
2448   struct trap_tracepoint_ctx ctx;
2449
2450   /* Not tracing, don't handle.  */
2451   if (!tracing)
2452     return 0;
2453
2454   ctx.regcache = get_thread_regcache (tinfo, 1);
2455
2456   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2457     {
2458       if (tpoint->enabled && stop_pc == tpoint->address)
2459         {
2460           trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
2461                        target_pid_to_str (tinfo->entry.id),
2462                        tpoint->number, paddress (tpoint->address));
2463
2464           /* Test the condition if present, and collect if true.  */
2465           if (!tpoint->cond
2466               || (condition_true_at_tracepoint
2467                   ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
2468             collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
2469                                         stop_pc, tpoint);
2470
2471           if (stopping_tracepoint
2472               || trace_buffer_is_full
2473               || expr_eval_result != expr_eval_no_error)
2474             {
2475               stop_tracing ();
2476             }
2477           /* If the tracepoint had a 'while-stepping' action, then set
2478              the thread to collect this tracepoint on the following
2479              single-steps.  */
2480           else if (tpoint->step_count > 0)
2481             {
2482               add_while_stepping_state (tinfo,
2483                                         tpoint->number, tpoint->address);
2484             }
2485
2486           ret = 1;
2487         }
2488     }
2489
2490   return ret;
2491 }
2492
2493 /* Create a trace frame for the hit of the given tracepoint in the
2494    given thread.  */
2495
2496 static void
2497 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
2498                             struct tracepoint *tpoint)
2499 {
2500   struct traceframe *tframe;
2501   int acti;
2502
2503   /* Only count it as a hit when we actually collect data.  */
2504   tpoint->hit_count++;
2505
2506   /* If we've exceeded a defined pass count, record the event for
2507      later, and finish the collection for this hit.  This test is only
2508      for nonstepping tracepoints, stepping tracepoints test at the end
2509      of their while-stepping loop.  */
2510   if (tpoint->pass_count > 0
2511       && tpoint->hit_count >= tpoint->pass_count
2512       && tpoint->step_count == 0
2513       && stopping_tracepoint == NULL)
2514     stopping_tracepoint = tpoint;
2515
2516   trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %ld",
2517                tpoint->number, paddress (tpoint->address), tpoint->hit_count);
2518
2519   tframe = add_traceframe (tpoint);
2520
2521   if (tframe)
2522     {
2523       for (acti = 0; acti < tpoint->numactions; ++acti)
2524         {
2525           trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
2526                        tpoint->number, paddress (tpoint->address),
2527                        tpoint->actions_str[acti]);
2528
2529           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
2530                                    tpoint->actions[acti]);
2531         }
2532
2533       finish_traceframe (tframe);
2534     }
2535
2536   if (tframe == NULL && tracing)
2537     trace_buffer_is_full = 1;
2538 }
2539
2540 static void
2541 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
2542                       CORE_ADDR stop_pc,
2543                       struct tracepoint *tpoint, int current_step)
2544 {
2545   struct traceframe *tframe;
2546   int acti;
2547
2548   trace_debug ("Making new step traceframe for "
2549                "tracepoint %d at 0x%s, step %d of %ld, hit %ld",
2550                tpoint->number, paddress (tpoint->address),
2551                current_step, tpoint->step_count,
2552                tpoint->hit_count);
2553
2554   tframe = add_traceframe (tpoint);
2555
2556   if (tframe)
2557     {
2558       for (acti = 0; acti < tpoint->num_step_actions; ++acti)
2559         {
2560           trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
2561                        tpoint->number, paddress (tpoint->address),
2562                        tpoint->step_actions_str[acti]);
2563
2564           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
2565                                    tpoint->step_actions[acti]);
2566         }
2567
2568       finish_traceframe (tframe);
2569     }
2570
2571   if (tframe == NULL && tracing)
2572     trace_buffer_is_full = 1;
2573 }
2574
2575 static struct regcache *
2576 get_context_regcache (struct tracepoint_hit_ctx *ctx)
2577 {
2578   struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
2579   struct regcache *regcache = tctx->regcache;
2580
2581   gdb_assert (regcache != NULL);
2582
2583   return regcache;
2584 }
2585
2586 static void
2587 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
2588                          CORE_ADDR stop_pc,
2589                          struct tracepoint *tpoint,
2590                          struct traceframe *tframe,
2591                          struct tracepoint_action *taction)
2592 {
2593   enum eval_result_type err;
2594
2595   switch (taction->type)
2596     {
2597     case 'M':
2598       {
2599         struct collect_memory_action *maction;
2600
2601         maction = (struct collect_memory_action *) taction;
2602
2603         trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
2604                      pulongest (maction->len),
2605                      paddress (maction->addr), maction->basereg);
2606         /* (should use basereg) */
2607         agent_mem_read (tframe, NULL,
2608                         (CORE_ADDR) maction->addr, maction->len);
2609         break;
2610       }
2611     case 'R':
2612       {
2613         struct collect_registers_action *raction;
2614
2615         unsigned char *regspace;
2616         struct regcache tregcache;
2617         struct regcache *context_regcache;
2618
2619         raction = (struct collect_registers_action *) taction;
2620
2621         trace_debug ("Want to collect registers");
2622
2623         /* Collect all registers for now.  */
2624         regspace = add_traceframe_block (tframe,
2625                                          1 + register_cache_size ());
2626         if (regspace == NULL)
2627           {
2628             trace_debug ("Trace buffer block allocation failed, skipping");
2629             break;
2630           }
2631         /* Identify a register block.  */
2632         *regspace = 'R';
2633
2634         context_regcache = get_context_regcache (ctx);
2635
2636         /* Wrap the regblock in a register cache (in the stack, we
2637            don't want to malloc here).  */
2638         init_register_cache (&tregcache, regspace + 1);
2639
2640         /* Copy the register data to the regblock.  */
2641         regcache_cpy (&tregcache, context_regcache);
2642
2643         /* On some platforms, trap-based tracepoints will have the PC
2644            pointing to the next instruction after the trap, but we
2645            don't want the user or GDB trying to guess whether the
2646            saved PC needs adjusting; so always record the adjusted
2647            stop_pc.  Note that we can't use tpoint->address instead,
2648            since it will be wrong for while-stepping actions.  */
2649         trace_debug ("Storing stop pc (0x%s) in regblock",
2650                      paddress (tpoint->address));
2651
2652         /* This changes the regblock, not the thread's
2653            regcache.  */
2654         regcache_write_pc (&tregcache, stop_pc);
2655       }
2656       break;
2657     case 'X':
2658       {
2659         struct eval_expr_action *eaction;
2660
2661         eaction = (struct eval_expr_action *) taction;
2662
2663         trace_debug ("Want to evaluate expression");
2664
2665         err = eval_agent_expr (ctx, tframe, eaction->expr, NULL);
2666
2667         if (err != expr_eval_no_error)
2668           {
2669             record_tracepoint_error (tpoint, "action expression", err);
2670             return;
2671           }
2672       }
2673       break;
2674     default:
2675       trace_debug ("unknown trace action '%c', ignoring", taction->type);
2676       break;
2677     }
2678 }
2679
2680 static int
2681 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
2682                               struct tracepoint *tpoint)
2683 {
2684   ULONGEST value = 0;
2685   enum eval_result_type err;
2686
2687   err = eval_agent_expr (ctx, NULL, tpoint->cond, &value);
2688
2689   if (err != expr_eval_no_error)
2690     {
2691       record_tracepoint_error (tpoint, "condition", err);
2692       /* The error case must return false.  */
2693       return 0;
2694     }
2695
2696   trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
2697                tpoint->number, paddress (tpoint->address),
2698                pulongest (value));
2699   return (value ? 1 : 0);
2700 }
2701
2702 /* The packet form of an agent expression consists of an 'X', number
2703    of bytes in expression, a comma, and then the bytes.  */
2704
2705 static struct agent_expr *
2706 parse_agent_expr (char **actparm)
2707 {
2708   char *act = *actparm;
2709   ULONGEST xlen;
2710   struct agent_expr *aexpr;
2711
2712   ++act;  /* skip the X */
2713   act = unpack_varlen_hex (act, &xlen);
2714   ++act;  /* skip a comma */
2715   aexpr = xmalloc (sizeof (struct agent_expr));
2716   aexpr->length = xlen;
2717   aexpr->bytes = xmalloc (xlen);
2718   convert_ascii_to_int (act, aexpr->bytes, xlen);
2719   *actparm = act + (xlen * 2);
2720   return aexpr;
2721 }
2722
2723 /* Convert the bytes of an agent expression back into hex digits, so
2724    they can be printed or uploaded.  This allocates the buffer,
2725    callers should free when they are done with it.  */
2726
2727 static char *
2728 unparse_agent_expr (struct agent_expr *aexpr)
2729 {
2730   char *rslt;
2731
2732   rslt = xmalloc (2 * aexpr->length + 1);
2733   convert_int_to_ascii (aexpr->bytes, rslt, aexpr->length);
2734   return rslt;
2735 }
2736
2737 /* The agent expression evaluator, as specified by the GDB docs. It
2738    returns 0 if everything went OK, and a nonzero error code
2739    otherwise.  */
2740
2741 static enum eval_result_type
2742 eval_agent_expr (struct tracepoint_hit_ctx *ctx,
2743                  struct traceframe *tframe,
2744                  struct agent_expr *aexpr,
2745                  ULONGEST *rslt)
2746 {
2747   int pc = 0;
2748 #define STACK_MAX 100
2749   ULONGEST stack[STACK_MAX], top;
2750   int sp = 0;
2751   unsigned char op;
2752   int arg;
2753
2754   /* This union is a convenient way to convert representations.  For
2755      now, assume a standard architecture where the hardware integer
2756      types have 8, 16, 32, 64 bit types.  A more robust solution would
2757      be to import stdint.h from gnulib.  */
2758   union
2759   {
2760     union
2761     {
2762       unsigned char bytes[1];
2763       unsigned char val;
2764     } u8;
2765     union
2766     {
2767       unsigned char bytes[2];
2768       unsigned short val;
2769     } u16;
2770     union
2771     {
2772       unsigned char bytes[4];
2773       unsigned int val;
2774     } u32;
2775     union
2776     {
2777       unsigned char bytes[8];
2778       ULONGEST val;
2779     } u64;
2780   } cnv;
2781
2782   if (aexpr->length == 0)
2783     {
2784       trace_debug ("empty agent expression");
2785       return expr_eval_empty_expression;
2786     }
2787
2788   /* Cache the stack top in its own variable. Much of the time we can
2789      operate on this variable, rather than dinking with the stack. It
2790      needs to be copied to the stack when sp changes.  */
2791   top = 0;
2792
2793   while (1)
2794     {
2795       op = aexpr->bytes[pc++];
2796
2797       trace_debug ("About to interpret byte 0x%x", op);
2798
2799       switch (op)
2800         {
2801         case gdb_agent_op_add:
2802           top += stack[--sp];
2803           break;
2804
2805         case gdb_agent_op_sub:
2806           top = stack[--sp] - top;
2807           break;
2808
2809         case gdb_agent_op_mul:
2810           top *= stack[--sp];
2811           break;
2812
2813         case gdb_agent_op_div_signed:
2814           if (top == 0)
2815             {
2816               trace_debug ("Attempted to divide by zero");
2817               return expr_eval_divide_by_zero;
2818             }
2819           top = ((LONGEST) stack[--sp]) / ((LONGEST) top);
2820           break;
2821
2822         case gdb_agent_op_div_unsigned:
2823           if (top == 0)
2824             {
2825               trace_debug ("Attempted to divide by zero");
2826               return expr_eval_divide_by_zero;
2827             }
2828           top = stack[--sp] / top;
2829           break;
2830
2831         case gdb_agent_op_rem_signed:
2832           if (top == 0)
2833             {
2834               trace_debug ("Attempted to divide by zero");
2835               return expr_eval_divide_by_zero;
2836             }
2837           top = ((LONGEST) stack[--sp]) % ((LONGEST) top);
2838           break;
2839
2840         case gdb_agent_op_rem_unsigned:
2841           if (top == 0)
2842             {
2843               trace_debug ("Attempted to divide by zero");
2844               return expr_eval_divide_by_zero;
2845             }
2846           top = stack[--sp] % top;
2847           break;
2848
2849         case gdb_agent_op_lsh:
2850           top = stack[--sp] << top;
2851           break;
2852
2853         case gdb_agent_op_rsh_signed:
2854           top = ((LONGEST) stack[--sp]) >> top;
2855           break;
2856
2857         case gdb_agent_op_rsh_unsigned:
2858           top = stack[--sp] >> top;
2859           break;
2860
2861         case gdb_agent_op_trace:
2862           agent_mem_read (tframe,
2863                           NULL, (CORE_ADDR) stack[--sp], (ULONGEST) top);
2864           if (--sp >= 0)
2865             top = stack[sp];
2866           break;
2867
2868         case gdb_agent_op_trace_quick:
2869           arg = aexpr->bytes[pc++];
2870           agent_mem_read (tframe, NULL, (CORE_ADDR) top, (ULONGEST) arg);
2871           break;
2872
2873         case gdb_agent_op_log_not:
2874           top = !top;
2875           break;
2876
2877         case gdb_agent_op_bit_and:
2878           top &= stack[--sp];
2879           break;
2880
2881         case gdb_agent_op_bit_or:
2882           top |= stack[--sp];
2883           break;
2884
2885         case gdb_agent_op_bit_xor:
2886           top ^= stack[--sp];
2887           break;
2888
2889         case gdb_agent_op_bit_not:
2890           top = ~top;
2891           break;
2892
2893         case gdb_agent_op_equal:
2894           top = (stack[--sp] == top);
2895           break;
2896
2897         case gdb_agent_op_less_signed:
2898           top = (((LONGEST) stack[--sp]) < ((LONGEST) top));
2899           break;
2900
2901         case gdb_agent_op_less_unsigned:
2902           top = (stack[--sp] < top);
2903           break;
2904
2905         case gdb_agent_op_ext:
2906           arg = aexpr->bytes[pc++];
2907           if (arg < (sizeof (LONGEST) * 8))
2908             {
2909               LONGEST mask = 1 << (arg - 1);
2910               top &= ((LONGEST) 1 << arg) - 1;
2911               top = (top ^ mask) - mask;
2912             }
2913           break;
2914
2915         case gdb_agent_op_ref8:
2916           agent_mem_read (tframe, cnv.u8.bytes, (CORE_ADDR) top, 1);
2917           top = cnv.u8.val;
2918           break;
2919
2920         case gdb_agent_op_ref16:
2921           agent_mem_read (tframe, cnv.u16.bytes, (CORE_ADDR) top, 2);
2922           top = cnv.u16.val;
2923           break;
2924
2925         case gdb_agent_op_ref32:
2926           agent_mem_read (tframe, cnv.u32.bytes, (CORE_ADDR) top, 4);
2927           top = cnv.u32.val;
2928           break;
2929
2930         case gdb_agent_op_ref64:
2931           agent_mem_read (tframe, cnv.u64.bytes, (CORE_ADDR) top, 8);
2932           top = cnv.u64.val;
2933           break;
2934
2935         case gdb_agent_op_if_goto:
2936           if (top)
2937             pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
2938           else
2939             pc += 2;
2940           if (--sp >= 0)
2941             top = stack[sp];
2942           break;
2943
2944         case gdb_agent_op_goto:
2945           pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
2946           break;
2947
2948         case gdb_agent_op_const8:
2949           /* Flush the cached stack top.  */
2950           stack[sp++] = top;
2951           top = aexpr->bytes[pc++];
2952           break;
2953
2954         case gdb_agent_op_const16:
2955           /* Flush the cached stack top.  */
2956           stack[sp++] = top;
2957           top = aexpr->bytes[pc++];
2958           top = (top << 8) + aexpr->bytes[pc++];
2959           break;
2960
2961         case gdb_agent_op_const32:
2962           /* Flush the cached stack top.  */
2963           stack[sp++] = top;
2964           top = aexpr->bytes[pc++];
2965           top = (top << 8) + aexpr->bytes[pc++];
2966           top = (top << 8) + aexpr->bytes[pc++];
2967           top = (top << 8) + aexpr->bytes[pc++];
2968           break;
2969
2970         case gdb_agent_op_const64:
2971           /* Flush the cached stack top.  */
2972           stack[sp++] = top;
2973           top = aexpr->bytes[pc++];
2974           top = (top << 8) + aexpr->bytes[pc++];
2975           top = (top << 8) + aexpr->bytes[pc++];
2976           top = (top << 8) + aexpr->bytes[pc++];
2977           top = (top << 8) + aexpr->bytes[pc++];
2978           top = (top << 8) + aexpr->bytes[pc++];
2979           top = (top << 8) + aexpr->bytes[pc++];
2980           top = (top << 8) + aexpr->bytes[pc++];
2981           break;
2982
2983         case gdb_agent_op_reg:
2984           /* Flush the cached stack top.  */
2985           stack[sp++] = top;
2986           arg = aexpr->bytes[pc++];
2987           arg = (arg << 8) + aexpr->bytes[pc++];
2988           {
2989             int regnum = arg;
2990             struct regcache *regcache;
2991
2992             regcache = get_context_regcache (ctx);
2993
2994             switch (register_size (regnum))
2995               {
2996               case 8:
2997                 collect_register (regcache, regnum, cnv.u64.bytes);
2998                 top = cnv.u64.val;
2999                 break;
3000               case 4:
3001                 collect_register (regcache, regnum, cnv.u32.bytes);
3002                 top = cnv.u32.val;
3003                 break;
3004               case 2:
3005                 collect_register (regcache, regnum, cnv.u16.bytes);
3006                 top = cnv.u16.val;
3007                 break;
3008               case 1:
3009                 collect_register (regcache, regnum, cnv.u8.bytes);
3010                 top = cnv.u8.val;
3011                 break;
3012               default:
3013                 internal_error (__FILE__, __LINE__,
3014                                 "unhandled register size");
3015               }
3016           }
3017           break;
3018
3019         case gdb_agent_op_end:
3020           trace_debug ("At end of expression, sp=%d, stack top cache=0x%s",
3021                        sp, pulongest (top));
3022           if (rslt)
3023             {
3024               if (sp <= 0)
3025                 {
3026                   /* This should be an error */
3027                   trace_debug ("Stack is empty, nothing to return");
3028                   return expr_eval_empty_stack;
3029                 }
3030               *rslt = top;
3031             }
3032           return expr_eval_no_error;
3033
3034         case gdb_agent_op_dup:
3035           stack[sp++] = top;
3036           break;
3037
3038         case gdb_agent_op_pop:
3039           if (--sp >= 0)
3040             top = stack[sp];
3041           break;
3042
3043         case gdb_agent_op_zero_ext:
3044           arg = aexpr->bytes[pc++];
3045           if (arg < (sizeof (LONGEST) * 8))
3046             top &= ((LONGEST) 1 << arg) - 1;
3047           break;
3048
3049         case gdb_agent_op_swap:
3050           /* Interchange top two stack elements, making sure top gets
3051              copied back onto stack.  */
3052           stack[sp] = top;
3053           top = stack[sp - 1];
3054           stack[sp - 1] = stack[sp];
3055           break;
3056
3057         case gdb_agent_op_getv:
3058           /* Flush the cached stack top.  */
3059           stack[sp++] = top;
3060           arg = aexpr->bytes[pc++];
3061           arg = (arg << 8) + aexpr->bytes[pc++];
3062           top = get_trace_state_variable_value (arg);
3063           break;
3064
3065         case gdb_agent_op_setv:
3066           arg = aexpr->bytes[pc++];
3067           arg = (arg << 8) + aexpr->bytes[pc++];
3068           set_trace_state_variable_value (arg, top);
3069           /* Note that we leave the value on the stack, for the
3070              benefit of later/enclosing expressions.  */
3071           break;
3072
3073         case gdb_agent_op_tracev:
3074           arg = aexpr->bytes[pc++];
3075           arg = (arg << 8) + aexpr->bytes[pc++];
3076           agent_tsv_read (tframe, arg);
3077           break;
3078
3079           /* GDB never (currently) generates any of these ops.  */
3080         case gdb_agent_op_float:
3081         case gdb_agent_op_ref_float:
3082         case gdb_agent_op_ref_double:
3083         case gdb_agent_op_ref_long_double:
3084         case gdb_agent_op_l_to_d:
3085         case gdb_agent_op_d_to_l:
3086         case gdb_agent_op_trace16:
3087           trace_debug ("Agent expression op 0x%x valid, but not handled",
3088                        op);
3089           /* If ever GDB generates any of these, we don't have the
3090              option of ignoring.  */
3091           return 1;
3092
3093         default:
3094           trace_debug ("Agent expression op 0x%x not recognized", op);
3095           /* Don't struggle on, things will just get worse.  */
3096           return expr_eval_unrecognized_opcode;
3097         }
3098
3099       /* Check for stack badness.  */
3100       if (sp >= (STACK_MAX - 1))
3101         {
3102           trace_debug ("Expression stack overflow");
3103           return expr_eval_stack_overflow;
3104         }
3105
3106       if (sp < 0)
3107         {
3108           trace_debug ("Expression stack underflow");
3109           return expr_eval_stack_underflow;
3110         }
3111
3112       trace_debug ("Op %s -> sp=%d, top=0x%s",
3113                    gdb_agent_op_names[op], sp, pulongest (top));
3114     }
3115 }
3116
3117 /* Do memory copies for bytecodes.  */
3118 /* Do the recording of memory blocks for actions and bytecodes.  */
3119
3120 static int
3121 agent_mem_read (struct traceframe *tframe,
3122                 unsigned char *to, CORE_ADDR from, ULONGEST len)
3123 {
3124   unsigned char *mspace;
3125   ULONGEST remaining = len;
3126   unsigned short blocklen;
3127
3128   /* If a 'to' buffer is specified, use it.  */
3129   if (to != NULL)
3130     {
3131       read_inferior_memory (from, to, len);
3132       return 0;
3133     }
3134
3135   /* Otherwise, create a new memory block in the trace buffer.  */
3136   while (remaining > 0)
3137     {
3138       size_t sp;
3139
3140       blocklen = (remaining > 65535 ? 65535 : remaining);
3141       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
3142       mspace = add_traceframe_block (tframe, sp);
3143       if (mspace == NULL)
3144         return 1;
3145       /* Identify block as a memory block.  */
3146       *mspace = 'M';
3147       ++mspace;
3148       /* Record address and size.  */
3149       memcpy (mspace, &from, sizeof (from));
3150       mspace += sizeof (from);
3151       memcpy (mspace, &blocklen, sizeof (blocklen));
3152       mspace += sizeof (blocklen);
3153       /* Record the memory block proper.  */
3154       read_inferior_memory (from, mspace, blocklen);
3155       trace_debug ("%d bytes recorded", blocklen);
3156       remaining -= blocklen;
3157       from += blocklen;
3158     }
3159   return 0;
3160 }
3161
3162 /* Record the value of a trace state variable.  */
3163
3164 static int
3165 agent_tsv_read (struct traceframe *tframe, int n)
3166 {
3167   unsigned char *vspace;
3168   LONGEST val;
3169
3170   vspace = add_traceframe_block (tframe,
3171                                  1 + sizeof (n) + sizeof (LONGEST));
3172   if (vspace == NULL)
3173     return 1;
3174   /* Identify block as a variable.  */
3175   *vspace = 'V';
3176   /* Record variable's number and value.  */
3177   memcpy (vspace + 1, &n, sizeof (n));
3178   val = get_trace_state_variable_value (n);
3179   memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
3180   trace_debug ("Variable %d recorded", n);
3181   return 0;
3182 }
3183
3184 static unsigned char *
3185 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
3186                             int tfnum, char type_wanted)
3187 {
3188   unsigned char *dataptr;
3189
3190   if (datasize == 0)
3191     {
3192       trace_debug ("traceframe %d has no data", tfnum);
3193       return NULL;
3194     }
3195
3196   /* Iterate through a traceframe's blocks, looking for a block of the
3197      requested type.  */
3198   for (dataptr = database;
3199        dataptr < database + datasize;
3200        /* nothing */)
3201     {
3202       char blocktype;
3203       unsigned short mlen;
3204
3205       if (dataptr == trace_buffer_wrap)
3206         {
3207           /* Adjust to reflect wrapping part of the frame around to
3208              the beginning.  */
3209           datasize = dataptr - database;
3210           dataptr = database = trace_buffer_lo;
3211         }
3212       blocktype = *dataptr++;
3213
3214       if (type_wanted == blocktype)
3215         return dataptr;
3216
3217       switch (blocktype)
3218         {
3219         case 'R':
3220           /* Skip over the registers block.  */
3221           dataptr += register_cache_size ();
3222           break;
3223         case 'M':
3224           /* Skip over the memory block.  */
3225           dataptr += sizeof (CORE_ADDR);
3226           memcpy (&mlen, dataptr, sizeof (mlen));
3227           dataptr += (sizeof (mlen) + mlen);
3228           break;
3229         case 'S':
3230           /* Skip over the static trace data block.  */
3231           memcpy (&mlen, dataptr, sizeof (mlen));
3232           dataptr += (sizeof (mlen) + mlen);
3233           break;
3234         case 'V':
3235           /* Skip over the TSV block.  */
3236           dataptr += (sizeof (int) + sizeof (LONGEST));
3237           break;
3238         default:
3239           trace_debug ("traceframe %d has unknown block type 0x%x",
3240                        tfnum, blocktype);
3241           return NULL;
3242         }
3243     }
3244
3245   return NULL;
3246 }
3247
3248 static unsigned char *
3249 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
3250 {
3251   unsigned char *regblock;
3252
3253   regblock = traceframe_find_block_type (tframe->data,
3254                                          tframe->data_size,
3255                                          tfnum, 'R');
3256
3257   if (regblock == NULL)
3258     trace_debug ("traceframe %d has no register data", tfnum);
3259
3260   return regblock;
3261 }
3262
3263 /* Get registers from a traceframe.  */
3264
3265 int
3266 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
3267 {
3268   unsigned char *dataptr;
3269   struct tracepoint *tpoint;
3270   struct traceframe *tframe;
3271
3272   tframe = find_traceframe (tfnum);
3273
3274   if (tframe == NULL)
3275     {
3276       trace_debug ("traceframe %d not found", tfnum);
3277       return 1;
3278     }
3279
3280   dataptr = traceframe_find_regblock (tframe, tfnum);
3281   if (dataptr == NULL)
3282     {
3283       /* We don't like making up numbers, but GDB has all manner of
3284          troubles when the target says there are no registers.  */
3285       supply_regblock (regcache, NULL);
3286
3287       /* We can generally guess at a PC, although this will be
3288          misleading for while-stepping frames and multi-location
3289          tracepoints.  */
3290       tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
3291       if (tpoint != NULL)
3292         regcache_write_pc (regcache, tpoint->address);
3293     }
3294   else
3295     supply_regblock (regcache, dataptr);
3296
3297   return 0;
3298 }
3299
3300 static CORE_ADDR
3301 traceframe_get_pc (struct traceframe *tframe)
3302 {
3303   struct regcache regcache;
3304   unsigned char *dataptr;
3305
3306   dataptr = traceframe_find_regblock (tframe, -1);
3307   if (dataptr == NULL)
3308     return 0;
3309
3310   init_register_cache (&regcache, dataptr);
3311   return regcache_read_pc (&regcache);
3312 }
3313
3314 /* Read a requested block of memory from a trace frame.  */
3315
3316 int
3317 traceframe_read_mem (int tfnum, CORE_ADDR addr,
3318                      unsigned char *buf, ULONGEST length,
3319                      ULONGEST *nbytes)
3320 {
3321   struct traceframe *tframe;
3322   unsigned char *database, *dataptr;
3323   unsigned int datasize;
3324   CORE_ADDR maddr;
3325   unsigned short mlen;
3326
3327   trace_debug ("traceframe_read_mem");
3328
3329   tframe = find_traceframe (tfnum);
3330
3331   if (!tframe)
3332     {
3333       trace_debug ("traceframe %d not found", tfnum);
3334       return 1;
3335     }
3336
3337   datasize = tframe->data_size;
3338   database = dataptr = &tframe->data[0];
3339
3340   /* Iterate through a traceframe's blocks, looking for memory.  */
3341   while ((dataptr = traceframe_find_block_type (dataptr,
3342                                                 datasize - (dataptr - database),
3343                                                 tfnum, 'M')) != NULL)
3344     {
3345       memcpy (&maddr, dataptr, sizeof (maddr));
3346       dataptr += sizeof (maddr);
3347       memcpy (&mlen, dataptr, sizeof (mlen));
3348       dataptr += sizeof (mlen);
3349       trace_debug ("traceframe %d has %d bytes at %s",
3350                    tfnum, mlen, paddress (maddr));
3351
3352       /* Check that requested data is in bounds.  */
3353       if (maddr <= addr && (addr + length) <= (maddr + mlen))
3354         {
3355           /* Block includes the requested range, copy it out.  */
3356           memcpy (buf, dataptr + (addr - maddr), length);
3357           *nbytes = length;
3358           return 0;
3359         }
3360
3361       /* Skip over this block.  */
3362       dataptr += mlen;
3363     }
3364
3365   trace_debug ("traceframe %d has no memory data for the desired region",
3366                tfnum);
3367
3368   *nbytes = 0;
3369   return 0;
3370 }
3371
3372 static int
3373 traceframe_read_tsv (int tsvnum, LONGEST *val)
3374 {
3375   int tfnum;
3376   struct traceframe *tframe;
3377   unsigned char *database, *dataptr;
3378   unsigned int datasize;
3379   int vnum;
3380
3381   trace_debug ("traceframe_read_tsv");
3382
3383   tfnum = current_traceframe;
3384
3385   if (tfnum < 0)
3386     {
3387       trace_debug ("no current traceframe");
3388       return 1;
3389     }
3390
3391   tframe = find_traceframe (tfnum);
3392
3393   if (tframe == NULL)
3394     {
3395       trace_debug ("traceframe %d not found", tfnum);
3396       return 1;
3397     }
3398
3399   datasize = tframe->data_size;
3400   database = dataptr = &tframe->data[0];
3401
3402   /* Iterate through a traceframe's blocks, looking for the tsv.  */
3403   while ((dataptr = traceframe_find_block_type (dataptr,
3404                                                 datasize - (dataptr - database),
3405                                                 tfnum, 'V')) != NULL)
3406     {
3407       memcpy (&vnum, dataptr, sizeof (vnum));
3408       dataptr += sizeof (vnum);
3409
3410       trace_debug ("traceframe %d has variable %d", tfnum, vnum);
3411
3412       /* Check that this is the variable we want.  */
3413       if (tsvnum == vnum)
3414         {
3415           memcpy (val, dataptr, sizeof (*val));
3416           return 0;
3417         }
3418
3419       /* Skip over this block.  */
3420       dataptr += sizeof (LONGEST);
3421     }
3422
3423   trace_debug ("traceframe %d has no data for variable %d",
3424                tfnum, tsvnum);
3425   return 1;
3426 }
3427
3428 static LONGEST
3429 tsv_get_timestamp (void)
3430 {
3431    struct timeval tv;
3432
3433    if (gettimeofday (&tv, 0) != 0)
3434      return -1;
3435    else
3436      return (LONGEST) tv.tv_sec * 1000000 + tv.tv_usec;
3437 }
3438
3439 void
3440 initialize_tracepoint (void)
3441 {
3442   /* There currently no way to change the buffer size.  */
3443   const int sizeOfBuffer = 5 * 1024 * 1024;
3444   unsigned char *buf = xmalloc (sizeOfBuffer);
3445   init_trace_buffer (buf, sizeOfBuffer);
3446
3447   /* Wire trace state variable 1 to be the timestamp.  This will be
3448      uploaded to GDB upon connection and become one of its trace state
3449      variables.  (In case you're wondering, if GDB already has a trace
3450      variable numbered 1, it will be renumbered.)  */
3451   create_trace_state_variable (1);
3452   set_trace_state_variable_name (1, "trace_timestamp");
3453   set_trace_state_variable_getter (1, tsv_get_timestamp);
3454 }