gdb/gdbserver/
[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 #include <stddef.h>
25 #if HAVE_MALLOC_H
26 #include <malloc.h>
27 #endif
28 #if HAVE_STDINT_H
29 #include <stdint.h>
30 #endif
31
32 /* This file is built for both both GDBserver, and the in-process
33    agent (IPA), a shared library that includes a tracing agent that is
34    loaded by the inferior to support fast tracepoints.  Fast
35    tracepoints (or more accurately, jump based tracepoints) are
36    implemented by patching the tracepoint location with a jump into a
37    small trampoline function whose job is to save the register state,
38    call the in-process tracing agent, and then execute the original
39    instruction that was under the tracepoint jump (possibly adjusted,
40    if PC-relative, or some such).
41
42    The current synchronization design is pull based.  That means,
43    GDBserver does most of the work, by peeking/poking at the inferior
44    agent's memory directly for downloading tracepoint and associated
45    objects, and for uploading trace frames.  Whenever the IPA needs
46    something from GDBserver (trace buffer is full, tracing stopped for
47    some reason, etc.) the IPA calls a corresponding hook function
48    where GDBserver has placed a breakpoint.
49
50    Each of the agents has its own trace buffer.  When browsing the
51    trace frames built from slow and fast tracepoints from GDB (tfind
52    mode), there's no guarantee the user is seeing the trace frames in
53    strict chronological creation order, although, GDBserver tries to
54    keep the order relatively reasonable, by syncing the trace buffers
55    at appropriate times.
56
57 */
58
59 static void trace_vdebug (const char *, ...) ATTR_FORMAT (printf, 1, 2);
60
61 static void
62 trace_vdebug (const char *fmt, ...)
63 {
64   char buf[1024];
65   va_list ap;
66
67   va_start (ap, fmt);
68   vsprintf (buf, fmt, ap);
69   fprintf (stderr, "gdbserver/tracepoint: %s\n", buf);
70   va_end (ap);
71 }
72
73 #define trace_debug_1(level, fmt, args...)      \
74   do {                                          \
75     if (level <= debug_threads)                 \
76       trace_vdebug ((fmt), ##args);             \
77   } while (0)
78
79 #define trace_debug(FMT, args...)               \
80   trace_debug_1 (1, FMT, ##args)
81
82 #if defined(__GNUC__)
83 #  define ATTR_USED __attribute__((used))
84 #  define ATTR_NOINLINE __attribute__((noinline))
85 #  define ATTR_CONSTRUCTOR __attribute__ ((constructor))
86 #else
87 #  define ATTR_USED
88 #  define ATTR_NOINLINE
89 #  define ATTR_CONSTRUCTOR
90 #endif
91
92 /* Make sure the functions the IPA needs to export (symbols GDBserver
93    needs to query GDB about) are exported.  */
94
95 #ifdef IN_PROCESS_AGENT
96 # if defined _WIN32 || defined __CYGWIN__
97 #   define IP_AGENT_EXPORT __declspec(dllexport) ATTR_USED
98 # else
99 #   if __GNUC__ >= 4
100 #     define IP_AGENT_EXPORT \
101   __attribute__ ((visibility("default"))) ATTR_USED
102 #   else
103 #     define IP_AGENT_EXPORT ATTR_USED
104 #   endif
105 # endif
106 #else
107 #  define IP_AGENT_EXPORT
108 #endif
109
110 /* Prefix exported symbols, for good citizenship.  All the symbols
111    that need exporting are defined in this module.  */
112 #ifdef IN_PROCESS_AGENT
113 # define gdb_tp_heap_buffer gdb_agent_gdb_tp_heap_buffer
114 # define gdb_jump_pad_buffer gdb_agent_gdb_jump_pad_buffer
115 # define gdb_jump_pad_buffer_end gdb_agent_gdb_jump_pad_buffer_end
116 # define collecting gdb_agent_collecting
117 # define gdb_collect gdb_agent_gdb_collect
118 # define stop_tracing gdb_agent_stop_tracing
119 # define flush_trace_buffer gdb_agent_flush_trace_buffer
120 # define about_to_request_buffer_space gdb_agent_about_to_request_buffer_space
121 # define trace_buffer_is_full gdb_agent_trace_buffer_is_full
122 # define stopping_tracepoint gdb_agent_stopping_tracepoint
123 # define expr_eval_result gdb_agent_expr_eval_result
124 # define error_tracepoint gdb_agent_error_tracepoint
125 # define tracepoints gdb_agent_tracepoints
126 # define tracing gdb_agent_tracing
127 # define trace_buffer_ctrl gdb_agent_trace_buffer_ctrl
128 # define trace_buffer_ctrl_curr gdb_agent_trace_buffer_ctrl_curr
129 # define trace_buffer_lo gdb_agent_trace_buffer_lo
130 # define trace_buffer_hi gdb_agent_trace_buffer_hi
131 # define traceframe_read_count gdb_agent_traceframe_read_count
132 # define traceframe_write_count gdb_agent_traceframe_write_count
133 # define traceframes_created gdb_agent_traceframes_created
134 # define trace_state_variables gdb_agent_trace_state_variables
135 #endif
136
137 #ifndef IN_PROCESS_AGENT
138
139 /* Addresses of in-process agent's symbols GDBserver cares about.  */
140
141 struct ipa_sym_addresses
142 {
143   CORE_ADDR addr_gdb_tp_heap_buffer;
144   CORE_ADDR addr_gdb_jump_pad_buffer;
145   CORE_ADDR addr_gdb_jump_pad_buffer_end;
146   CORE_ADDR addr_collecting;
147   CORE_ADDR addr_gdb_collect;
148   CORE_ADDR addr_stop_tracing;
149   CORE_ADDR addr_flush_trace_buffer;
150   CORE_ADDR addr_about_to_request_buffer_space;
151   CORE_ADDR addr_trace_buffer_is_full;
152   CORE_ADDR addr_stopping_tracepoint;
153   CORE_ADDR addr_expr_eval_result;
154   CORE_ADDR addr_error_tracepoint;
155   CORE_ADDR addr_tracepoints;
156   CORE_ADDR addr_tracing;
157   CORE_ADDR addr_trace_buffer_ctrl;
158   CORE_ADDR addr_trace_buffer_ctrl_curr;
159   CORE_ADDR addr_trace_buffer_lo;
160   CORE_ADDR addr_trace_buffer_hi;
161   CORE_ADDR addr_traceframe_read_count;
162   CORE_ADDR addr_traceframe_write_count;
163   CORE_ADDR addr_traceframes_created;
164   CORE_ADDR addr_trace_state_variables;
165 };
166
167 #define STRINGIZE_1(STR) #STR
168 #define STRINGIZE(STR) STRINGIZE_1(STR)
169 #define IPA_SYM(SYM)                            \
170   {                                                     \
171     STRINGIZE (gdb_agent_ ## SYM),                      \
172     offsetof (struct ipa_sym_addresses, addr_ ## SYM)   \
173   }
174
175 static struct
176 {
177   const char *name;
178   int offset;
179   int required;
180 } symbol_list[] = {
181   IPA_SYM(gdb_tp_heap_buffer),
182   IPA_SYM(gdb_jump_pad_buffer),
183   IPA_SYM(gdb_jump_pad_buffer_end),
184   IPA_SYM(collecting),
185   IPA_SYM(gdb_collect),
186   IPA_SYM(stop_tracing),
187   IPA_SYM(flush_trace_buffer),
188   IPA_SYM(about_to_request_buffer_space),
189   IPA_SYM(trace_buffer_is_full),
190   IPA_SYM(stopping_tracepoint),
191   IPA_SYM(expr_eval_result),
192   IPA_SYM(error_tracepoint),
193   IPA_SYM(tracepoints),
194   IPA_SYM(tracing),
195   IPA_SYM(trace_buffer_ctrl),
196   IPA_SYM(trace_buffer_ctrl_curr),
197   IPA_SYM(trace_buffer_lo),
198   IPA_SYM(trace_buffer_hi),
199   IPA_SYM(traceframe_read_count),
200   IPA_SYM(traceframe_write_count),
201   IPA_SYM(traceframes_created),
202   IPA_SYM(trace_state_variables),
203 };
204
205 struct ipa_sym_addresses ipa_sym_addrs;
206
207 int all_tracepoint_symbols_looked_up;
208
209 int
210 in_process_agent_loaded (void)
211 {
212   return all_tracepoint_symbols_looked_up;
213 }
214
215 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
216
217 static void
218 write_e_ipa_not_loaded (char *buffer)
219 {
220   sprintf (buffer,
221            "E.In-process agent library not loaded in process.  "
222            "Dynamic tracepoints unavailable.");
223 }
224
225 static int
226 maybe_write_ipa_not_loaded (char *buffer)
227 {
228   if (!in_process_agent_loaded ())
229     {
230       write_e_ipa_not_loaded (buffer);
231       return 1;
232     }
233   return 0;
234 }
235
236 /* Cache all future symbols that the tracepoints module might request.
237    We can not request symbols at arbitrary states in the remote
238    protocol, only when the client tells us that new symbols are
239    available.  So when we load the in-process library, make sure to
240    check the entire list.  */
241
242 void
243 tracepoint_look_up_symbols (void)
244 {
245   int all_ok;
246   int i;
247
248   if (all_tracepoint_symbols_looked_up)
249     return;
250
251   all_ok = 1;
252   for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
253     {
254       CORE_ADDR *addrp =
255         (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
256
257       if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
258         {
259           if (debug_threads)
260             fprintf (stderr, "symbol `%s' not found\n", symbol_list[i].name);
261           all_ok = 0;
262         }
263     }
264
265   all_tracepoint_symbols_looked_up = all_ok;
266 }
267
268 #endif
269
270 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
271    of the "stop_tracing" function.  When this breakpoint is hit,
272    tracing stopped in the IPA for some reason.  E.g., due to
273    tracepoint reaching the pass count, hitting conditional expression
274    evaluation error, etc.
275
276    The IPA's trace buffer is never in circular tracing mode: instead,
277    GDBserver's is, and whenever the in-process buffer fills, it calls
278    "flush_trace_buffer", which triggers an internal breakpoint.
279    GDBserver reacts to this breakpoint by pulling the meanwhile
280    collected data.  Old frames discarding is always handled on the
281    GDBserver side.  */
282
283 #ifdef IN_PROCESS_AGENT
284 int debug_threads = 0;
285
286 int
287 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
288 {
289   memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
290   return 0;
291 }
292
293 /* Call this in the functions where GDBserver places a breakpoint, so
294    that the compiler doesn't try to be clever and skip calling the
295    function at all.  This is necessary, even if we tell the compiler
296    to not inline said functions.  */
297
298 #if defined(__GNUC__)
299 #  define UNKNOWN_SIDE_EFFECTS() asm ("")
300 #else
301 #  define UNKNOWN_SIDE_EFFECTS() do {} while (0)
302 #endif
303
304 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
305 stop_tracing (void)
306 {
307   /* GDBserver places breakpoint here.  */
308   UNKNOWN_SIDE_EFFECTS();
309 }
310
311 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
312 flush_trace_buffer (void)
313 {
314   /* GDBserver places breakpoint here.  */
315   UNKNOWN_SIDE_EFFECTS();
316 }
317
318 #endif
319
320 #ifndef IN_PROCESS_AGENT
321 static int
322 tracepoint_handler (CORE_ADDR address)
323 {
324   trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
325                paddress (address));
326   return 0;
327 }
328
329 /* Breakpoint at "stop_tracing" in the inferior lib.  */
330 struct breakpoint *stop_tracing_bkpt;
331 static int stop_tracing_handler (CORE_ADDR);
332
333 /* Breakpoint at "flush_trace_buffer" in the inferior lib.  */
334 struct breakpoint *flush_trace_buffer_bkpt;
335 static int flush_trace_buffer_handler (CORE_ADDR);
336
337 static void download_tracepoints (void);
338 static void download_trace_state_variables (void);
339 static void upload_fast_traceframes (void);
340
341 static int
342 read_inferior_integer (CORE_ADDR symaddr, int *val)
343 {
344   return read_inferior_memory (symaddr, (unsigned char *) val,
345                                sizeof (*val));
346 }
347
348 static int
349 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
350 {
351   return read_inferior_memory (symaddr, (unsigned char *) val,
352                                sizeof (*val));
353 }
354
355 static int
356 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
357 {
358   void *pval = (void *) (uintptr_t) val;
359   int ret;
360
361   ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
362   *val = (uintptr_t) pval;
363   return ret;
364 }
365
366 static int
367 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
368 {
369   void *pval = (void *) (uintptr_t) val;
370   return write_inferior_memory (symaddr,
371                                 (unsigned char *) &pval, sizeof (pval));
372 }
373
374 static int
375 write_inferior_integer (CORE_ADDR symaddr, int val)
376 {
377   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
378 }
379
380 static int
381 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
382 {
383   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
384 }
385
386 #endif
387
388 /* This enum must exactly match what is documented in
389    gdb/doc/agentexpr.texi, including all the numerical values.  */
390
391 enum gdb_agent_op
392   {
393     gdb_agent_op_float = 0x01,
394     gdb_agent_op_add = 0x02,
395     gdb_agent_op_sub = 0x03,
396     gdb_agent_op_mul = 0x04,
397     gdb_agent_op_div_signed = 0x05,
398     gdb_agent_op_div_unsigned = 0x06,
399     gdb_agent_op_rem_signed = 0x07,
400     gdb_agent_op_rem_unsigned = 0x08,
401     gdb_agent_op_lsh = 0x09,
402     gdb_agent_op_rsh_signed = 0x0a,
403     gdb_agent_op_rsh_unsigned = 0x0b,
404     gdb_agent_op_trace = 0x0c,
405     gdb_agent_op_trace_quick = 0x0d,
406     gdb_agent_op_log_not = 0x0e,
407     gdb_agent_op_bit_and = 0x0f,
408     gdb_agent_op_bit_or = 0x10,
409     gdb_agent_op_bit_xor = 0x11,
410     gdb_agent_op_bit_not = 0x12,
411     gdb_agent_op_equal = 0x13,
412     gdb_agent_op_less_signed = 0x14,
413     gdb_agent_op_less_unsigned = 0x15,
414     gdb_agent_op_ext = 0x16,
415     gdb_agent_op_ref8 = 0x17,
416     gdb_agent_op_ref16 = 0x18,
417     gdb_agent_op_ref32 = 0x19,
418     gdb_agent_op_ref64 = 0x1a,
419     gdb_agent_op_ref_float = 0x1b,
420     gdb_agent_op_ref_double = 0x1c,
421     gdb_agent_op_ref_long_double = 0x1d,
422     gdb_agent_op_l_to_d = 0x1e,
423     gdb_agent_op_d_to_l = 0x1f,
424     gdb_agent_op_if_goto = 0x20,
425     gdb_agent_op_goto = 0x21,
426     gdb_agent_op_const8 = 0x22,
427     gdb_agent_op_const16 = 0x23,
428     gdb_agent_op_const32 = 0x24,
429     gdb_agent_op_const64 = 0x25,
430     gdb_agent_op_reg = 0x26,
431     gdb_agent_op_end = 0x27,
432     gdb_agent_op_dup = 0x28,
433     gdb_agent_op_pop = 0x29,
434     gdb_agent_op_zero_ext = 0x2a,
435     gdb_agent_op_swap = 0x2b,
436     gdb_agent_op_getv = 0x2c,
437     gdb_agent_op_setv = 0x2d,
438     gdb_agent_op_tracev = 0x2e,
439     gdb_agent_op_trace16 = 0x30,
440     gdb_agent_op_last
441   };
442
443 static const char *gdb_agent_op_names [gdb_agent_op_last] =
444   {
445     "?undef?",
446     "float",
447     "add",
448     "sub",
449     "mul",
450     "div_signed",
451     "div_unsigned",
452     "rem_signed",
453     "rem_unsigned",
454     "lsh",
455     "rsh_signed",
456     "rsh_unsigned",
457     "trace",
458     "trace_quick",
459     "log_not",
460     "bit_and",
461     "bit_or",
462     "bit_xor",
463     "bit_not",
464     "equal",
465     "less_signed",
466     "less_unsigned",
467     "ext",
468     "ref8",
469     "ref16",
470     "ref32",
471     "ref64",
472     "ref_float",
473     "ref_double",
474     "ref_long_double",
475     "l_to_d",
476     "d_to_l",
477     "if_goto",
478     "goto",
479     "const8",
480     "const16",
481     "const32",
482     "const64",
483     "reg",
484     "end",
485     "dup",
486     "pop",
487     "zero_ext",
488     "swap",
489     "getv",
490     "setv",
491     "tracev",
492     "?undef?",
493     "trace16",
494   };
495
496 struct agent_expr
497 {
498   int length;
499
500   unsigned char *bytes;
501 };
502
503 /* Base action.  Concrete actions inherit this.  */
504
505 struct tracepoint_action
506 {
507   char type;
508 };
509
510 /* An 'M' (collect memory) action.  */
511 struct collect_memory_action
512 {
513   struct tracepoint_action base;
514
515   ULONGEST addr;
516   ULONGEST len;
517   int basereg;
518 };
519
520 /* An 'R' (collect registers) action.  */
521
522 struct collect_registers_action
523 {
524   struct tracepoint_action base;
525 };
526
527 /* An 'X' (evaluate expression) action.  */
528
529 struct eval_expr_action
530 {
531   struct tracepoint_action base;
532
533   struct agent_expr *expr;
534 };
535
536 /* This structure describes a piece of the source-level definition of
537    the tracepoint.  The contents are not interpreted by the target,
538    but preserved verbatim for uploading upon reconnection.  */
539
540 struct source_string
541 {
542   /* The type of string, such as "cond" for a conditional.  */
543   char *type;
544
545   /* The source-level string itself.  For the sake of target
546      debugging, we store it in plaintext, even though it is always
547      transmitted in hex.  */
548   char *str;
549
550   /* Link to the next one in the list.  We link them in the order
551      received, in case some make up an ordered list of commands or
552      some such.  */
553   struct source_string *next;
554 };
555
556 enum tracepoint_type
557 {
558   /* Trap based tracepoint.  */
559   trap_tracepoint,
560
561   /* A fast tracepoint implemented with a jump instead of a trap.  */
562   fast_tracepoint,
563 };
564
565 struct tracepoint_hit_ctx;
566
567 /* The definition of a tracepoint.  */
568
569 /* Tracepoints may have multiple locations, each at a different
570    address.  This can occur with optimizations, template
571    instantiation, etc.  Since the locations may be in different
572    scopes, the conditions and actions may be different for each
573    location.  Our target version of tracepoints is more like GDB's
574    notion of "breakpoint locations", but we have almost nothing that
575    is not per-location, so we bother having two kinds of objects.  The
576    key consequence is that numbers are not unique, and that it takes
577    both number and address to identify a tracepoint uniquely.  */
578
579 struct tracepoint
580 {
581   /* The number of the tracepoint, as specified by GDB.  Several
582      tracepoint objects here may share a number.  */
583   int number;
584
585   /* Address at which the tracepoint is supposed to trigger.  Several
586      tracepoints may share an address.  */
587   CORE_ADDR address;
588
589   /* Tracepoint type.  */
590   enum tracepoint_type type;
591
592   /* True if the tracepoint is currently enabled.  */
593   int enabled;
594
595   /* The number of single steps that will be performed after each
596      tracepoint hit.  */
597   long step_count;
598
599   /* The number of times the tracepoint may be hit before it will
600      terminate the entire tracing run.  */
601   long pass_count;
602
603   /* Pointer to the agent expression that is the tracepoint's
604      conditional, or NULL if the tracepoint is unconditional.  */
605   struct agent_expr *cond;
606
607   /* The list of actions to take when the tracepoint triggers.  */
608   int numactions;
609   struct tracepoint_action **actions;
610
611   /* Count of the times we've hit this tracepoint during the run.
612      Note that while-stepping steps are not counted as "hits".  */
613   long hit_count;
614
615   /* Link to the next tracepoint in the list.  */
616   struct tracepoint *next;
617
618 #ifndef IN_PROCESS_AGENT
619   /* The list of actions to take when the tracepoint triggers, in
620      string/packet form.  */
621   char **actions_str;
622
623   /* The collection of strings that describe the tracepoint as it was
624      entered into GDB.  These are not used by the target, but are
625      reported back to GDB upon reconnection.  */
626   struct source_string *source_strings;
627
628   /* The number of bytes displaced by fast tracepoints. It may subsume
629      multiple instructions, for multi-byte fast tracepoints.  This
630      field is only valid for fast tracepoints.  */
631   int orig_size;
632
633   /* Only for fast tracepoints.  */
634   CORE_ADDR obj_addr_on_target;
635
636   /* Address range where the original instruction under a fast
637      tracepoint was relocated to.  (_end is actually one byte past
638      the end).  */
639   CORE_ADDR adjusted_insn_addr;
640   CORE_ADDR adjusted_insn_addr_end;
641
642   /* The address range of the piece of the jump pad buffer that was
643      assigned to this fast tracepoint.  (_end is actually one byte
644      past the end).*/
645   CORE_ADDR jump_pad;
646   CORE_ADDR jump_pad_end;
647
648   /* The list of actions to take while in a stepping loop.  These
649      fields are only valid for patch-based tracepoints.  */
650   int num_step_actions;
651   struct tracepoint_action **step_actions;
652   /* Same, but in string/packet form.  */
653   char **step_actions_str;
654
655   /* Handle returned by the breakpoint or tracepoint module when we
656      inserted the trap or jump.  NULL if we haven't inserted it
657      yet.  */
658   void *handle;
659 #endif
660
661 };
662
663 #ifndef IN_PROCESS_AGENT
664
665 /* Given `while-stepping', a thread may be collecting data for more
666    than one tracepoint simultaneously.  On the other hand, the same
667    tracepoint with a while-stepping action may be hit by more than one
668    thread simultaneously (but not quite, each thread could be handling
669    a different step).  Each thread holds a list of these objects,
670    representing the current step of each while-stepping action being
671    collected.  */
672
673 struct wstep_state
674 {
675   struct wstep_state *next;
676
677   /* The tracepoint number.  */
678   int tp_number;
679   /* The tracepoint's address.  */
680   CORE_ADDR tp_address;
681
682   /* The number of the current step in this 'while-stepping'
683      action.  */
684   long current_step;
685 };
686
687 #endif
688
689 /* The linked list of all tracepoints.  Marked explicitly as used as
690    the in-process library doesn't use it for the fast tracepoints
691    support.  */
692 IP_AGENT_EXPORT struct tracepoint *tracepoints ATTR_USED;
693
694 #ifndef IN_PROCESS_AGENT
695
696 /* Pointer to the last tracepoint in the list, new tracepoints are
697    linked in at the end.  */
698
699 static struct tracepoint *last_tracepoint;
700 #endif
701
702 /* The first tracepoint to exceed its pass count.  */
703
704 IP_AGENT_EXPORT struct tracepoint *stopping_tracepoint;
705
706 /* True if the trace buffer is full or otherwise no longer usable.  */
707
708 IP_AGENT_EXPORT int trace_buffer_is_full;
709
710 /* Enumeration of the different kinds of things that can happen during
711    agent expression evaluation.  */
712
713 enum eval_result_type
714   {
715     expr_eval_no_error,
716     expr_eval_empty_expression,
717     expr_eval_empty_stack,
718     expr_eval_stack_overflow,
719     expr_eval_stack_underflow,
720     expr_eval_unhandled_opcode,
721     expr_eval_unrecognized_opcode,
722     expr_eval_divide_by_zero,
723     expr_eval_invalid_goto
724   };
725
726 static enum eval_result_type expr_eval_result = expr_eval_no_error;
727
728 #ifndef IN_PROCESS_AGENT
729
730 static const char *eval_result_names[] =
731   {
732     "terror:in the attic",  /* this should never be reported */
733     "terror:empty expression",
734     "terror:empty stack",
735     "terror:stack overflow",
736     "terror:stack underflow",
737     "terror:unhandled opcode",
738     "terror:unrecognized opcode",
739     "terror:divide by zero"
740   };
741
742 #endif
743
744 /* The tracepoint in which the error occurred.  */
745
746 static struct tracepoint *error_tracepoint;
747
748 struct trace_state_variable
749 {
750   /* This is the name of the variable as used in GDB.  The target
751      doesn't use the name, but needs to have it for saving and
752      reconnection purposes.  */
753   char *name;
754
755   /* This number identifies the variable uniquely.  Numbers may be
756      assigned either by the target (in the case of builtin variables),
757      or by GDB, and are presumed unique during the course of a trace
758      experiment.  */
759   int number;
760
761   /* The variable's initial value, a 64-bit signed integer always.  */
762   LONGEST initial_value;
763
764   /* The variable's value, a 64-bit signed integer always.  */
765   LONGEST value;
766
767   /* Pointer to a getter function, used to supply computed values.  */
768   LONGEST (*getter) (void);
769
770   /* Link to the next variable.  */
771   struct trace_state_variable *next;
772 };
773
774 /* Linked list of all trace state variables.  */
775
776 #ifdef IN_PROCESS_AGENT
777 struct trace_state_variable *alloced_trace_state_variables;
778 #endif
779
780 IP_AGENT_EXPORT struct trace_state_variable *trace_state_variables;
781
782 /* The results of tracing go into a fixed-size space known as the
783    "trace buffer".  Because usage follows a limited number of
784    patterns, we manage it ourselves rather than with malloc.  Basic
785    rules are that we create only one trace frame at a time, each is
786    variable in size, they are never moved once created, and we only
787    discard if we are doing a circular buffer, and then only the oldest
788    ones.  Each trace frame includes its own size, so we don't need to
789    link them together, and the trace frame number is relative to the
790    first one, so we don't need to record numbers.  A trace frame also
791    records the number of the tracepoint that created it.  The data
792    itself is a series of blocks, each introduced by a single character
793    and with a defined format.  Each type of block has enough
794    type/length info to allow scanners to jump quickly from one block
795    to the next without reading each byte in the block.  */
796
797 /* Trace buffer management would be simple - advance a free pointer
798    from beginning to end, then stop - were it not for the circular
799    buffer option, which is a useful way to prevent a trace run from
800    stopping prematurely because the buffer filled up.  In the circular
801    case, the location of the first trace frame (trace_buffer_start)
802    moves as old trace frames are discarded.  Also, since we grow trace
803    frames incrementally as actions are performed, we wrap around to
804    the beginning of the trace buffer.  This is per-block, so each
805    block within a trace frame remains contiguous.  Things get messy
806    when the wrapped-around trace frame is the one being discarded; the
807    free space ends up in two parts at opposite ends of the buffer.  */
808
809 #ifndef ATTR_PACKED
810 #  if defined(__GNUC__)
811 #    define ATTR_PACKED __attribute__ ((packed))
812 #  else
813 #    define ATTR_PACKED /* nothing */
814 #  endif
815 #endif
816
817 /* The data collected at a tracepoint hit.  This object should be as
818    small as possible, since there may be a great many of them.  We do
819    not need to keep a frame number, because they are all sequential
820    and there are no deletions; so the Nth frame in the buffer is
821    always frame number N.  */
822
823 struct traceframe
824 {
825   /* Number of the tracepoint that collected this traceframe.  A value
826      of 0 indicates the current end of the trace buffer.  We make this
827      a 16-bit field because it's never going to happen that GDB's
828      numbering of tracepoints reaches 32,000.  */
829   int tpnum : 16;
830
831   /* The size of the data in this trace frame.  We limit this to 32
832      bits, even on a 64-bit target, because it's just implausible that
833      one is validly going to collect 4 gigabytes of data at a single
834      tracepoint hit.  */
835   unsigned int data_size : 32;
836
837   /* The base of the trace data, which is contiguous from this point.  */
838   unsigned char data[0];
839
840 } ATTR_PACKED;
841
842 /* The traceframe to be used as the source of data to send back to
843    GDB.  A value of -1 means to get data from the live program.  */
844
845 int current_traceframe = -1;
846
847 /* This flag is true if the trace buffer is circular, meaning that
848    when it fills, the oldest trace frames are discarded in order to
849    make room.  */
850
851 #ifndef IN_PROCESS_AGENT
852 static int circular_trace_buffer;
853 #endif
854
855 /* Pointer to the block of memory that traceframes all go into.  */
856
857 static unsigned char *trace_buffer_lo;
858
859 /* Pointer to the end of the trace buffer, more precisely to the byte
860    after the end of the buffer.  */
861
862 static unsigned char *trace_buffer_hi;
863
864 /* Control structure holding the read/write/etc. pointers into the
865    trace buffer.  We need more than one of these to implement a
866    transaction-like mechanism to garantees that both GDBserver and the
867    in-process agent can try to change the trace buffer
868    simultaneously.  */
869
870 struct trace_buffer_control
871 {
872   /* Pointer to the first trace frame in the buffer.  In the
873      non-circular case, this is equal to trace_buffer_lo, otherwise it
874      moves around in the buffer.  */
875   unsigned char *start;
876
877   /* Pointer to the free part of the trace buffer.  Note that we clear
878      several bytes at and after this pointer, so that traceframe
879      scans/searches terminate properly.  */
880   unsigned char *free;
881
882   /* Pointer to the byte after the end of the free part.  Note that
883      this may be smaller than trace_buffer_free in the circular case,
884      and means that the free part is in two pieces.  Initially it is
885      equal to trace_buffer_hi, then is generally equivalent to
886      trace_buffer_start.  */
887   unsigned char *end_free;
888
889   /* Pointer to the wraparound.  If not equal to trace_buffer_hi, then
890      this is the point at which the trace data breaks, and resumes at
891      trace_buffer_lo.  */
892   unsigned char *wrap;
893 };
894
895 /* Same as above, to be used by GDBserver when updating the in-process
896    agent.  */
897 struct ipa_trace_buffer_control
898 {
899   uintptr_t start;
900   uintptr_t free;
901   uintptr_t end_free;
902   uintptr_t wrap;
903 };
904
905
906 /* We have possibly both GDBserver and an inferior thread accessing
907    the same IPA trace buffer memory.  The IPA is the producer (tries
908    to put new frames in the buffer), while GDBserver occasionally
909    consumes them, that is, flushes the IPA's buffer into its own
910    buffer.  Both sides need to update the trace buffer control
911    pointers (current head, tail, etc.).  We can't use a global lock to
912    synchronize the accesses, as otherwise we could deadlock GDBserver
913    (if the thread holding the lock stops for a signal, say).  So
914    instead of that, we use a transaction scheme where GDBserver writes
915    always prevail over the IPAs writes, and, we have the IPA detect
916    the commit failure/overwrite, and retry the whole attempt.  This is
917    mainly implemented by having a global token object that represents
918    who wrote last to the buffer control structure.  We need to freeze
919    any inferior writing to the buffer while GDBserver touches memory,
920    so that the inferior can correctly detect that GDBserver had been
921    there, otherwise, it could mistakingly think its commit was
922    successful; that's implemented by simply having GDBserver set a
923    breakpoint the inferior hits if it is the critical region.
924
925    There are three cycling trace buffer control structure copies
926    (buffer head, tail, etc.), with the token object including an index
927    indicating which is current live copy.  The IPA tentatively builds
928    an updated copy in a non-current control structure, while GDBserver
929    always clobbers the current version directly.  The IPA then tries
930    to atomically "commit" its version; if GDBserver clobbered the
931    structure meanwhile, that will fail, and the IPA restarts the
932    allocation process.
933
934    Listing the step in further detail, we have:
935
936   In-process agent (producer):
937
938   - passes by `about_to_request_buffer_space' breakpoint/lock
939
940   - reads current token, extracts current trace buffer control index,
941     and starts tentatively updating the rightmost one (0->1, 1->2,
942     2->0).  Note that only one inferior thread is executing this code
943     at any given time, due to an outer lock in the jump pads.
944
945   - updates counters, and tries to commit the token.
946
947   - passes by second `about_to_request_buffer_space' breakpoint/lock,
948     leaving the sync region.
949
950   - checks if the update was effective.
951
952   - if trace buffer was found full, hits flush_trace_buffer
953     breakpoint, and restarts later afterwards.
954
955   GDBserver (consumer):
956
957   - sets `about_to_request_buffer_space' breakpoint/lock.
958
959   - updates the token unconditionally, using the current buffer
960     control index, since it knows that the IP agent always writes to
961     the rightmost, and due to the breakpoint, at most one IP thread
962     can try to update the trace buffer concurrently to GDBserver, so
963     there will be no danger of trace buffer control index wrap making
964     the IPA write to the same index as GDBserver.
965
966   - flushes the IP agent's trace buffer completely, and updates the
967     current trace buffer control structure.  GDBserver *always* wins.
968
969   - removes the `about_to_request_buffer_space' breakpoint.
970
971 The token is stored in the `trace_buffer_ctrl_curr' variable.
972 Internally, it's bits are defined as:
973
974  |-------------+-----+-------------+--------+-------------+--------------|
975  | Bit offsets |  31 |   30 - 20   |   19   |    18-8     |     7-0      |
976  |-------------+-----+-------------+--------+-------------+--------------|
977  | What        | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
978  |-------------+-----+-------------+--------+-------------+--------------|
979
980  GSB  - GDBserver Stamp Bit
981  PC   - Previous Counter
982  CC   - Current Counter
983  TBCI - Trace Buffer Control Index
984
985
986 An IPA update of `trace_buffer_ctrl_curr' does:
987
988     - read CC from the current token, save as PC.
989     - updates pointers
990     - atomically tries to write PC+1,CC
991
992 A GDBserver update of `trace_buffer_ctrl_curr' does:
993
994     - reads PC and CC from the current token.
995     - updates pointers
996     - writes GSB,PC,CC
997 */
998
999 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1000    for the counters described below.  The cleared bits are used to
1001    hold the index of the items of the `trace_buffer_ctrl' array that
1002    is "current".  */
1003 #define GDBSERVER_FLUSH_COUNT_MASK        0xfffffff0
1004
1005 /* `trace_buffer_ctrl_curr' contains two counters.  The `previous'
1006    counter, and the `current' counter.  */
1007
1008 #define GDBSERVER_FLUSH_COUNT_MASK_PREV   0x7ff00000
1009 #define GDBSERVER_FLUSH_COUNT_MASK_CURR   0x0007ff00
1010
1011 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1012    always stamps this bit as set.  */
1013 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1014
1015 #ifdef IN_PROCESS_AGENT
1016 IP_AGENT_EXPORT struct trace_buffer_control trace_buffer_ctrl[3];
1017 IP_AGENT_EXPORT unsigned int trace_buffer_ctrl_curr;
1018
1019 # define TRACE_BUFFER_CTRL_CURR \
1020   (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1021
1022 #else
1023
1024 /* The GDBserver side agent only needs one instance of this object, as
1025    it doesn't need to sync with itself.  Define it as array anyway so
1026    that the rest of the code base doesn't need to care for the
1027    difference.  */
1028 struct trace_buffer_control trace_buffer_ctrl[1];
1029 # define TRACE_BUFFER_CTRL_CURR 0
1030 #endif
1031
1032 /* These are convenience macros used to access the current trace
1033    buffer control in effect.  */
1034 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1035 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1036 #define trace_buffer_end_free \
1037   (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1038 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1039
1040
1041 /* Macro that returns a pointer to the first traceframe in the buffer.  */
1042
1043 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1044
1045 /* Macro that returns a pointer to the next traceframe in the buffer.
1046    If the computed location is beyond the wraparound point, subtract
1047    the offset of the wraparound.  */
1048
1049 #define NEXT_TRACEFRAME_1(TF) \
1050   (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1051
1052 #define NEXT_TRACEFRAME(TF) \
1053   ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF)  \
1054                           - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1055                              ? (trace_buffer_wrap - trace_buffer_lo)    \
1056                              : 0)))
1057
1058 /* The difference between these counters represents the total number
1059    of complete traceframes present in the trace buffer.  The IP agent
1060    writes to the write count, GDBserver writes to read count.  */
1061
1062 IP_AGENT_EXPORT unsigned int traceframe_write_count;
1063 IP_AGENT_EXPORT unsigned int traceframe_read_count;
1064
1065 /* Convenience macro.  */
1066
1067 #define traceframe_count \
1068   ((unsigned int) (traceframe_write_count - traceframe_read_count))
1069
1070 /* The count of all traceframes created in the current run, including
1071    ones that were discarded to make room.  */
1072
1073 IP_AGENT_EXPORT int traceframes_created;
1074
1075 #ifndef IN_PROCESS_AGENT
1076
1077 /* Read-only regions are address ranges whose contents don't change,
1078    and so can be read from target memory even while looking at a trace
1079    frame.  Without these, disassembly for instance will likely fail,
1080    because the program code is not usually collected into a trace
1081    frame.  This data structure does not need to be very complicated or
1082    particularly efficient, it's only going to be used occasionally,
1083    and only by some commands.  */
1084
1085 struct readonly_region
1086 {
1087   /* The bounds of the region.  */
1088   CORE_ADDR start, end;
1089
1090   /* Link to the next one.  */
1091   struct readonly_region *next;
1092 };
1093
1094 /* Linked list of readonly regions.  This list stays in effect from
1095    one tstart to the next.  */
1096
1097 static struct readonly_region *readonly_regions;
1098
1099 #endif
1100
1101 /* The global that controls tracing overall.  */
1102
1103 IP_AGENT_EXPORT int tracing;
1104
1105 #ifndef IN_PROCESS_AGENT
1106
1107 /* Controls whether tracing should continue after GDB disconnects.  */
1108
1109 int disconnected_tracing;
1110
1111 /* The reason for the last tracing run to have stopped.  We initialize
1112    to a distinct string so that GDB can distinguish between "stopped
1113    after running" and "stopped because never run" cases.  */
1114
1115 static const char *tracing_stop_reason = "tnotrun";
1116
1117 static int tracing_stop_tpnum;
1118
1119 #endif
1120
1121 /* Functions local to this file.  */
1122
1123 /* Base "class" for tracepoint type specific data to be passed down to
1124    collect_data_at_tracepoint.  */
1125 struct tracepoint_hit_ctx
1126 {
1127   enum tracepoint_type type;
1128 };
1129
1130 #ifdef IN_PROCESS_AGENT
1131
1132 /* Fast/jump tracepoint specific data to be passed down to
1133    collect_data_at_tracepoint.  */
1134 struct fast_tracepoint_ctx
1135 {
1136   struct tracepoint_hit_ctx base;
1137
1138   struct regcache regcache;
1139   int regcache_initted;
1140   unsigned char *regspace;
1141
1142   unsigned char *regs;
1143   struct tracepoint *tpoint;
1144 };
1145
1146 #else
1147
1148 /* Static tracepoint specific data to be passed down to
1149    collect_data_at_tracepoint.  */
1150 struct trap_tracepoint_ctx
1151 {
1152   struct tracepoint_hit_ctx base;
1153
1154   struct regcache *regcache;
1155 };
1156
1157 #endif
1158
1159 #ifndef IN_PROCESS_AGENT
1160 static struct agent_expr *parse_agent_expr (char **actparm);
1161 static char *unparse_agent_expr (struct agent_expr *aexpr);
1162 #endif
1163 static enum eval_result_type eval_agent_expr (struct tracepoint_hit_ctx *ctx,
1164                                               struct traceframe *tframe,
1165                                               struct agent_expr *aexpr,
1166                                               ULONGEST *rslt);
1167
1168 static int agent_mem_read (struct traceframe *tframe,
1169                            unsigned char *to, CORE_ADDR from, ULONGEST len);
1170 static int agent_tsv_read (struct traceframe *tframe, int n);
1171
1172 #ifndef IN_PROCESS_AGENT
1173 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1174 static int traceframe_read_tsv (int num, LONGEST *val);
1175 #endif
1176
1177 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1178                                          struct tracepoint *tpoint);
1179
1180 #ifndef IN_PROCESS_AGENT
1181 static void clear_readonly_regions (void);
1182 static void clear_installed_tracepoints (void);
1183 #endif
1184
1185 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1186                                         CORE_ADDR stop_pc,
1187                                         struct tracepoint *tpoint);
1188 #ifndef IN_PROCESS_AGENT
1189 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1190                                   CORE_ADDR stop_pc,
1191                                   struct tracepoint *tpoint, int current_step);
1192 #endif
1193 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1194                                      CORE_ADDR stop_pc,
1195                                      struct tracepoint *tpoint,
1196                                      struct traceframe *tframe,
1197                                      struct tracepoint_action *taction);
1198
1199 #ifndef IN_PROCESS_AGENT
1200 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1201 #endif
1202
1203 #if defined(__GNUC__)
1204 #  define memory_barrier() asm volatile ("" : : : "memory")
1205 #else
1206 #  define memory_barrier() do {} while (0)
1207 #endif
1208
1209 /* We only build the IPA if this builtin is supported, and there are
1210    no uses of this in GDBserver itself, so we're safe in defining this
1211    unconditionally.  */
1212 #define cmpxchg(mem, oldval, newval) \
1213   __sync_val_compare_and_swap (mem, oldval, newval)
1214
1215 /* Record that an error occurred during expression evaluation.  */
1216
1217 static void
1218 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1219                          enum eval_result_type rtype)
1220 {
1221   trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1222                tpoint->number, paddress (tpoint->address), which, rtype);
1223
1224 #ifdef IN_PROCESS_AGENT
1225   /* Only record the first error we get.  */
1226   if (cmpxchg (&expr_eval_result,
1227                expr_eval_no_error,
1228                rtype) != expr_eval_no_error)
1229     return;
1230 #else
1231   if (expr_eval_result != expr_eval_no_error)
1232     return;
1233 #endif
1234
1235   error_tracepoint = tpoint;
1236 }
1237
1238 /* Trace buffer management.  */
1239
1240 static void
1241 clear_trace_buffer (void)
1242 {
1243   trace_buffer_start = trace_buffer_lo;
1244   trace_buffer_free = trace_buffer_lo;
1245   trace_buffer_end_free = trace_buffer_hi;
1246   trace_buffer_wrap = trace_buffer_hi;
1247   /* A traceframe with zeroed fields marks the end of trace data.  */
1248   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1249   ((struct traceframe *) trace_buffer_free)->data_size = 0;
1250   traceframe_read_count = traceframe_write_count = 0;
1251   traceframes_created = 0;
1252 }
1253
1254 #ifndef IN_PROCESS_AGENT
1255
1256 static void
1257 clear_inferior_trace_buffer (void)
1258 {
1259   CORE_ADDR ipa_trace_buffer_lo;
1260   CORE_ADDR ipa_trace_buffer_hi;
1261   struct traceframe ipa_traceframe = { 0 };
1262   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1263
1264   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1265                               &ipa_trace_buffer_lo);
1266   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1267                               &ipa_trace_buffer_hi);
1268
1269   ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1270   ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1271   ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1272   ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1273
1274   /* A traceframe with zeroed fields marks the end of trace data.  */
1275   write_inferior_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1276                          (unsigned char *) &ipa_trace_buffer_ctrl,
1277                          sizeof (ipa_trace_buffer_ctrl));
1278
1279   write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1280
1281   /* A traceframe with zeroed fields marks the end of trace data.  */
1282   write_inferior_memory (ipa_trace_buffer_lo,
1283                          (unsigned char *) &ipa_traceframe,
1284                          sizeof (ipa_traceframe));
1285
1286   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1287   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1288   write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1289 }
1290
1291 #endif
1292
1293 static void
1294 init_trace_buffer (unsigned char *buf, int bufsize)
1295 {
1296   trace_buffer_lo = buf;
1297   trace_buffer_hi = trace_buffer_lo + bufsize;
1298
1299   clear_trace_buffer ();
1300 }
1301
1302 #ifdef IN_PROCESS_AGENT
1303
1304 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
1305 about_to_request_buffer_space (void)
1306 {
1307   /* GDBserver places breakpoint here while it goes about to flush
1308      data at random times.  */
1309   UNKNOWN_SIDE_EFFECTS();
1310 }
1311
1312 #endif
1313
1314 /* Carve out a piece of the trace buffer, returning NULL in case of
1315    failure.  */
1316
1317 static void *
1318 trace_buffer_alloc (size_t amt)
1319 {
1320   unsigned char *rslt;
1321   struct trace_buffer_control *tbctrl;
1322   unsigned int curr;
1323 #ifdef IN_PROCESS_AGENT
1324   unsigned int prev, prev_filtered;
1325   unsigned int commit_count;
1326   unsigned int commit;
1327   unsigned int readout;
1328 #else
1329   struct traceframe *oldest;
1330   unsigned char *new_start;
1331 #endif
1332
1333   trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1334                (long) amt, (long) sizeof (struct traceframe));
1335
1336   /* Account for the EOB marker.  */
1337   amt += sizeof (struct traceframe);
1338
1339 #ifdef IN_PROCESS_AGENT
1340  again:
1341   memory_barrier ();
1342
1343   /* Read the current token and extract the index to try to write to,
1344      storing it in CURR.  */
1345   prev = trace_buffer_ctrl_curr;
1346   prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1347   curr = prev_filtered + 1;
1348   if (curr > 2)
1349     curr = 0;
1350
1351   about_to_request_buffer_space ();
1352
1353   /* Start out with a copy of the current state.  GDBserver may be
1354      midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1355      be able to commit anyway if that happens.  */
1356   trace_buffer_ctrl[curr]
1357     = trace_buffer_ctrl[prev_filtered];
1358   trace_debug ("trying curr=%u", curr);
1359 #else
1360   /* The GDBserver's agent doesn't need all that syncing, and always
1361      updates TCB 0 (there's only one, mind you).  */
1362   curr = 0;
1363 #endif
1364   tbctrl = &trace_buffer_ctrl[curr];
1365
1366   /* Offsets are easier to grok for debugging than raw addresses,
1367      especially for the small trace buffer sizes that are useful for
1368      testing.  */
1369   trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1370                curr,
1371                (int) (tbctrl->start - trace_buffer_lo),
1372                (int) (tbctrl->free - trace_buffer_lo),
1373                (int) (tbctrl->end_free - trace_buffer_lo),
1374                (int) (tbctrl->wrap - trace_buffer_lo),
1375                (int) (trace_buffer_hi - trace_buffer_lo));
1376
1377   /* The algorithm here is to keep trying to get a contiguous block of
1378      the requested size, possibly discarding older traceframes to free
1379      up space.  Since free space might come in one or two pieces,
1380      depending on whether discarded traceframes wrapped around at the
1381      high end of the buffer, we test both pieces after each
1382      discard.  */
1383   while (1)
1384     {
1385       /* First, if we have two free parts, try the upper one first.  */
1386       if (tbctrl->end_free < tbctrl->free)
1387         {
1388           if (tbctrl->free + amt <= trace_buffer_hi)
1389             /* We have enough in the upper part.  */
1390             break;
1391           else
1392             {
1393               /* Our high part of free space wasn't enough.  Give up
1394                  on it for now, set wraparound.  We will recover the
1395                  space later, if/when the wrapped-around traceframe is
1396                  discarded.  */
1397               trace_debug ("Upper part too small, setting wraparound");
1398               tbctrl->wrap = tbctrl->free;
1399               tbctrl->free = trace_buffer_lo;
1400             }
1401         }
1402
1403       /* The normal case.  */
1404       if (tbctrl->free + amt <= tbctrl->end_free)
1405         break;
1406
1407 #ifdef IN_PROCESS_AGENT
1408       /* The IP Agent's buffer is always circular.  It isn't used
1409          currently, but `circular_trace_buffer' could represent
1410          GDBserver's mode.  If we didn't find space, ask GDBserver to
1411          flush.  */
1412
1413       flush_trace_buffer ();
1414       memory_barrier ();
1415       if (tracing)
1416         {
1417           trace_debug ("gdbserver flushed buffer, retrying");
1418           goto again;
1419         }
1420
1421       /* GDBserver cancelled the tracing.  Bail out as well.  */
1422       return NULL;
1423 #else
1424       /* If we're here, then neither part is big enough, and
1425          non-circular trace buffers are now full.  */
1426       if (!circular_trace_buffer)
1427         {
1428           trace_debug ("Not enough space in the trace buffer");
1429           return NULL;
1430         }
1431
1432       trace_debug ("Need more space in the trace buffer");
1433
1434       /* If we have a circular buffer, we can try discarding the
1435          oldest traceframe and see if that helps.  */
1436       oldest = FIRST_TRACEFRAME ();
1437       if (oldest->tpnum == 0)
1438         {
1439           /* Not good; we have no traceframes to free.  Perhaps we're
1440              asking for a block that is larger than the buffer?  In
1441              any case, give up.  */
1442           trace_debug ("No traceframes to discard");
1443           return NULL;
1444         }
1445
1446       /* We don't run this code in the in-process agent currently.
1447          E.g., we could leave the in-process agent in autonomous
1448          circular mode if we only have fast tracepoints.  If we do
1449          that, then this bit becomes racy with GDBserver, which also
1450          writes to this counter.  */
1451       --traceframe_write_count;
1452
1453       new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1454       /* If we freed the traceframe that wrapped around, go back
1455          to the non-wrap case.  */
1456       if (new_start < tbctrl->start)
1457         {
1458           trace_debug ("Discarding past the wraparound");
1459           tbctrl->wrap = trace_buffer_hi;
1460         }
1461       tbctrl->start = new_start;
1462       tbctrl->end_free = tbctrl->start;
1463
1464       trace_debug ("Discarded a traceframe\n"
1465                    "Trace buffer [%d], start=%d free=%d "
1466                    "endfree=%d wrap=%d hi=%d",
1467                    curr,
1468                    (int) (tbctrl->start - trace_buffer_lo),
1469                    (int) (tbctrl->free - trace_buffer_lo),
1470                    (int) (tbctrl->end_free - trace_buffer_lo),
1471                    (int) (tbctrl->wrap - trace_buffer_lo),
1472                    (int) (trace_buffer_hi - trace_buffer_lo));
1473
1474       /* Now go back around the loop.  The discard might have resulted
1475          in either one or two pieces of free space, so we want to try
1476          both before freeing any more traceframes.  */
1477 #endif
1478     }
1479
1480   /* If we get here, we know we can provide the asked-for space.  */
1481
1482   rslt = tbctrl->free;
1483
1484   /* Adjust the request back down, now that we know we have space for
1485      the marker, but don't commit to AMT yet, we may still need to
1486      restart the operation if GDBserver touches the trace buffer
1487      (obviously only important in the in-process agent's version).  */
1488   tbctrl->free += (amt - sizeof (struct traceframe));
1489
1490   /* Or not.  If GDBserver changed the trace buffer behind our back,
1491      we get to restart a new allocation attempt.  */
1492
1493 #ifdef IN_PROCESS_AGENT
1494   /* Build the tentative token.  */
1495   commit_count = (((prev & 0x0007ff00) + 0x100) & 0x0007ff00);
1496   commit = (((prev & 0x0007ff00) << 12)
1497             | commit_count
1498             | curr);
1499
1500   /* Try to commit it.  */
1501   readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1502   if (readout != prev)
1503     {
1504       trace_debug ("GDBserver has touched the trace buffer, restarting."
1505                    " (prev=%08x, commit=%08x, readout=%08x)",
1506                    prev, commit, readout);
1507       goto again;
1508     }
1509
1510   /* Hold your horses here.  Even if that change was committed,
1511      GDBserver could come in, and clobber it.  We need to hold to be
1512      able to tell if GDBserver clobbers before or after we committed
1513      the change.  Whenever GDBserver goes about touching the IPA
1514      buffer, it sets a breakpoint in this routine, so we have a sync
1515      point here.  */
1516   about_to_request_buffer_space ();
1517
1518   /* Check if the change has been effective, even if GDBserver stopped
1519      us at the breakpoint.  */
1520
1521   {
1522     unsigned int refetch;
1523
1524     memory_barrier ();
1525
1526     refetch = trace_buffer_ctrl_curr;
1527
1528     if ((refetch == commit
1529          || ((refetch & 0x7ff00000) >> 12) == commit_count))
1530       {
1531         /* effective */
1532         trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1533                      "readout=%08x, refetch=%08x)",
1534                      prev, commit, readout, refetch);
1535       }
1536     else
1537       {
1538         trace_debug ("GDBserver has touched the trace buffer, not effective."
1539                      " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1540                      prev, commit, readout, refetch);
1541         goto again;
1542       }
1543   }
1544 #endif
1545
1546   /* We have a new piece of the trace buffer.  Hurray!  */
1547
1548   /* Add an EOB marker just past this allocation.  */
1549   ((struct traceframe *) tbctrl->free)->tpnum = 0;
1550   ((struct traceframe *) tbctrl->free)->data_size = 0;
1551
1552   /* Adjust the request back down, now that we know we have space for
1553      the marker.  */
1554   amt -= sizeof (struct traceframe);
1555
1556   if (debug_threads)
1557     {
1558       trace_debug ("Allocated %d bytes", (int) amt);
1559       trace_debug ("Trace buffer [%d] start=%d free=%d "
1560                    "endfree=%d wrap=%d hi=%d",
1561                    curr,
1562                    (int) (tbctrl->start - trace_buffer_lo),
1563                    (int) (tbctrl->free - trace_buffer_lo),
1564                    (int) (tbctrl->end_free - trace_buffer_lo),
1565                    (int) (tbctrl->wrap - trace_buffer_lo),
1566                    (int) (trace_buffer_hi - trace_buffer_lo));
1567     }
1568
1569   return rslt;
1570 }
1571
1572 #ifndef IN_PROCESS_AGENT
1573
1574 /* Return the total free space.  This is not necessarily the largest
1575    block we can allocate, because of the two-part case.  */
1576
1577 static int
1578 free_space (void)
1579 {
1580   if (trace_buffer_free <= trace_buffer_end_free)
1581     return trace_buffer_end_free - trace_buffer_free;
1582   else
1583     return ((trace_buffer_end_free - trace_buffer_lo)
1584             + (trace_buffer_hi - trace_buffer_free));
1585 }
1586
1587 /* An 'S' in continuation packets indicates remainder are for
1588    while-stepping.  */
1589
1590 static int seen_step_action_flag;
1591
1592 /* Create a tracepoint (location) with given number and address.  */
1593
1594 static struct tracepoint *
1595 add_tracepoint (int num, CORE_ADDR addr)
1596 {
1597   struct tracepoint *tpoint;
1598
1599   tpoint = xmalloc (sizeof (struct tracepoint));
1600   tpoint->number = num;
1601   tpoint->address = addr;
1602   tpoint->numactions = 0;
1603   tpoint->actions = NULL;
1604   tpoint->actions_str = NULL;
1605   tpoint->cond = NULL;
1606   tpoint->num_step_actions = 0;
1607   tpoint->step_actions = NULL;
1608   tpoint->step_actions_str = NULL;
1609   /* Start all off as regular (slow) tracepoints.  */
1610   tpoint->type = trap_tracepoint;
1611   tpoint->orig_size = -1;
1612   tpoint->source_strings = NULL;
1613   tpoint->handle = NULL;
1614   tpoint->next = NULL;
1615
1616   if (!last_tracepoint)
1617     tracepoints = tpoint;
1618   else
1619     last_tracepoint->next = tpoint;
1620   last_tracepoint = tpoint;
1621
1622   seen_step_action_flag = 0;
1623
1624   return tpoint;
1625 }
1626
1627 #ifndef IN_PROCESS_AGENT
1628
1629 /* Return the tracepoint with the given number and address, or NULL.  */
1630
1631 static struct tracepoint *
1632 find_tracepoint (int id, CORE_ADDR addr)
1633 {
1634   struct tracepoint *tpoint;
1635
1636   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1637     if (tpoint->number == id && tpoint->address == addr)
1638       return tpoint;
1639
1640   return NULL;
1641 }
1642
1643 /* There may be several tracepoints with the same number (because they
1644    are "locations", in GDB parlance); return the next one after the
1645    given tracepoint, or search from the beginning of the list if the
1646    first argument is NULL.  */
1647
1648 static struct tracepoint *
1649 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1650 {
1651   struct tracepoint *tpoint;
1652
1653   if (prev_tp)
1654     tpoint = prev_tp->next;
1655   else
1656     tpoint = tracepoints;
1657   for (; tpoint; tpoint = tpoint->next)
1658     if (tpoint->number == num)
1659       return tpoint;
1660
1661   return NULL;
1662 }
1663
1664 #endif
1665
1666 static char *
1667 save_string (const char *str, size_t len)
1668 {
1669   char *s;
1670
1671   s = xmalloc (len + 1);
1672   memcpy (s, str, len);
1673   s[len] = '\0';
1674
1675   return s;
1676 }
1677
1678 /* Append another action to perform when the tracepoint triggers.  */
1679
1680 static void
1681 add_tracepoint_action (struct tracepoint *tpoint, char *packet)
1682 {
1683   char *act;
1684
1685   if (*packet == 'S')
1686     {
1687       seen_step_action_flag = 1;
1688       ++packet;
1689     }
1690
1691   act = packet;
1692
1693   while (*act)
1694     {
1695       char *act_start = act;
1696       struct tracepoint_action *action = NULL;
1697
1698       switch (*act)
1699         {
1700         case 'M':
1701           {
1702             struct collect_memory_action *maction;
1703             ULONGEST basereg;
1704             int is_neg;
1705
1706             maction = xmalloc (sizeof *maction);
1707             maction->base.type = *act;
1708             action = &maction->base;
1709
1710             ++act;
1711             is_neg = (*act == '-');
1712             if (*act == '-')
1713               ++act;
1714             act = unpack_varlen_hex (act, &basereg);
1715             ++act;
1716             act = unpack_varlen_hex (act, &maction->addr);
1717             ++act;
1718             act = unpack_varlen_hex (act, &maction->len);
1719             maction->basereg = (is_neg
1720                                 ? - (int) basereg
1721                                 : (int) basereg);
1722             trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1723                          pulongest (maction->len),
1724                          paddress (maction->addr), maction->basereg);
1725             break;
1726           }
1727         case 'R':
1728           {
1729             struct collect_registers_action *raction;
1730
1731             raction = xmalloc (sizeof *raction);
1732             raction->base.type = *act;
1733             action = &raction->base;
1734
1735             trace_debug ("Want to collect registers");
1736             ++act;
1737             /* skip past hex digits of mask for now */
1738             while (isxdigit(*act))
1739               ++act;
1740             break;
1741           }
1742         case 'S':
1743           trace_debug ("Unexpected step action, ignoring");
1744           ++act;
1745           break;
1746         case 'X':
1747           {
1748             struct eval_expr_action *xaction;
1749
1750             xaction = xmalloc (sizeof (*xaction));
1751             xaction->base.type = *act;
1752             action = &xaction->base;
1753
1754             trace_debug ("Want to evaluate expression");
1755             xaction->expr = parse_agent_expr (&act);
1756             break;
1757           }
1758         default:
1759           trace_debug ("unknown trace action '%c', ignoring...", *act);
1760           break;
1761         case '-':
1762           break;
1763         }
1764
1765       if (action == NULL)
1766         break;
1767
1768       if (seen_step_action_flag)
1769         {
1770           tpoint->num_step_actions++;
1771
1772           tpoint->step_actions
1773             = xrealloc (tpoint->step_actions,
1774                         (sizeof (*tpoint->step_actions)
1775                          * tpoint->num_step_actions));
1776           tpoint->step_actions_str
1777             = xrealloc (tpoint->step_actions_str,
1778                         (sizeof (*tpoint->step_actions_str)
1779                          * tpoint->num_step_actions));
1780           tpoint->step_actions[tpoint->num_step_actions - 1] = action;
1781           tpoint->step_actions_str[tpoint->num_step_actions - 1]
1782             = save_string (act_start, act - act_start);
1783         }
1784       else
1785         {
1786           tpoint->numactions++;
1787           tpoint->actions
1788             = xrealloc (tpoint->actions,
1789                         sizeof (*tpoint->actions) * tpoint->numactions);
1790           tpoint->actions_str
1791             = xrealloc (tpoint->actions_str,
1792                         sizeof (*tpoint->actions_str) * tpoint->numactions);
1793           tpoint->actions[tpoint->numactions - 1] = action;
1794           tpoint->actions_str[tpoint->numactions - 1]
1795             = save_string (act_start, act - act_start);
1796         }
1797     }
1798 }
1799
1800 #endif
1801
1802 /* Find or create a trace state variable with the given number.  */
1803
1804 static struct trace_state_variable *
1805 get_trace_state_variable (int num)
1806 {
1807   struct trace_state_variable *tsv;
1808
1809 #ifdef IN_PROCESS_AGENT
1810   /* Search for an existing variable.  */
1811   for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
1812     if (tsv->number == num)
1813       return tsv;
1814 #endif
1815
1816   /* Search for an existing variable.  */
1817   for (tsv = trace_state_variables; tsv; tsv = tsv->next)
1818     if (tsv->number == num)
1819       return tsv;
1820
1821   return NULL;
1822 }
1823
1824 /* Find or create a trace state variable with the given number.  */
1825
1826 static struct trace_state_variable *
1827 create_trace_state_variable (int num, int gdb)
1828 {
1829   struct trace_state_variable *tsv;
1830
1831   tsv = get_trace_state_variable (num);
1832   if (tsv != NULL)
1833     return tsv;
1834
1835   /* Create a new variable.  */
1836   tsv = xmalloc (sizeof (struct trace_state_variable));
1837   tsv->number = num;
1838   tsv->initial_value = 0;
1839   tsv->value = 0;
1840   tsv->getter = NULL;
1841   tsv->name = NULL;
1842 #ifdef IN_PROCESS_AGENT
1843   if (!gdb)
1844     {
1845       tsv->next = alloced_trace_state_variables;
1846       alloced_trace_state_variables = tsv;
1847     }
1848   else
1849 #endif
1850     {
1851       tsv->next = trace_state_variables;
1852       trace_state_variables = tsv;
1853     }
1854   return tsv;
1855 }
1856
1857 static LONGEST
1858 get_trace_state_variable_value (int num)
1859 {
1860   struct trace_state_variable *tsv;
1861
1862   tsv = get_trace_state_variable (num);
1863
1864   if (!tsv)
1865     {
1866       trace_debug ("No trace state variable %d, skipping value get", num);
1867       return 0;
1868     }
1869
1870   /* Call a getter function if we have one.  While it's tempting to
1871      set up something to only call the getter once per tracepoint hit,
1872      it could run afoul of thread races. Better to let the getter
1873      handle it directly, if necessary to worry about it.  */
1874   if (tsv->getter)
1875     tsv->value = (tsv->getter) ();
1876
1877   trace_debug ("get_trace_state_variable_value(%d) ==> %s",
1878                num, plongest (tsv->value));
1879
1880   return tsv->value;
1881 }
1882
1883 static void
1884 set_trace_state_variable_value (int num, LONGEST val)
1885 {
1886   struct trace_state_variable *tsv;
1887
1888   tsv = get_trace_state_variable (num);
1889
1890   if (!tsv)
1891     {
1892       trace_debug ("No trace state variable %d, skipping value set", num);
1893       return;
1894     }
1895
1896   tsv->value = val;
1897 }
1898
1899 static void
1900 set_trace_state_variable_name (int num, const char *name)
1901 {
1902   struct trace_state_variable *tsv;
1903
1904   tsv = get_trace_state_variable (num);
1905
1906   if (!tsv)
1907     {
1908       trace_debug ("No trace state variable %d, skipping name set", num);
1909       return;
1910     }
1911
1912   tsv->name = (char *) name;
1913 }
1914
1915 static void
1916 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
1917 {
1918   struct trace_state_variable *tsv;
1919
1920   tsv = get_trace_state_variable (num);
1921
1922   if (!tsv)
1923     {
1924       trace_debug ("No trace state variable %d, skipping getter set", num);
1925       return;
1926     }
1927
1928   tsv->getter = getter;
1929 }
1930
1931 /* Add a raw traceframe for the given tracepoint.  */
1932
1933 static struct traceframe *
1934 add_traceframe (struct tracepoint *tpoint)
1935 {
1936   struct traceframe *tframe;
1937
1938   tframe = trace_buffer_alloc (sizeof (struct traceframe));
1939
1940   if (tframe == NULL)
1941     return NULL;
1942
1943   tframe->tpnum = tpoint->number;
1944   tframe->data_size = 0;
1945
1946   return tframe;
1947 }
1948
1949 /* Add a block to the traceframe currently being worked on.  */
1950
1951 static unsigned char *
1952 add_traceframe_block (struct traceframe *tframe, int amt)
1953 {
1954   unsigned char *block;
1955
1956   if (!tframe)
1957     return NULL;
1958
1959   block = trace_buffer_alloc (amt);
1960
1961   if (!block)
1962     return NULL;
1963
1964   tframe->data_size += amt;
1965
1966   return block;
1967 }
1968
1969 /* Flag that the current traceframe is finished.  */
1970
1971 static void
1972 finish_traceframe (struct traceframe *tframe)
1973 {
1974   ++traceframe_write_count;
1975   ++traceframes_created;
1976 }
1977
1978 #ifndef IN_PROCESS_AGENT
1979
1980 /* Given a traceframe number NUM, find the NUMth traceframe in the
1981    buffer.  */
1982
1983 static struct traceframe *
1984 find_traceframe (int num)
1985 {
1986   struct traceframe *tframe;
1987   int tfnum = 0;
1988
1989   for (tframe = FIRST_TRACEFRAME ();
1990        tframe->tpnum != 0;
1991        tframe = NEXT_TRACEFRAME (tframe))
1992     {
1993       if (tfnum == num)
1994         return tframe;
1995       ++tfnum;
1996     }
1997
1998   return NULL;
1999 }
2000
2001 static CORE_ADDR
2002 get_traceframe_address (struct traceframe *tframe)
2003 {
2004   CORE_ADDR addr;
2005   struct tracepoint *tpoint;
2006
2007   addr = traceframe_get_pc (tframe);
2008
2009   if (addr)
2010     return addr;
2011
2012   /* Fallback strategy, will be incorrect for while-stepping frames
2013      and multi-location tracepoints.  */
2014   tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2015   return tpoint->address;
2016 }
2017
2018 /* Search for the next traceframe whose address is inside or outside
2019    the given range.  */
2020
2021 static struct traceframe *
2022 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2023                                int *tfnump)
2024 {
2025   struct traceframe *tframe;
2026   CORE_ADDR tfaddr;
2027
2028   *tfnump = current_traceframe + 1;
2029   tframe = find_traceframe (*tfnump);
2030   /* The search is not supposed to wrap around.  */
2031   if (!tframe)
2032     {
2033       *tfnump = -1;
2034       return NULL;
2035     }
2036
2037   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2038     {
2039       tfaddr = get_traceframe_address (tframe);
2040       if (inside_p
2041           ? (lo <= tfaddr && tfaddr <= hi)
2042           : (lo > tfaddr || tfaddr > hi))
2043         return tframe;
2044       ++*tfnump;
2045     }
2046
2047   *tfnump = -1;
2048   return NULL;
2049 }
2050
2051 /* Search for the next traceframe recorded by the given tracepoint.
2052    Note that for multi-location tracepoints, this will find whatever
2053    location appears first.  */
2054
2055 static struct traceframe *
2056 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2057 {
2058   struct traceframe *tframe;
2059
2060   *tfnump = current_traceframe + 1;
2061   tframe = find_traceframe (*tfnump);
2062   /* The search is not supposed to wrap around.  */
2063   if (!tframe)
2064     {
2065       *tfnump = -1;
2066       return NULL;
2067     }
2068
2069   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2070     {
2071       if (tframe->tpnum == num)
2072         return tframe;
2073       ++*tfnump;
2074     }
2075
2076   *tfnump = -1;
2077   return NULL;
2078 }
2079
2080 #endif
2081
2082 #ifndef IN_PROCESS_AGENT
2083
2084 /* Clear all past trace state.  */
2085
2086 static void
2087 cmd_qtinit (char *packet)
2088 {
2089   struct trace_state_variable *tsv, *prev, *next;
2090
2091   /* Make sure we don't try to read from a trace frame.  */
2092   current_traceframe = -1;
2093
2094   trace_debug ("Initializing the trace");
2095
2096   clear_installed_tracepoints ();
2097   clear_readonly_regions ();
2098
2099   tracepoints = NULL;
2100   last_tracepoint = NULL;
2101
2102   /* Clear out any leftover trace state variables.  Ones with target
2103      defined getters should be kept however.  */
2104   prev = NULL;
2105   tsv = trace_state_variables;
2106   while (tsv)
2107     {
2108       trace_debug ("Looking at var %d", tsv->number);
2109       if (tsv->getter == NULL)
2110         {
2111           next = tsv->next;
2112           if (prev)
2113             prev->next = next;
2114           else
2115             trace_state_variables = next;
2116           trace_debug ("Deleting var %d", tsv->number);
2117           free (tsv);
2118           tsv = next;
2119         }
2120       else
2121         {
2122           prev = tsv;
2123           tsv = tsv->next;
2124         }
2125     }
2126
2127   clear_trace_buffer ();
2128   clear_inferior_trace_buffer ();
2129
2130   write_ok (packet);
2131 }
2132
2133 /* Restore the program to its pre-tracing state.  This routine may be called
2134    in error situations, so it needs to be careful about only restoring
2135    from known-valid bits.  */
2136
2137 static void
2138 clear_installed_tracepoints (void)
2139 {
2140   struct tracepoint *tpoint;
2141   struct tracepoint *prev_stpoint;
2142
2143   pause_all (1);
2144   cancel_breakpoints ();
2145
2146   prev_stpoint = NULL;
2147
2148   /* Restore any bytes overwritten by tracepoints.  */
2149   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2150     {
2151       if (!tpoint->enabled)
2152         continue;
2153
2154       /* Catch the case where we might try to remove a tracepoint that
2155          was never actually installed.  */
2156       if (tpoint->handle == NULL)
2157         {
2158           trace_debug ("Tracepoint %d at 0x%s was "
2159                        "never installed, nothing to clear",
2160                        tpoint->number, paddress (tpoint->address));
2161           continue;
2162         }
2163
2164       switch (tpoint->type)
2165         {
2166         case trap_tracepoint:
2167           delete_breakpoint (tpoint->handle);
2168           break;
2169         case fast_tracepoint:
2170           delete_fast_tracepoint_jump (tpoint->handle);
2171           break;
2172         }
2173
2174       tpoint->handle = NULL;
2175     }
2176
2177   unpause_all (1);
2178 }
2179
2180 /* Parse a packet that defines a tracepoint.  */
2181
2182 static void
2183 cmd_qtdp (char *own_buf)
2184 {
2185   int tppacket;
2186   ULONGEST num;
2187   ULONGEST addr;
2188   ULONGEST count;
2189   struct tracepoint *tpoint;
2190   char *actparm;
2191   char *packet = own_buf;
2192
2193   packet += strlen ("QTDP:");
2194
2195   /* A hyphen at the beginning marks a packet specifying actions for a
2196      tracepoint already supplied.  */
2197   tppacket = 1;
2198   if (*packet == '-')
2199     {
2200       tppacket = 0;
2201       ++packet;
2202     }
2203   packet = unpack_varlen_hex (packet, &num);
2204   ++packet; /* skip a colon */
2205   packet = unpack_varlen_hex (packet, &addr);
2206   ++packet; /* skip a colon */
2207
2208   /* See if we already have this tracepoint.  */
2209   tpoint = find_tracepoint (num, addr);
2210
2211   if (tppacket)
2212     {
2213       /* Duplicate tracepoints are never allowed.  */
2214       if (tpoint)
2215         {
2216           trace_debug ("Tracepoint error: tracepoint %d"
2217                        " at 0x%s already exists",
2218                        (int) num, paddress (addr));
2219           write_enn (own_buf);
2220           return;
2221         }
2222
2223       tpoint = add_tracepoint (num, addr);
2224
2225       tpoint->enabled = (*packet == 'E');
2226       ++packet; /* skip 'E' */
2227       ++packet; /* skip a colon */
2228       packet = unpack_varlen_hex (packet, &count);
2229       tpoint->step_count = count;
2230       ++packet; /* skip a colon */
2231       packet = unpack_varlen_hex (packet, &count);
2232       tpoint->pass_count = count;
2233       /* See if we have any of the additional optional fields.  */
2234       while (*packet == ':')
2235         {
2236           ++packet;
2237           if (*packet == 'F')
2238             {
2239               tpoint->type = fast_tracepoint;
2240               ++packet;
2241               packet = unpack_varlen_hex (packet, &count);
2242               tpoint->orig_size = count;
2243             }
2244           else if (*packet == 'X')
2245             {
2246               actparm = (char *) packet;
2247               tpoint->cond = parse_agent_expr (&actparm);
2248               packet = actparm;
2249             }
2250           else if (*packet == '-')
2251             break;
2252           else if (*packet == '\0')
2253             break;
2254           else
2255             trace_debug ("Unknown optional tracepoint field");
2256         }
2257       if (*packet == '-')
2258         trace_debug ("Also has actions\n");
2259
2260       trace_debug ("Defined %stracepoint %d at 0x%s, "
2261                    "enabled %d step %ld pass %ld",
2262                    tpoint->type == fast_tracepoint ? "fast "
2263                    : "",
2264                    tpoint->number, paddress (tpoint->address), tpoint->enabled,
2265                    tpoint->step_count, tpoint->pass_count);
2266     }
2267   else if (tpoint)
2268     add_tracepoint_action (tpoint, packet);
2269   else
2270     {
2271       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2272                    (int) num, paddress (addr));
2273       write_enn (own_buf);
2274       return;
2275     }
2276
2277   write_ok (own_buf);
2278 }
2279
2280 static void
2281 cmd_qtdpsrc (char *own_buf)
2282 {
2283   ULONGEST num, addr, start, slen;
2284   struct tracepoint *tpoint;
2285   char *packet = own_buf;
2286   char *saved, *srctype, *src;
2287   size_t nbytes;
2288   struct source_string *last, *newlast;
2289
2290   packet += strlen ("QTDPsrc:");
2291
2292   packet = unpack_varlen_hex (packet, &num);
2293   ++packet; /* skip a colon */
2294   packet = unpack_varlen_hex (packet, &addr);
2295   ++packet; /* skip a colon */
2296
2297   /* See if we already have this tracepoint.  */
2298   tpoint = find_tracepoint (num, addr);
2299
2300   if (!tpoint)
2301     {
2302       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2303                    (int) num, paddress (addr));
2304       write_enn (own_buf);
2305       return;
2306     }
2307
2308   saved = packet;
2309   packet = strchr (packet, ':');
2310   srctype = xmalloc (packet - saved + 1);
2311   memcpy (srctype, saved, packet - saved);
2312   srctype[packet - saved] = '\0';
2313   ++packet;
2314   packet = unpack_varlen_hex (packet, &start);
2315   ++packet; /* skip a colon */
2316   packet = unpack_varlen_hex (packet, &slen);
2317   ++packet; /* skip a colon */
2318   src = xmalloc (slen + 1);
2319   nbytes = unhexify (src, packet, strlen (packet) / 2);
2320   src[nbytes] = '\0';
2321
2322   newlast = xmalloc (sizeof (struct source_string));
2323   newlast->type = srctype;
2324   newlast->str = src;
2325   newlast->next = NULL;
2326   /* Always add a source string to the end of the list;
2327      this keeps sequences of actions/commands in the right
2328      order.  */
2329   if (tpoint->source_strings)
2330     {
2331       for (last = tpoint->source_strings; last->next; last = last->next)
2332         ;
2333       last->next = newlast;
2334     }
2335   else
2336     tpoint->source_strings = newlast;
2337
2338   write_ok (own_buf);
2339 }
2340
2341 static void
2342 cmd_qtdv (char *own_buf)
2343 {
2344   ULONGEST num, val, builtin;
2345   char *varname;
2346   size_t nbytes;
2347   struct trace_state_variable *tsv;
2348   char *packet = own_buf;
2349
2350   packet += strlen ("QTDV:");
2351
2352   packet = unpack_varlen_hex (packet, &num);
2353   ++packet; /* skip a colon */
2354   packet = unpack_varlen_hex (packet, &val);
2355   ++packet; /* skip a colon */
2356   packet = unpack_varlen_hex (packet, &builtin);
2357   ++packet; /* skip a colon */
2358
2359   nbytes = strlen (packet) / 2;
2360   varname = xmalloc (nbytes + 1);
2361   nbytes = unhexify (varname, packet, nbytes);
2362   varname[nbytes] = '\0';
2363
2364   tsv = create_trace_state_variable (num, 1);
2365   tsv->initial_value = (LONGEST) val;
2366   tsv->name = varname;
2367
2368   set_trace_state_variable_value (num, (LONGEST) val);
2369
2370   write_ok (own_buf);
2371 }
2372
2373 static void
2374 cmd_qtv (char *own_buf)
2375 {
2376   ULONGEST num;
2377   LONGEST val;
2378   int err;
2379   char *packet = own_buf;
2380
2381   packet += strlen ("qTV:");
2382   packet = unpack_varlen_hex (packet, &num);
2383
2384   if (current_traceframe >= 0)
2385     {
2386       err = traceframe_read_tsv ((int) num, &val);
2387       if (err)
2388         {
2389           strcpy (own_buf, "U");
2390           return;
2391         }
2392     }
2393   /* Only make tsv's be undefined before the first trace run.  After a
2394      trace run is over, the user might want to see the last value of
2395      the tsv, and it might not be available in a traceframe.  */
2396   else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2397     {
2398       strcpy (own_buf, "U");
2399       return;
2400     }
2401   else
2402     val = get_trace_state_variable_value (num);
2403
2404   sprintf (own_buf, "V%s", phex_nz (val, 0));
2405 }
2406
2407 /* Clear out the list of readonly regions.  */
2408
2409 static void
2410 clear_readonly_regions (void)
2411 {
2412   struct readonly_region *roreg;
2413
2414   while (readonly_regions)
2415     {
2416       roreg = readonly_regions;
2417       readonly_regions = readonly_regions->next;
2418       free (roreg);
2419     }
2420 }
2421
2422 /* Parse the collection of address ranges whose contents GDB believes
2423    to be unchanging and so can be read directly from target memory
2424    even while looking at a traceframe.  */
2425
2426 static void
2427 cmd_qtro (char *own_buf)
2428 {
2429   ULONGEST start, end;
2430   struct readonly_region *roreg;
2431   char *packet = own_buf;
2432
2433   trace_debug ("Want to mark readonly regions");
2434
2435   clear_readonly_regions ();
2436
2437   packet += strlen ("QTro");
2438
2439   while (*packet == ':')
2440     {
2441       ++packet;  /* skip a colon */
2442       packet = unpack_varlen_hex (packet, &start);
2443       ++packet;  /* skip a comma */
2444       packet = unpack_varlen_hex (packet, &end);
2445       roreg = xmalloc (sizeof (struct readonly_region));
2446       roreg->start = start;
2447       roreg->end = end;
2448       roreg->next = readonly_regions;
2449       readonly_regions = roreg;
2450       trace_debug ("Added readonly region from 0x%s to 0x%s",
2451                    paddress (roreg->start), paddress (roreg->end));
2452     }
2453
2454   write_ok (own_buf);
2455 }
2456
2457 /* Test to see if the given range is in our list of readonly ranges.
2458    We only test for being entirely within a range, GDB is not going to
2459    send a single memory packet that spans multiple regions.  */
2460
2461 int
2462 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2463 {
2464   struct readonly_region *roreg;
2465
2466   for (roreg = readonly_regions; roreg; roreg = roreg->next)
2467     if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2468       return 1;
2469
2470   return 0;
2471 }
2472
2473 /* The maximum size of a jump pad entry.  */
2474 static const int max_jump_pad_size = 0x100;
2475
2476 static CORE_ADDR gdb_jump_pad_head;
2477
2478 /* Return the address of the next free jump space.  */
2479
2480 static CORE_ADDR
2481 get_jump_space_head (void)
2482 {
2483   if (gdb_jump_pad_head == 0)
2484     {
2485       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2486                                       &gdb_jump_pad_head))
2487         fatal ("error extracting jump_pad_buffer");
2488     }
2489
2490   return gdb_jump_pad_head;
2491 }
2492
2493 /* Reserve USED bytes from the jump space.  */
2494
2495 static void
2496 claim_jump_space (ULONGEST used)
2497 {
2498   trace_debug ("claim_jump_space reserves %s bytes at %s",
2499                pulongest (used), paddress (gdb_jump_pad_head));
2500   gdb_jump_pad_head += used;
2501 }
2502
2503 /* Sort tracepoints by PC, using a bubble sort.  */
2504
2505 static void
2506 sort_tracepoints (void)
2507 {
2508   struct tracepoint *lst, *tmp, *prev = NULL;
2509   int i, j, n = 0;
2510
2511   if (tracepoints == NULL)
2512     return;
2513
2514   /* Count nodes.  */
2515   for (tmp = tracepoints; tmp->next; tmp = tmp->next)
2516     n++;
2517
2518   for (i = 0; i < n - 1; i++)
2519     for (j = 0, lst = tracepoints;
2520          lst && lst->next && (j <= n - 1 - i);
2521          j++)
2522       {
2523         /* If we're at beginning, the start node is the prev
2524            node.  */
2525         if (j == 0)
2526           prev = lst;
2527
2528         /* Compare neighbors.  */
2529         if (lst->next->address < lst->address)
2530           {
2531             struct tracepoint *p;
2532
2533             /* Swap'em.  */
2534             tmp = (lst->next ? lst->next->next : NULL);
2535
2536             if (j == 0 && prev == tracepoints)
2537               tracepoints = lst->next;
2538
2539             p = lst->next;
2540             prev->next = lst->next;
2541             lst->next->next = lst;
2542             lst->next = tmp;
2543             prev = p;
2544           }
2545         else
2546           {
2547             lst = lst->next;
2548             /* Keep track of the previous node.  We need it if we need
2549                to swap nodes.  */
2550             if (j != 0)
2551               prev = prev->next;
2552           }
2553       }
2554 }
2555
2556 #define MAX_JUMP_SIZE 20
2557
2558 static void
2559 cmd_qtstart (char *packet)
2560 {
2561   struct tracepoint *tpoint, *prev_ftpoint;
2562   int slow_tracepoint_count, fast_count;
2563   CORE_ADDR jump_entry;
2564
2565   /* The jump to the jump pad of the last fast tracepoint
2566      installed.  */
2567   unsigned char fjump[MAX_JUMP_SIZE];
2568   ULONGEST fjump_size;
2569
2570   trace_debug ("Starting the trace");
2571
2572   slow_tracepoint_count = fast_count = 0;
2573
2574   /* Sort tracepoints by ascending address.  This makes installing
2575      fast tracepoints at the same address easier to handle. */
2576   sort_tracepoints ();
2577
2578   /* Pause all threads temporarily while we patch tracepoints.  */
2579   pause_all (0);
2580
2581   /* Get threads out of jump pads.  Safe to do here, since this is a
2582      top level command.  And, required to do here, since we're
2583      deleting/rewriting jump pads.  */
2584
2585   stabilize_threads ();
2586
2587   /* Freeze threads.  */
2588   pause_all (1);
2589
2590   /* Sync the fast tracepoints list in the inferior ftlib.  */
2591   if (in_process_agent_loaded ())
2592     {
2593       download_tracepoints ();
2594       download_trace_state_variables ();
2595     }
2596
2597   /* No previous fast tpoint yet.  */
2598   prev_ftpoint = NULL;
2599
2600   *packet = '\0';
2601
2602   /* Install tracepoints.  */
2603   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2604     {
2605       /* Ensure all the hit counts start at zero.  */
2606       tpoint->hit_count = 0;
2607
2608       if (!tpoint->enabled)
2609         continue;
2610
2611       if (tpoint->type == trap_tracepoint)
2612         {
2613           ++slow_tracepoint_count;
2614
2615           /* Tracepoints are installed as memory breakpoints.  Just go
2616              ahead and install the trap.  The breakpoints module
2617              handles duplicated breakpoints, and the memory read
2618              routine handles un-patching traps from memory reads.  */
2619           tpoint->handle = set_breakpoint_at (tpoint->address,
2620                                               tracepoint_handler);
2621         }
2622       else if (tpoint->type == fast_tracepoint)
2623         {
2624           ++fast_count;
2625
2626           if (maybe_write_ipa_not_loaded (packet))
2627             {
2628               trace_debug ("Requested a fast tracepoint, but fast "
2629                            "tracepoints aren't supported.");
2630               break;
2631             }
2632
2633           if (prev_ftpoint != NULL && prev_ftpoint->address == tpoint->address)
2634             {
2635               tpoint->handle = set_fast_tracepoint_jump (tpoint->address,
2636                                                          fjump,
2637                                                          fjump_size);
2638               tpoint->jump_pad = prev_ftpoint->jump_pad;
2639               tpoint->jump_pad_end = prev_ftpoint->jump_pad_end;
2640               tpoint->adjusted_insn_addr = prev_ftpoint->adjusted_insn_addr;
2641               tpoint->adjusted_insn_addr_end
2642                 = prev_ftpoint->adjusted_insn_addr_end;
2643             }
2644           else
2645             {
2646               CORE_ADDR jentry;
2647               int err = 0;
2648
2649               prev_ftpoint = NULL;
2650
2651               jentry = jump_entry = get_jump_space_head ();
2652
2653               /* Install the jump pad.  */
2654               err = install_fast_tracepoint_jump_pad
2655                 (tpoint->obj_addr_on_target,
2656                  tpoint->address,
2657                  ipa_sym_addrs.addr_gdb_collect,
2658                  ipa_sym_addrs.addr_collecting,
2659                  tpoint->orig_size,
2660                  &jentry,
2661                  fjump, &fjump_size,
2662                  &tpoint->adjusted_insn_addr,
2663                  &tpoint->adjusted_insn_addr_end);
2664
2665               /* Wire it in.  */
2666               if (!err)
2667                 tpoint->handle = set_fast_tracepoint_jump (tpoint->address,
2668                                                            fjump, fjump_size);
2669
2670               if (tpoint->handle != NULL)
2671                 {
2672                   tpoint->jump_pad = jump_entry;
2673                   tpoint->jump_pad_end = jentry;
2674
2675                   /* Pad to 8-byte alignment.  */
2676                   jentry = ((jentry + 7) & ~0x7);
2677                   claim_jump_space (jentry - jump_entry);
2678
2679                   /* So that we can handle multiple fast tracepoints
2680                      at the same address easily.  */
2681                   prev_ftpoint = tpoint;
2682                 }
2683             }
2684         }
2685
2686       /* Any failure in the inner loop is sufficient cause to give
2687          up.  */
2688       if (tpoint->handle == NULL)
2689         break;
2690     }
2691
2692   /* Any error in tracepoint insertion is unacceptable; better to
2693      address the problem now, than end up with a useless or misleading
2694      trace run.  */
2695   if (tpoint != NULL)
2696     {
2697       clear_installed_tracepoints ();
2698       if (*packet == '\0')
2699         write_enn (packet);
2700       unpause_all (1);
2701       return;
2702     }
2703
2704   stopping_tracepoint = NULL;
2705   trace_buffer_is_full = 0;
2706   expr_eval_result = expr_eval_no_error;
2707   error_tracepoint = NULL;
2708
2709   /* Tracing is now active, hits will now start being logged.  */
2710   tracing = 1;
2711
2712   if (in_process_agent_loaded ())
2713     {
2714       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
2715         fatal ("Error setting tracing variable in lib");
2716
2717       if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
2718                                        0))
2719         fatal ("Error clearing stopping_tracepoint variable in lib");
2720
2721       if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
2722         fatal ("Error clearing trace_buffer_is_full variable in lib");
2723
2724       stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
2725                                              stop_tracing_handler);
2726       if (stop_tracing_bkpt == NULL)
2727         error ("Error setting stop_tracing breakpoint");
2728
2729       flush_trace_buffer_bkpt
2730         = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
2731                              flush_trace_buffer_handler);
2732       if (flush_trace_buffer_bkpt == NULL)
2733         error ("Error setting flush_trace_buffer breakpoint");
2734     }
2735
2736   unpause_all (1);
2737
2738   write_ok (packet);
2739 }
2740
2741 /* End a tracing run, filling in a stop reason to report back to GDB,
2742    and removing the tracepoints from the code.  */
2743
2744 void
2745 stop_tracing (void)
2746 {
2747   if (!tracing)
2748     {
2749       trace_debug ("Tracing is already off, ignoring");
2750       return;
2751     }
2752
2753   trace_debug ("Stopping the trace");
2754
2755   /* Pause all threads before removing fast jumps from memory,
2756      breakpoints, and touching IPA state variables (inferior memory).
2757      Some thread may hit the internal tracing breakpoints, or be
2758      collecting this moment, but that's ok, we don't release the
2759      tpoint object's memory or the jump pads here (we only do that
2760      when we're sure we can move all threads out of the jump pads).
2761      We can't now, since we may be getting here due to the inferior
2762      agent calling us.  */
2763   pause_all (1);
2764   /* Since we're removing breakpoints, cancel breakpoint hits,
2765      possibly related to the breakpoints we're about to delete.  */
2766   cancel_breakpoints ();
2767
2768   /* Stop logging. Tracepoints can still be hit, but they will not be
2769      recorded.  */
2770   tracing = 0;
2771   if (in_process_agent_loaded ())
2772     {
2773       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
2774         fatal ("Error clearing tracing variable in lib");
2775     }
2776
2777   tracing_stop_reason = "t???";
2778   tracing_stop_tpnum = 0;
2779   if (stopping_tracepoint)
2780     {
2781       trace_debug ("Stopping the trace because "
2782                    "tracepoint %d was hit %ld times",
2783                    stopping_tracepoint->number,
2784                    stopping_tracepoint->pass_count);
2785       tracing_stop_reason = "tpasscount";
2786       tracing_stop_tpnum = stopping_tracepoint->number;
2787     }
2788   else if (trace_buffer_is_full)
2789     {
2790       trace_debug ("Stopping the trace because the trace buffer is full");
2791       tracing_stop_reason = "tfull";
2792     }
2793   else if (expr_eval_result != expr_eval_no_error)
2794     {
2795       trace_debug ("Stopping the trace because of an expression eval error");
2796       tracing_stop_reason = eval_result_names[expr_eval_result];
2797       tracing_stop_tpnum = error_tracepoint->number;
2798     }
2799 #ifndef IN_PROCESS_AGENT
2800   else if (!gdb_connected ())
2801     {
2802       trace_debug ("Stopping the trace because GDB disconnected");
2803       tracing_stop_reason = "tdisconnected";
2804     }
2805 #endif
2806   else
2807     {
2808       trace_debug ("Stopping the trace because of a tstop command");
2809       tracing_stop_reason = "tstop";
2810     }
2811
2812   stopping_tracepoint = NULL;
2813   error_tracepoint = NULL;
2814
2815   /* Clear out the tracepoints.  */
2816   clear_installed_tracepoints ();
2817
2818   if (in_process_agent_loaded ())
2819     {
2820       /* Pull in fast tracepoint trace frames from the inferior lib
2821          buffer into our buffer, even if our buffer is already full,
2822          because we want to present the full number of created frames
2823          in addition to what fit in the trace buffer.  */
2824       upload_fast_traceframes ();
2825     }
2826
2827   if (stop_tracing_bkpt != NULL)
2828     {
2829       delete_breakpoint (stop_tracing_bkpt);
2830       stop_tracing_bkpt = NULL;
2831     }
2832
2833   if (flush_trace_buffer_bkpt != NULL)
2834     {
2835       delete_breakpoint (flush_trace_buffer_bkpt);
2836       flush_trace_buffer_bkpt = NULL;
2837     }
2838
2839   unpause_all (1);
2840 }
2841
2842 static int
2843 stop_tracing_handler (CORE_ADDR addr)
2844 {
2845   trace_debug ("lib hit stop_tracing");
2846
2847   /* Don't actually handle it here.  When we stop tracing we remove
2848      breakpoints from the inferior, and that is not allowed in a
2849      breakpoint handler (as the caller is walking the breakpoint
2850      list).  */
2851   return 0;
2852 }
2853
2854 static int
2855 flush_trace_buffer_handler (CORE_ADDR addr)
2856 {
2857   trace_debug ("lib hit flush_trace_buffer");
2858   return 0;
2859 }
2860
2861 static void
2862 cmd_qtstop (char *packet)
2863 {
2864   stop_tracing ();
2865   write_ok (packet);
2866 }
2867
2868 static void
2869 cmd_qtdisconnected (char *own_buf)
2870 {
2871   ULONGEST setting;
2872   char *packet = own_buf;
2873
2874   packet += strlen ("QTDisconnected:");
2875
2876   unpack_varlen_hex (packet, &setting);
2877
2878   write_ok (own_buf);
2879
2880   disconnected_tracing = setting;
2881 }
2882
2883 static void
2884 cmd_qtframe (char *own_buf)
2885 {
2886   ULONGEST frame, pc, lo, hi, num;
2887   int tfnum, tpnum;
2888   struct traceframe *tframe;
2889   char *packet = own_buf;
2890
2891   packet += strlen ("QTFrame:");
2892
2893   if (strncmp (packet, "pc:", strlen ("pc:")) == 0)
2894     {
2895       packet += strlen ("pc:");
2896       packet = unpack_varlen_hex (packet, &pc);
2897       trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
2898       tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
2899     }
2900   else if (strncmp (packet, "range:", strlen ("range:")) == 0)
2901     {
2902       packet += strlen ("range:");
2903       packet = unpack_varlen_hex (packet, &lo);
2904       ++packet;
2905       packet = unpack_varlen_hex (packet, &hi);
2906       trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
2907                    paddress (lo), paddress (hi));
2908       tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
2909     }
2910   else if (strncmp (packet, "outside:", strlen ("outside:")) == 0)
2911     {
2912       packet += strlen ("outside:");
2913       packet = unpack_varlen_hex (packet, &lo);
2914       ++packet;
2915       packet = unpack_varlen_hex (packet, &hi);
2916       trace_debug ("Want to find next traceframe "
2917                    "outside the range 0x%s to 0x%s",
2918                    paddress (lo), paddress (hi));
2919       tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
2920     }
2921   else if (strncmp (packet, "tdp:", strlen ("tdp:")) == 0)
2922     {
2923       packet += strlen ("tdp:");
2924       packet = unpack_varlen_hex (packet, &num);
2925       tpnum = (int) num;
2926       trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
2927       tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
2928     }
2929   else
2930     {
2931       unpack_varlen_hex (packet, &frame);
2932       tfnum = (int) frame;
2933       if (tfnum == -1)
2934         {
2935           trace_debug ("Want to stop looking at traceframes");
2936           current_traceframe = -1;
2937           write_ok (own_buf);
2938           return;
2939         }
2940       trace_debug ("Want to look at traceframe %d", tfnum);
2941       tframe = find_traceframe (tfnum);
2942     }
2943
2944   if (tframe)
2945     {
2946       current_traceframe = tfnum;
2947       sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
2948     }
2949   else
2950     sprintf (own_buf, "F-1");
2951 }
2952
2953 static void
2954 cmd_qtstatus (char *packet)
2955 {
2956   char *stop_reason_rsp = NULL;
2957
2958   trace_debug ("Returning trace status as %d, stop reason %s",
2959                tracing, tracing_stop_reason);
2960
2961   if (in_process_agent_loaded ())
2962     {
2963       pause_all (1);
2964
2965       upload_fast_traceframes ();
2966
2967       unpause_all (1);
2968    }
2969
2970   stop_reason_rsp = (char *) tracing_stop_reason;
2971
2972   /* The user visible error string in terror needs to be hex encoded.
2973      We leave it as plain string in `tracepoint_stop_reason' to ease
2974      debugging.  */
2975   if (strncmp (stop_reason_rsp, "terror:", strlen ("terror:")) == 0)
2976     {
2977       const char *result_name;
2978       int hexstr_len;
2979       char *p;
2980
2981       result_name = stop_reason_rsp + strlen ("terror:");
2982       hexstr_len = strlen (result_name) * 2;
2983       p = stop_reason_rsp = alloca (strlen ("terror:") + hexstr_len + 1);
2984       strcpy (p, "terror:");
2985       p += strlen (p);
2986       convert_int_to_ascii ((gdb_byte *) result_name, p, strlen (result_name));
2987     }
2988
2989   sprintf (packet,
2990            "T%d;"
2991            "%s:%x;"
2992            "tframes:%x;tcreated:%x;"
2993            "tfree:%x;tsize:%s;"
2994            "circular:%d;"
2995            "disconn:%d",
2996            tracing ? 1 : 0,
2997            stop_reason_rsp, tracing_stop_tpnum,
2998            traceframe_count, traceframes_created,
2999            free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3000            circular_trace_buffer,
3001            disconnected_tracing);
3002 }
3003
3004 /* State variables to help return all the tracepoint bits.  */
3005 static struct tracepoint *cur_tpoint;
3006 static int cur_action;
3007 static int cur_step_action;
3008 static struct source_string *cur_source_string;
3009 static struct trace_state_variable *cur_tsv;
3010
3011 /* Compose a response that is an imitation of the syntax by which the
3012    tracepoint was originally downloaded.  */
3013
3014 static void
3015 response_tracepoint (char *packet, struct tracepoint *tpoint)
3016 {
3017   char *buf;
3018
3019   sprintf (packet, "T%x:%s:%c:%lx:%lx", tpoint->number,
3020            paddress (tpoint->address),
3021            (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3022            tpoint->pass_count);
3023   if (tpoint->type == fast_tracepoint)
3024     sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3025
3026   if (tpoint->cond)
3027     {
3028       buf = unparse_agent_expr (tpoint->cond);
3029       sprintf (packet + strlen (packet), ":X%x,%s",
3030                tpoint->cond->length, buf);
3031       free (buf);
3032     }
3033 }
3034
3035 /* Compose a response that is an imitation of the syntax by which the
3036    tracepoint action was originally downloaded (with the difference
3037    that due to the way we store the actions, this will output a packet
3038    per action, while GDB could have combined more than one action
3039    per-packet.  */
3040
3041 static void
3042 response_action (char *packet, struct tracepoint *tpoint,
3043                  char *taction, int step)
3044 {
3045   sprintf (packet, "%c%x:%s:%s",
3046            (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3047            taction);
3048 }
3049
3050 /* Compose a response that is an imitation of the syntax by which the
3051    tracepoint source piece was originally downloaded.  */
3052
3053 static void
3054 response_source (char *packet,
3055                  struct tracepoint *tpoint, struct source_string *src)
3056 {
3057   char *buf;
3058   int len;
3059
3060   len = strlen (src->str);
3061   buf = alloca (len * 2 + 1);
3062   convert_int_to_ascii ((gdb_byte *) src->str, buf, len);
3063
3064   sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3065            tpoint->number, paddress (tpoint->address),
3066            src->type, 0, len, buf);
3067 }
3068
3069 /* Return the first piece of tracepoint definition, and initialize the
3070    state machine that will iterate through all the tracepoint
3071    bits.  */
3072
3073 static void
3074 cmd_qtfp (char *packet)
3075 {
3076   trace_debug ("Returning first tracepoint definition piece");
3077
3078   cur_tpoint = tracepoints;
3079   cur_action = cur_step_action = -1;
3080   cur_source_string = NULL;
3081
3082   if (cur_tpoint)
3083     response_tracepoint (packet, cur_tpoint);
3084   else
3085     strcpy (packet, "l");
3086 }
3087
3088 /* Return additional pieces of tracepoint definition.  Each action and
3089    stepping action must go into its own packet, because of packet size
3090    limits, and so we use state variables to deliver one piece at a
3091    time.  */
3092
3093 static void
3094 cmd_qtsp (char *packet)
3095 {
3096   trace_debug ("Returning subsequent tracepoint definition piece");
3097
3098   if (!cur_tpoint)
3099     {
3100       /* This case would normally never occur, but be prepared for
3101          GDB misbehavior.  */
3102       strcpy (packet, "l");
3103     }
3104   else if (cur_action < cur_tpoint->numactions - 1)
3105     {
3106       ++cur_action;
3107       response_action (packet, cur_tpoint,
3108                        cur_tpoint->actions_str[cur_action], 0);
3109     }
3110   else if (cur_step_action < cur_tpoint->num_step_actions - 1)
3111     {
3112       ++cur_step_action;
3113       response_action (packet, cur_tpoint,
3114                        cur_tpoint->step_actions_str[cur_step_action], 1);
3115     }
3116   else if ((cur_source_string
3117             ? cur_source_string->next
3118             : cur_tpoint->source_strings))
3119     {
3120       if (cur_source_string)
3121         cur_source_string = cur_source_string->next;
3122       else
3123         cur_source_string = cur_tpoint->source_strings;
3124       response_source (packet, cur_tpoint, cur_source_string);
3125     }
3126   else
3127     {
3128       cur_tpoint = cur_tpoint->next;
3129       cur_action = cur_step_action = -1;
3130       cur_source_string = NULL;
3131       if (cur_tpoint)
3132         response_tracepoint (packet, cur_tpoint);
3133       else
3134         strcpy (packet, "l");
3135     }
3136 }
3137
3138 /* Compose a response that is an imitation of the syntax by which the
3139    trace state variable was originally downloaded.  */
3140
3141 static void
3142 response_tsv (char *packet, struct trace_state_variable *tsv)
3143 {
3144   char *buf = (char *) "";
3145   int namelen;
3146
3147   if (tsv->name)
3148     {
3149       namelen = strlen (tsv->name);
3150       buf = alloca (namelen * 2 + 1);
3151       convert_int_to_ascii ((gdb_byte *) tsv->name, buf, namelen);
3152     }
3153
3154   sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3155            tsv->getter ? 1 : 0, buf);
3156 }
3157
3158 /* Return the first trace state variable definition, and initialize
3159    the state machine that will iterate through all the tsv bits.  */
3160
3161 static void
3162 cmd_qtfv (char *packet)
3163 {
3164   trace_debug ("Returning first trace state variable definition");
3165
3166   cur_tsv = trace_state_variables;
3167
3168   if (cur_tsv)
3169     response_tsv (packet, cur_tsv);
3170   else
3171     strcpy (packet, "l");
3172 }
3173
3174 /* Return additional trace state variable definitions. */
3175
3176 static void
3177 cmd_qtsv (char *packet)
3178 {
3179   trace_debug ("Returning first trace state variable definition");
3180
3181   if (!cur_tpoint)
3182     {
3183       /* This case would normally never occur, but be prepared for
3184          GDB misbehavior.  */
3185       strcpy (packet, "l");
3186     }
3187   else if (cur_tsv)
3188     {
3189       cur_tsv = cur_tsv->next;
3190       if (cur_tsv)
3191         response_tsv (packet, cur_tsv);
3192       else
3193         strcpy (packet, "l");
3194     }
3195   else
3196     strcpy (packet, "l");
3197 }
3198
3199 /* Respond to qTBuffer packet with a block of raw data from the trace
3200    buffer.  GDB may ask for a lot, but we are allowed to reply with
3201    only as much as will fit within packet limits or whatever.  */
3202
3203 static void
3204 cmd_qtbuffer (char *own_buf)
3205 {
3206   ULONGEST offset, num, tot;
3207   unsigned char *tbp;
3208   char *packet = own_buf;
3209
3210   packet += strlen ("qTBuffer:");
3211
3212   packet = unpack_varlen_hex (packet, &offset);
3213   ++packet; /* skip a comma */
3214   packet = unpack_varlen_hex (packet, &num);
3215
3216   trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3217                (int) num, pulongest (offset));
3218
3219   tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3220
3221   /* If we're right at the end, reply specially that we're done.  */
3222   if (offset == tot)
3223     {
3224       strcpy (own_buf, "l");
3225       return;
3226     }
3227
3228   /* Object to any other out-of-bounds request.  */
3229   if (offset > tot)
3230     {
3231       write_enn (own_buf);
3232       return;
3233     }
3234
3235   /* Compute the pointer corresponding to the given offset, accounting
3236      for wraparound.  */
3237   tbp = trace_buffer_start + offset;
3238   if (tbp >= trace_buffer_wrap)
3239     tbp -= (trace_buffer_wrap - trace_buffer_lo);
3240
3241   /* Trim to the remaining bytes if we're close to the end.  */
3242   if (num > tot - offset)
3243     num = tot - offset;
3244
3245   /* Trim to available packet size.  */
3246   if (num >= (PBUFSIZ - 16) / 2 )
3247     num = (PBUFSIZ - 16) / 2;
3248
3249   convert_int_to_ascii (tbp, own_buf, num);
3250   own_buf[num] = '\0';
3251 }
3252
3253 static void
3254 cmd_bigqtbuffer (char *own_buf)
3255 {
3256   ULONGEST val;
3257   char *packet = own_buf;
3258
3259   packet += strlen ("QTBuffer:");
3260
3261   if (strncmp ("circular:", packet, strlen ("circular:")) == 0)
3262     {
3263       packet += strlen ("circular:");
3264       packet = unpack_varlen_hex (packet, &val);
3265       circular_trace_buffer = val;
3266       trace_debug ("Trace buffer is now %s",
3267                    circular_trace_buffer ? "circular" : "linear");
3268       write_ok (own_buf);
3269     }
3270   else
3271     write_enn (own_buf);
3272 }
3273
3274 int
3275 handle_tracepoint_general_set (char *packet)
3276 {
3277   if (strcmp ("QTinit", packet) == 0)
3278     {
3279       cmd_qtinit (packet);
3280       return 1;
3281     }
3282   else if (strncmp ("QTDP:", packet, strlen ("QTDP:")) == 0)
3283     {
3284       cmd_qtdp (packet);
3285       return 1;
3286     }
3287   else if (strncmp ("QTDPsrc:", packet, strlen ("QTDPsrc:")) == 0)
3288     {
3289       cmd_qtdpsrc (packet);
3290       return 1;
3291     }
3292   else if (strncmp ("QTDV:", packet, strlen ("QTDV:")) == 0)
3293     {
3294       cmd_qtdv (packet);
3295       return 1;
3296     }
3297   else if (strncmp ("QTro:", packet, strlen ("QTro:")) == 0)
3298     {
3299       cmd_qtro (packet);
3300       return 1;
3301     }
3302   else if (strcmp ("QTStart", packet) == 0)
3303     {
3304       cmd_qtstart (packet);
3305       return 1;
3306     }
3307   else if (strcmp ("QTStop", packet) == 0)
3308     {
3309       cmd_qtstop (packet);
3310       return 1;
3311     }
3312   else if (strncmp ("QTDisconnected:", packet,
3313                     strlen ("QTDisconnected:")) == 0)
3314     {
3315       cmd_qtdisconnected (packet);
3316       return 1;
3317     }
3318   else if (strncmp ("QTFrame:", packet, strlen ("QTFrame:")) == 0)
3319     {
3320       cmd_qtframe (packet);
3321       return 1;
3322     }
3323   else if (strncmp ("QTBuffer:", packet, strlen ("QTBuffer:")) == 0)
3324     {
3325       cmd_bigqtbuffer (packet);
3326       return 1;
3327     }
3328
3329   return 0;
3330 }
3331
3332 int
3333 handle_tracepoint_query (char *packet)
3334 {
3335   if (strcmp ("qTStatus", packet) == 0)
3336     {
3337       cmd_qtstatus (packet);
3338       return 1;
3339     }
3340   else if (strcmp ("qTfP", packet) == 0)
3341     {
3342       cmd_qtfp (packet);
3343       return 1;
3344     }
3345   else if (strcmp ("qTsP", packet) == 0)
3346     {
3347       cmd_qtsp (packet);
3348       return 1;
3349     }
3350   else if (strcmp ("qTfV", packet) == 0)
3351     {
3352       cmd_qtfv (packet);
3353       return 1;
3354     }
3355   else if (strcmp ("qTsV", packet) == 0)
3356     {
3357       cmd_qtsv (packet);
3358       return 1;
3359     }
3360   else if (strncmp ("qTV:", packet, strlen ("qTV:")) == 0)
3361     {
3362       cmd_qtv (packet);
3363       return 1;
3364     }
3365   else if (strncmp ("qTBuffer:", packet, strlen ("qTBuffer:")) == 0)
3366     {
3367       cmd_qtbuffer (packet);
3368       return 1;
3369     }
3370
3371   return 0;
3372 }
3373
3374 #endif
3375 #ifndef IN_PROCESS_AGENT
3376
3377 /* Call this when thread TINFO has hit the tracepoint defined by
3378    TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
3379    action.  This adds a while-stepping collecting state item to the
3380    threads' collecting state list, so that we can keep track of
3381    multiple simultaneous while-stepping actions being collected by the
3382    same thread.  This can happen in cases like:
3383
3384     ff0001  INSN1 <-- TP1, while-stepping 10 collect $regs
3385     ff0002  INSN2
3386     ff0003  INSN3 <-- TP2, collect $regs
3387     ff0004  INSN4 <-- TP3, while-stepping 10 collect $regs
3388     ff0005  INSN5
3389
3390    Notice that when instruction INSN5 is reached, the while-stepping
3391    actions of both TP1 and TP3 are still being collected, and that TP2
3392    had been collected meanwhile.  The whole range of ff0001-ff0005
3393    should be single-stepped, due to at least TP1's while-stepping
3394    action covering the whole range.  */
3395
3396 static void
3397 add_while_stepping_state (struct thread_info *tinfo,
3398                           int tp_number, CORE_ADDR tp_address)
3399 {
3400   struct wstep_state *wstep;
3401
3402   wstep = xmalloc (sizeof (*wstep));
3403   wstep->next = tinfo->while_stepping;
3404
3405   wstep->tp_number = tp_number;
3406   wstep->tp_address = tp_address;
3407   wstep->current_step = 0;
3408
3409   tinfo->while_stepping = wstep;
3410 }
3411
3412 /* Release the while-stepping collecting state WSTEP.  */
3413
3414 static void
3415 release_while_stepping_state (struct wstep_state *wstep)
3416 {
3417   free (wstep);
3418 }
3419
3420 /* Release all while-stepping collecting states currently associated
3421    with thread TINFO.  */
3422
3423 void
3424 release_while_stepping_state_list (struct thread_info *tinfo)
3425 {
3426   struct wstep_state *head;
3427
3428   while (tinfo->while_stepping)
3429     {
3430       head = tinfo->while_stepping;
3431       tinfo->while_stepping = head->next;
3432       release_while_stepping_state (head);
3433     }
3434 }
3435
3436 /* If TINFO was handling a 'while-stepping' action, the step has
3437    finished, so collect any step data needed, and check if any more
3438    steps are required.  Return true if the thread was indeed
3439    collecting tracepoint data, false otherwise.  */
3440
3441 int
3442 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
3443 {
3444   struct tracepoint *tpoint;
3445   struct wstep_state *wstep;
3446   struct wstep_state **wstep_link;
3447   struct trap_tracepoint_ctx ctx;
3448
3449   /* Pull in fast tracepoint trace frames from the inferior lib buffer into
3450      our buffer.  */
3451   if (in_process_agent_loaded ())
3452     upload_fast_traceframes ();
3453
3454   /* Check if we were indeed collecting data for one of more
3455      tracepoints with a 'while-stepping' count.  */
3456   if (tinfo->while_stepping == NULL)
3457     return 0;
3458
3459   if (!tracing)
3460     {
3461       /* We're not even tracing anymore.  Stop this thread from
3462          collecting.  */
3463       release_while_stepping_state_list (tinfo);
3464
3465       /* The thread had stopped due to a single-step request indeed
3466          explained by a tracepoint.  */
3467       return 1;
3468     }
3469
3470   wstep = tinfo->while_stepping;
3471   wstep_link = &tinfo->while_stepping;
3472
3473   trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
3474                target_pid_to_str (tinfo->entry.id),
3475                wstep->tp_number, paddress (wstep->tp_address));
3476
3477   ctx.base.type = trap_tracepoint;
3478   ctx.regcache = get_thread_regcache (tinfo, 1);
3479
3480   while (wstep != NULL)
3481     {
3482       tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
3483       if (tpoint == NULL)
3484         {
3485           trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
3486                        wstep->tp_number, paddress (wstep->tp_address),
3487                        target_pid_to_str (tinfo->entry.id));
3488
3489           /* Unlink.  */
3490           *wstep_link = wstep->next;
3491           release_while_stepping_state (wstep);
3492           continue;
3493         }
3494
3495       /* We've just finished one step.  */
3496       ++wstep->current_step;
3497
3498       /* Collect data.  */
3499       collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
3500                             stop_pc, tpoint, wstep->current_step);
3501
3502       if (wstep->current_step >= tpoint->step_count)
3503         {
3504           /* The requested numbers of steps have occurred.  */
3505           trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
3506                        target_pid_to_str (tinfo->entry.id),
3507                        wstep->tp_number, paddress (wstep->tp_address));
3508
3509           /* Unlink the wstep.  */
3510           *wstep_link = wstep->next;
3511           release_while_stepping_state (wstep);
3512           wstep = *wstep_link;
3513
3514           /* Only check the hit count now, which ensure that we do all
3515              our stepping before stopping the run.  */
3516           if (tpoint->pass_count > 0
3517               && tpoint->hit_count >= tpoint->pass_count
3518               && stopping_tracepoint == NULL)
3519             stopping_tracepoint = tpoint;
3520         }
3521       else
3522         {
3523           /* Keep single-stepping until the requested numbers of steps
3524              have occurred.  */
3525           wstep_link = &wstep->next;
3526           wstep = *wstep_link;
3527         }
3528
3529       if (stopping_tracepoint
3530           || trace_buffer_is_full
3531           || expr_eval_result != expr_eval_no_error)
3532         {
3533           stop_tracing ();
3534           break;
3535         }
3536     }
3537
3538   return 1;
3539 }
3540
3541 /* Handle any internal tracing control breakpoint hits.  That means,
3542    pull traceframes from the IPA to our buffer, and syncing both
3543    tracing agents when the IPA's tracing stops for some reason.  */
3544
3545 int
3546 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
3547 {
3548   /* Pull in fast tracepoint trace frames from the inferior in-process
3549      agent's buffer into our buffer.  */
3550
3551   if (!in_process_agent_loaded ())
3552     return 0;
3553
3554   upload_fast_traceframes ();
3555
3556   /* Check if the in-process agent had decided we should stop
3557      tracing.  */
3558   if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
3559     {
3560       int ipa_trace_buffer_is_full;
3561       CORE_ADDR ipa_stopping_tracepoint;
3562       int ipa_expr_eval_result;
3563       CORE_ADDR ipa_error_tracepoint;
3564
3565       trace_debug ("lib stopped at stop_tracing");
3566
3567       read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
3568                              &ipa_trace_buffer_is_full);
3569
3570       read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3571                                   &ipa_stopping_tracepoint);
3572       write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
3573
3574       read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
3575                                   &ipa_error_tracepoint);
3576       write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
3577
3578       read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
3579                              &ipa_expr_eval_result);
3580       write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
3581
3582       trace_debug ("lib: trace_buffer_is_full: %d, "
3583                    "stopping_tracepoint: %s, "
3584                    "ipa_expr_eval_result: %d, "
3585                    "error_tracepoint: %s, ",
3586                    ipa_trace_buffer_is_full,
3587                    paddress (ipa_stopping_tracepoint),
3588                    ipa_expr_eval_result,
3589                    paddress (ipa_error_tracepoint));
3590
3591       if (debug_threads)
3592         {
3593           if (ipa_trace_buffer_is_full)
3594             trace_debug ("lib stopped due to full buffer.");
3595           if (ipa_stopping_tracepoint)
3596             trace_debug ("lib stopped due to tpoint");
3597           if (ipa_stopping_tracepoint)
3598             trace_debug ("lib stopped due to error");
3599         }
3600
3601       if (ipa_stopping_tracepoint != 0)
3602         {
3603           stopping_tracepoint
3604             = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
3605         }
3606       else if (ipa_expr_eval_result != expr_eval_no_error)
3607         {
3608           expr_eval_result = ipa_expr_eval_result;
3609           error_tracepoint
3610             = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
3611         }
3612       stop_tracing ();
3613       return 1;
3614     }
3615   else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
3616     {
3617       trace_debug ("lib stopped at flush_trace_buffer");
3618       return 1;
3619     }
3620
3621   return 0;
3622 }
3623
3624 /* Return true if TINFO just hit a tracepoint.  Collect data if
3625    so.  */
3626
3627 int
3628 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
3629 {
3630   struct tracepoint *tpoint;
3631   int ret = 0;
3632   struct trap_tracepoint_ctx ctx;
3633
3634   /* Not tracing, don't handle.  */
3635   if (!tracing)
3636     return 0;
3637
3638   ctx.base.type = trap_tracepoint;
3639   ctx.regcache = get_thread_regcache (tinfo, 1);
3640
3641   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3642     {
3643       /* Note that we collect fast tracepoints here as well.  We'll
3644          step over the fast tracepoint jump later, which avoids the
3645          double collect.  */
3646       if (tpoint->enabled && stop_pc == tpoint->address)
3647         {
3648           trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
3649                        target_pid_to_str (tinfo->entry.id),
3650                        tpoint->number, paddress (tpoint->address));
3651
3652           /* Test the condition if present, and collect if true.  */
3653           if (!tpoint->cond
3654               || (condition_true_at_tracepoint
3655                   ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
3656             collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
3657                                         stop_pc, tpoint);
3658
3659           if (stopping_tracepoint
3660               || trace_buffer_is_full
3661               || expr_eval_result != expr_eval_no_error)
3662             {
3663               stop_tracing ();
3664             }
3665           /* If the tracepoint had a 'while-stepping' action, then set
3666              the thread to collect this tracepoint on the following
3667              single-steps.  */
3668           else if (tpoint->step_count > 0)
3669             {
3670               add_while_stepping_state (tinfo,
3671                                         tpoint->number, tpoint->address);
3672             }
3673
3674           ret = 1;
3675         }
3676     }
3677
3678   return ret;
3679 }
3680
3681 #endif
3682
3683 /* Create a trace frame for the hit of the given tracepoint in the
3684    given thread.  */
3685
3686 static void
3687 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
3688                             struct tracepoint *tpoint)
3689 {
3690   struct traceframe *tframe;
3691   int acti;
3692
3693   /* Only count it as a hit when we actually collect data.  */
3694   tpoint->hit_count++;
3695
3696   /* If we've exceeded a defined pass count, record the event for
3697      later, and finish the collection for this hit.  This test is only
3698      for nonstepping tracepoints, stepping tracepoints test at the end
3699      of their while-stepping loop.  */
3700   if (tpoint->pass_count > 0
3701       && tpoint->hit_count >= tpoint->pass_count
3702       && tpoint->step_count == 0
3703       && stopping_tracepoint == NULL)
3704     stopping_tracepoint = tpoint;
3705
3706   trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %ld",
3707                tpoint->number, paddress (tpoint->address), tpoint->hit_count);
3708
3709   tframe = add_traceframe (tpoint);
3710
3711   if (tframe)
3712     {
3713       for (acti = 0; acti < tpoint->numactions; ++acti)
3714         {
3715 #ifndef IN_PROCESS_AGENT
3716           trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
3717                        tpoint->number, paddress (tpoint->address),
3718                        tpoint->actions_str[acti]);
3719 #endif
3720
3721           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
3722                                    tpoint->actions[acti]);
3723         }
3724
3725       finish_traceframe (tframe);
3726     }
3727
3728   if (tframe == NULL && tracing)
3729     trace_buffer_is_full = 1;
3730 }
3731
3732 #ifndef IN_PROCESS_AGENT
3733
3734 static void
3735 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
3736                       CORE_ADDR stop_pc,
3737                       struct tracepoint *tpoint, int current_step)
3738 {
3739   struct traceframe *tframe;
3740   int acti;
3741
3742   trace_debug ("Making new step traceframe for "
3743                "tracepoint %d at 0x%s, step %d of %ld, hit %ld",
3744                tpoint->number, paddress (tpoint->address),
3745                current_step, tpoint->step_count,
3746                tpoint->hit_count);
3747
3748   tframe = add_traceframe (tpoint);
3749
3750   if (tframe)
3751     {
3752       for (acti = 0; acti < tpoint->num_step_actions; ++acti)
3753         {
3754           trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
3755                        tpoint->number, paddress (tpoint->address),
3756                        tpoint->step_actions_str[acti]);
3757
3758           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
3759                                    tpoint->step_actions[acti]);
3760         }
3761
3762       finish_traceframe (tframe);
3763     }
3764
3765   if (tframe == NULL && tracing)
3766     trace_buffer_is_full = 1;
3767 }
3768
3769 #endif
3770
3771 static struct regcache *
3772 get_context_regcache (struct tracepoint_hit_ctx *ctx)
3773 {
3774   struct regcache *regcache = NULL;
3775
3776 #ifdef IN_PROCESS_AGENT
3777   if (ctx->type == fast_tracepoint)
3778     {
3779       struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
3780       if (!fctx->regcache_initted)
3781         {
3782           fctx->regcache_initted = 1;
3783           init_register_cache (&fctx->regcache, fctx->regspace);
3784           supply_regblock (&fctx->regcache, NULL);
3785           supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
3786         }
3787       regcache = &fctx->regcache;
3788     }
3789 #else
3790   if (ctx->type == trap_tracepoint)
3791     {
3792       struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
3793       regcache = tctx->regcache;
3794     }
3795 #endif
3796
3797   gdb_assert (regcache != NULL);
3798
3799   return regcache;
3800 }
3801
3802 static void
3803 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
3804                          CORE_ADDR stop_pc,
3805                          struct tracepoint *tpoint,
3806                          struct traceframe *tframe,
3807                          struct tracepoint_action *taction)
3808 {
3809   enum eval_result_type err;
3810
3811   switch (taction->type)
3812     {
3813     case 'M':
3814       {
3815         struct collect_memory_action *maction;
3816
3817         maction = (struct collect_memory_action *) taction;
3818
3819         trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
3820                      pulongest (maction->len),
3821                      paddress (maction->addr), maction->basereg);
3822         /* (should use basereg) */
3823         agent_mem_read (tframe, NULL,
3824                         (CORE_ADDR) maction->addr, maction->len);
3825         break;
3826       }
3827     case 'R':
3828       {
3829         struct collect_registers_action *raction;
3830
3831         unsigned char *regspace;
3832         struct regcache tregcache;
3833         struct regcache *context_regcache;
3834
3835         raction = (struct collect_registers_action *) taction;
3836
3837         trace_debug ("Want to collect registers");
3838
3839         /* Collect all registers for now.  */
3840         regspace = add_traceframe_block (tframe,
3841                                          1 + register_cache_size ());
3842         if (regspace == NULL)
3843           {
3844             trace_debug ("Trace buffer block allocation failed, skipping");
3845             break;
3846           }
3847         /* Identify a register block.  */
3848         *regspace = 'R';
3849
3850         context_regcache = get_context_regcache (ctx);
3851
3852         /* Wrap the regblock in a register cache (in the stack, we
3853            don't want to malloc here).  */
3854         init_register_cache (&tregcache, regspace + 1);
3855
3856         /* Copy the register data to the regblock.  */
3857         regcache_cpy (&tregcache, context_regcache);
3858
3859 #ifndef IN_PROCESS_AGENT
3860         /* On some platforms, trap-based tracepoints will have the PC
3861            pointing to the next instruction after the trap, but we
3862            don't want the user or GDB trying to guess whether the
3863            saved PC needs adjusting; so always record the adjusted
3864            stop_pc.  Note that we can't use tpoint->address instead,
3865            since it will be wrong for while-stepping actions.  This
3866            adjustment is a nop for fast tracepoints collected from the
3867            in-process lib (but not if GDBserver is collecting one
3868            preemptively), since the PC had already been adjusted to
3869            contain the tracepoint's address by the jump pad.  */
3870         trace_debug ("Storing stop pc (0x%s) in regblock",
3871                      paddress (tpoint->address));
3872
3873         /* This changes the regblock, not the thread's
3874            regcache.  */
3875         regcache_write_pc (&tregcache, stop_pc);
3876 #endif
3877       }
3878       break;
3879     case 'X':
3880       {
3881         struct eval_expr_action *eaction;
3882
3883         eaction = (struct eval_expr_action *) taction;
3884
3885         trace_debug ("Want to evaluate expression");
3886
3887         err = eval_agent_expr (ctx, tframe, eaction->expr, NULL);
3888
3889         if (err != expr_eval_no_error)
3890           {
3891             record_tracepoint_error (tpoint, "action expression", err);
3892             return;
3893           }
3894       }
3895       break;
3896     default:
3897       trace_debug ("unknown trace action '%c', ignoring", taction->type);
3898       break;
3899     }
3900 }
3901
3902 static int
3903 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
3904                               struct tracepoint *tpoint)
3905 {
3906   ULONGEST value = 0;
3907   enum eval_result_type err;
3908
3909   err = eval_agent_expr (ctx, NULL, tpoint->cond, &value);
3910
3911   if (err != expr_eval_no_error)
3912     {
3913       record_tracepoint_error (tpoint, "condition", err);
3914       /* The error case must return false.  */
3915       return 0;
3916     }
3917
3918   trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
3919                tpoint->number, paddress (tpoint->address),
3920                pulongest (value));
3921   return (value ? 1 : 0);
3922 }
3923
3924 #ifndef IN_PROCESS_AGENT
3925
3926 /* The packet form of an agent expression consists of an 'X', number
3927    of bytes in expression, a comma, and then the bytes.  */
3928
3929 static struct agent_expr *
3930 parse_agent_expr (char **actparm)
3931 {
3932   char *act = *actparm;
3933   ULONGEST xlen;
3934   struct agent_expr *aexpr;
3935
3936   ++act;  /* skip the X */
3937   act = unpack_varlen_hex (act, &xlen);
3938   ++act;  /* skip a comma */
3939   aexpr = xmalloc (sizeof (struct agent_expr));
3940   aexpr->length = xlen;
3941   aexpr->bytes = xmalloc (xlen);
3942   convert_ascii_to_int (act, aexpr->bytes, xlen);
3943   *actparm = act + (xlen * 2);
3944   return aexpr;
3945 }
3946
3947 /* Convert the bytes of an agent expression back into hex digits, so
3948    they can be printed or uploaded.  This allocates the buffer,
3949    callers should free when they are done with it.  */
3950
3951 static char *
3952 unparse_agent_expr (struct agent_expr *aexpr)
3953 {
3954   char *rslt;
3955
3956   rslt = xmalloc (2 * aexpr->length + 1);
3957   convert_int_to_ascii (aexpr->bytes, rslt, aexpr->length);
3958   return rslt;
3959 }
3960
3961 #endif
3962
3963 /* The agent expression evaluator, as specified by the GDB docs. It
3964    returns 0 if everything went OK, and a nonzero error code
3965    otherwise.  */
3966
3967 static enum eval_result_type
3968 eval_agent_expr (struct tracepoint_hit_ctx *ctx,
3969                  struct traceframe *tframe,
3970                  struct agent_expr *aexpr,
3971                  ULONGEST *rslt)
3972 {
3973   int pc = 0;
3974 #define STACK_MAX 100
3975   ULONGEST stack[STACK_MAX], top;
3976   int sp = 0;
3977   unsigned char op;
3978   int arg;
3979
3980   /* This union is a convenient way to convert representations.  For
3981      now, assume a standard architecture where the hardware integer
3982      types have 8, 16, 32, 64 bit types.  A more robust solution would
3983      be to import stdint.h from gnulib.  */
3984   union
3985   {
3986     union
3987     {
3988       unsigned char bytes[1];
3989       unsigned char val;
3990     } u8;
3991     union
3992     {
3993       unsigned char bytes[2];
3994       unsigned short val;
3995     } u16;
3996     union
3997     {
3998       unsigned char bytes[4];
3999       unsigned int val;
4000     } u32;
4001     union
4002     {
4003       unsigned char bytes[8];
4004       ULONGEST val;
4005     } u64;
4006   } cnv;
4007
4008   if (aexpr->length == 0)
4009     {
4010       trace_debug ("empty agent expression");
4011       return expr_eval_empty_expression;
4012     }
4013
4014   /* Cache the stack top in its own variable. Much of the time we can
4015      operate on this variable, rather than dinking with the stack. It
4016      needs to be copied to the stack when sp changes.  */
4017   top = 0;
4018
4019   while (1)
4020     {
4021       op = aexpr->bytes[pc++];
4022
4023       trace_debug ("About to interpret byte 0x%x", op);
4024
4025       switch (op)
4026         {
4027         case gdb_agent_op_add:
4028           top += stack[--sp];
4029           break;
4030
4031         case gdb_agent_op_sub:
4032           top = stack[--sp] - top;
4033           break;
4034
4035         case gdb_agent_op_mul:
4036           top *= stack[--sp];
4037           break;
4038
4039         case gdb_agent_op_div_signed:
4040           if (top == 0)
4041             {
4042               trace_debug ("Attempted to divide by zero");
4043               return expr_eval_divide_by_zero;
4044             }
4045           top = ((LONGEST) stack[--sp]) / ((LONGEST) top);
4046           break;
4047
4048         case gdb_agent_op_div_unsigned:
4049           if (top == 0)
4050             {
4051               trace_debug ("Attempted to divide by zero");
4052               return expr_eval_divide_by_zero;
4053             }
4054           top = stack[--sp] / top;
4055           break;
4056
4057         case gdb_agent_op_rem_signed:
4058           if (top == 0)
4059             {
4060               trace_debug ("Attempted to divide by zero");
4061               return expr_eval_divide_by_zero;
4062             }
4063           top = ((LONGEST) stack[--sp]) % ((LONGEST) top);
4064           break;
4065
4066         case gdb_agent_op_rem_unsigned:
4067           if (top == 0)
4068             {
4069               trace_debug ("Attempted to divide by zero");
4070               return expr_eval_divide_by_zero;
4071             }
4072           top = stack[--sp] % top;
4073           break;
4074
4075         case gdb_agent_op_lsh:
4076           top = stack[--sp] << top;
4077           break;
4078
4079         case gdb_agent_op_rsh_signed:
4080           top = ((LONGEST) stack[--sp]) >> top;
4081           break;
4082
4083         case gdb_agent_op_rsh_unsigned:
4084           top = stack[--sp] >> top;
4085           break;
4086
4087         case gdb_agent_op_trace:
4088           agent_mem_read (tframe,
4089                           NULL, (CORE_ADDR) stack[--sp], (ULONGEST) top);
4090           if (--sp >= 0)
4091             top = stack[sp];
4092           break;
4093
4094         case gdb_agent_op_trace_quick:
4095           arg = aexpr->bytes[pc++];
4096           agent_mem_read (tframe, NULL, (CORE_ADDR) top, (ULONGEST) arg);
4097           break;
4098
4099         case gdb_agent_op_log_not:
4100           top = !top;
4101           break;
4102
4103         case gdb_agent_op_bit_and:
4104           top &= stack[--sp];
4105           break;
4106
4107         case gdb_agent_op_bit_or:
4108           top |= stack[--sp];
4109           break;
4110
4111         case gdb_agent_op_bit_xor:
4112           top ^= stack[--sp];
4113           break;
4114
4115         case gdb_agent_op_bit_not:
4116           top = ~top;
4117           break;
4118
4119         case gdb_agent_op_equal:
4120           top = (stack[--sp] == top);
4121           break;
4122
4123         case gdb_agent_op_less_signed:
4124           top = (((LONGEST) stack[--sp]) < ((LONGEST) top));
4125           break;
4126
4127         case gdb_agent_op_less_unsigned:
4128           top = (stack[--sp] < top);
4129           break;
4130
4131         case gdb_agent_op_ext:
4132           arg = aexpr->bytes[pc++];
4133           if (arg < (sizeof (LONGEST) * 8))
4134             {
4135               LONGEST mask = 1 << (arg - 1);
4136               top &= ((LONGEST) 1 << arg) - 1;
4137               top = (top ^ mask) - mask;
4138             }
4139           break;
4140
4141         case gdb_agent_op_ref8:
4142           agent_mem_read (tframe, cnv.u8.bytes, (CORE_ADDR) top, 1);
4143           top = cnv.u8.val;
4144           break;
4145
4146         case gdb_agent_op_ref16:
4147           agent_mem_read (tframe, cnv.u16.bytes, (CORE_ADDR) top, 2);
4148           top = cnv.u16.val;
4149           break;
4150
4151         case gdb_agent_op_ref32:
4152           agent_mem_read (tframe, cnv.u32.bytes, (CORE_ADDR) top, 4);
4153           top = cnv.u32.val;
4154           break;
4155
4156         case gdb_agent_op_ref64:
4157           agent_mem_read (tframe, cnv.u64.bytes, (CORE_ADDR) top, 8);
4158           top = cnv.u64.val;
4159           break;
4160
4161         case gdb_agent_op_if_goto:
4162           if (top)
4163             pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
4164           else
4165             pc += 2;
4166           if (--sp >= 0)
4167             top = stack[sp];
4168           break;
4169
4170         case gdb_agent_op_goto:
4171           pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
4172           break;
4173
4174         case gdb_agent_op_const8:
4175           /* Flush the cached stack top.  */
4176           stack[sp++] = top;
4177           top = aexpr->bytes[pc++];
4178           break;
4179
4180         case gdb_agent_op_const16:
4181           /* Flush the cached stack top.  */
4182           stack[sp++] = top;
4183           top = aexpr->bytes[pc++];
4184           top = (top << 8) + aexpr->bytes[pc++];
4185           break;
4186
4187         case gdb_agent_op_const32:
4188           /* Flush the cached stack top.  */
4189           stack[sp++] = top;
4190           top = aexpr->bytes[pc++];
4191           top = (top << 8) + aexpr->bytes[pc++];
4192           top = (top << 8) + aexpr->bytes[pc++];
4193           top = (top << 8) + aexpr->bytes[pc++];
4194           break;
4195
4196         case gdb_agent_op_const64:
4197           /* Flush the cached stack top.  */
4198           stack[sp++] = top;
4199           top = aexpr->bytes[pc++];
4200           top = (top << 8) + aexpr->bytes[pc++];
4201           top = (top << 8) + aexpr->bytes[pc++];
4202           top = (top << 8) + aexpr->bytes[pc++];
4203           top = (top << 8) + aexpr->bytes[pc++];
4204           top = (top << 8) + aexpr->bytes[pc++];
4205           top = (top << 8) + aexpr->bytes[pc++];
4206           top = (top << 8) + aexpr->bytes[pc++];
4207           break;
4208
4209         case gdb_agent_op_reg:
4210           /* Flush the cached stack top.  */
4211           stack[sp++] = top;
4212           arg = aexpr->bytes[pc++];
4213           arg = (arg << 8) + aexpr->bytes[pc++];
4214           {
4215             int regnum = arg;
4216             struct regcache *regcache;
4217
4218             regcache = get_context_regcache (ctx);
4219
4220             switch (register_size (regnum))
4221               {
4222               case 8:
4223                 collect_register (regcache, regnum, cnv.u64.bytes);
4224                 top = cnv.u64.val;
4225                 break;
4226               case 4:
4227                 collect_register (regcache, regnum, cnv.u32.bytes);
4228                 top = cnv.u32.val;
4229                 break;
4230               case 2:
4231                 collect_register (regcache, regnum, cnv.u16.bytes);
4232                 top = cnv.u16.val;
4233                 break;
4234               case 1:
4235                 collect_register (regcache, regnum, cnv.u8.bytes);
4236                 top = cnv.u8.val;
4237                 break;
4238               default:
4239                 internal_error (__FILE__, __LINE__,
4240                                 "unhandled register size");
4241               }
4242           }
4243           break;
4244
4245         case gdb_agent_op_end:
4246           trace_debug ("At end of expression, sp=%d, stack top cache=0x%s",
4247                        sp, pulongest (top));
4248           if (rslt)
4249             {
4250               if (sp <= 0)
4251                 {
4252                   /* This should be an error */
4253                   trace_debug ("Stack is empty, nothing to return");
4254                   return expr_eval_empty_stack;
4255                 }
4256               *rslt = top;
4257             }
4258           return expr_eval_no_error;
4259
4260         case gdb_agent_op_dup:
4261           stack[sp++] = top;
4262           break;
4263
4264         case gdb_agent_op_pop:
4265           if (--sp >= 0)
4266             top = stack[sp];
4267           break;
4268
4269         case gdb_agent_op_zero_ext:
4270           arg = aexpr->bytes[pc++];
4271           if (arg < (sizeof (LONGEST) * 8))
4272             top &= ((LONGEST) 1 << arg) - 1;
4273           break;
4274
4275         case gdb_agent_op_swap:
4276           /* Interchange top two stack elements, making sure top gets
4277              copied back onto stack.  */
4278           stack[sp] = top;
4279           top = stack[sp - 1];
4280           stack[sp - 1] = stack[sp];
4281           break;
4282
4283         case gdb_agent_op_getv:
4284           /* Flush the cached stack top.  */
4285           stack[sp++] = top;
4286           arg = aexpr->bytes[pc++];
4287           arg = (arg << 8) + aexpr->bytes[pc++];
4288           top = get_trace_state_variable_value (arg);
4289           break;
4290
4291         case gdb_agent_op_setv:
4292           arg = aexpr->bytes[pc++];
4293           arg = (arg << 8) + aexpr->bytes[pc++];
4294           set_trace_state_variable_value (arg, top);
4295           /* Note that we leave the value on the stack, for the
4296              benefit of later/enclosing expressions.  */
4297           break;
4298
4299         case gdb_agent_op_tracev:
4300           arg = aexpr->bytes[pc++];
4301           arg = (arg << 8) + aexpr->bytes[pc++];
4302           agent_tsv_read (tframe, arg);
4303           break;
4304
4305           /* GDB never (currently) generates any of these ops.  */
4306         case gdb_agent_op_float:
4307         case gdb_agent_op_ref_float:
4308         case gdb_agent_op_ref_double:
4309         case gdb_agent_op_ref_long_double:
4310         case gdb_agent_op_l_to_d:
4311         case gdb_agent_op_d_to_l:
4312         case gdb_agent_op_trace16:
4313           trace_debug ("Agent expression op 0x%x valid, but not handled",
4314                        op);
4315           /* If ever GDB generates any of these, we don't have the
4316              option of ignoring.  */
4317           return 1;
4318
4319         default:
4320           trace_debug ("Agent expression op 0x%x not recognized", op);
4321           /* Don't struggle on, things will just get worse.  */
4322           return expr_eval_unrecognized_opcode;
4323         }
4324
4325       /* Check for stack badness.  */
4326       if (sp >= (STACK_MAX - 1))
4327         {
4328           trace_debug ("Expression stack overflow");
4329           return expr_eval_stack_overflow;
4330         }
4331
4332       if (sp < 0)
4333         {
4334           trace_debug ("Expression stack underflow");
4335           return expr_eval_stack_underflow;
4336         }
4337
4338       trace_debug ("Op %s -> sp=%d, top=0x%s",
4339                    gdb_agent_op_names[op], sp, pulongest (top));
4340     }
4341 }
4342
4343 /* Do memory copies for bytecodes.  */
4344 /* Do the recording of memory blocks for actions and bytecodes.  */
4345
4346 static int
4347 agent_mem_read (struct traceframe *tframe,
4348                 unsigned char *to, CORE_ADDR from, ULONGEST len)
4349 {
4350   unsigned char *mspace;
4351   ULONGEST remaining = len;
4352   unsigned short blocklen;
4353
4354   /* If a 'to' buffer is specified, use it.  */
4355   if (to != NULL)
4356     {
4357       read_inferior_memory (from, to, len);
4358       return 0;
4359     }
4360
4361   /* Otherwise, create a new memory block in the trace buffer.  */
4362   while (remaining > 0)
4363     {
4364       size_t sp;
4365
4366       blocklen = (remaining > 65535 ? 65535 : remaining);
4367       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4368       mspace = add_traceframe_block (tframe, sp);
4369       if (mspace == NULL)
4370         return 1;
4371       /* Identify block as a memory block.  */
4372       *mspace = 'M';
4373       ++mspace;
4374       /* Record address and size.  */
4375       memcpy (mspace, &from, sizeof (from));
4376       mspace += sizeof (from);
4377       memcpy (mspace, &blocklen, sizeof (blocklen));
4378       mspace += sizeof (blocklen);
4379       /* Record the memory block proper.  */
4380       read_inferior_memory (from, mspace, blocklen);
4381       trace_debug ("%d bytes recorded", blocklen);
4382       remaining -= blocklen;
4383       from += blocklen;
4384     }
4385   return 0;
4386 }
4387
4388 /* Record the value of a trace state variable.  */
4389
4390 static int
4391 agent_tsv_read (struct traceframe *tframe, int n)
4392 {
4393   unsigned char *vspace;
4394   LONGEST val;
4395
4396   vspace = add_traceframe_block (tframe,
4397                                  1 + sizeof (n) + sizeof (LONGEST));
4398   if (vspace == NULL)
4399     return 1;
4400   /* Identify block as a variable.  */
4401   *vspace = 'V';
4402   /* Record variable's number and value.  */
4403   memcpy (vspace + 1, &n, sizeof (n));
4404   val = get_trace_state_variable_value (n);
4405   memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
4406   trace_debug ("Variable %d recorded", n);
4407   return 0;
4408 }
4409
4410 #ifndef IN_PROCESS_AGENT
4411
4412 static unsigned char *
4413 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
4414                             int tfnum, char type_wanted)
4415 {
4416   unsigned char *dataptr;
4417
4418   if (datasize == 0)
4419     {
4420       trace_debug ("traceframe %d has no data", tfnum);
4421       return NULL;
4422     }
4423
4424   /* Iterate through a traceframe's blocks, looking for a block of the
4425      requested type.  */
4426   for (dataptr = database;
4427        dataptr < database + datasize;
4428        /* nothing */)
4429     {
4430       char blocktype;
4431       unsigned short mlen;
4432
4433       if (dataptr == trace_buffer_wrap)
4434         {
4435           /* Adjust to reflect wrapping part of the frame around to
4436              the beginning.  */
4437           datasize = dataptr - database;
4438           dataptr = database = trace_buffer_lo;
4439         }
4440       blocktype = *dataptr++;
4441
4442       if (type_wanted == blocktype)
4443         return dataptr;
4444
4445       switch (blocktype)
4446         {
4447         case 'R':
4448           /* Skip over the registers block.  */
4449           dataptr += register_cache_size ();
4450           break;
4451         case 'M':
4452           /* Skip over the memory block.  */
4453           dataptr += sizeof (CORE_ADDR);
4454           memcpy (&mlen, dataptr, sizeof (mlen));
4455           dataptr += (sizeof (mlen) + mlen);
4456           break;
4457         case 'V':
4458           /* Skip over the TSV block.  */
4459           dataptr += (sizeof (int) + sizeof (LONGEST));
4460           break;
4461         default:
4462           trace_debug ("traceframe %d has unknown block type 0x%x",
4463                        tfnum, blocktype);
4464           return NULL;
4465         }
4466     }
4467
4468   return NULL;
4469 }
4470
4471 static unsigned char *
4472 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
4473 {
4474   unsigned char *regblock;
4475
4476   regblock = traceframe_find_block_type (tframe->data,
4477                                          tframe->data_size,
4478                                          tfnum, 'R');
4479
4480   if (regblock == NULL)
4481     trace_debug ("traceframe %d has no register data", tfnum);
4482
4483   return regblock;
4484 }
4485
4486 /* Get registers from a traceframe.  */
4487
4488 int
4489 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
4490 {
4491   unsigned char *dataptr;
4492   struct tracepoint *tpoint;
4493   struct traceframe *tframe;
4494
4495   tframe = find_traceframe (tfnum);
4496
4497   if (tframe == NULL)
4498     {
4499       trace_debug ("traceframe %d not found", tfnum);
4500       return 1;
4501     }
4502
4503   dataptr = traceframe_find_regblock (tframe, tfnum);
4504   if (dataptr == NULL)
4505     {
4506       /* We don't like making up numbers, but GDB has all manner of
4507          troubles when the target says there are no registers.  */
4508       supply_regblock (regcache, NULL);
4509
4510       /* We can generally guess at a PC, although this will be
4511          misleading for while-stepping frames and multi-location
4512          tracepoints.  */
4513       tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
4514       if (tpoint != NULL)
4515         regcache_write_pc (regcache, tpoint->address);
4516     }
4517   else
4518     supply_regblock (regcache, dataptr);
4519
4520   return 0;
4521 }
4522
4523 static CORE_ADDR
4524 traceframe_get_pc (struct traceframe *tframe)
4525 {
4526   struct regcache regcache;
4527   unsigned char *dataptr;
4528
4529   dataptr = traceframe_find_regblock (tframe, -1);
4530   if (dataptr == NULL)
4531     return 0;
4532
4533   init_register_cache (&regcache, dataptr);
4534   return regcache_read_pc (&regcache);
4535 }
4536
4537 /* Read a requested block of memory from a trace frame.  */
4538
4539 int
4540 traceframe_read_mem (int tfnum, CORE_ADDR addr,
4541                      unsigned char *buf, ULONGEST length,
4542                      ULONGEST *nbytes)
4543 {
4544   struct traceframe *tframe;
4545   unsigned char *database, *dataptr;
4546   unsigned int datasize;
4547   CORE_ADDR maddr;
4548   unsigned short mlen;
4549
4550   trace_debug ("traceframe_read_mem");
4551
4552   tframe = find_traceframe (tfnum);
4553
4554   if (!tframe)
4555     {
4556       trace_debug ("traceframe %d not found", tfnum);
4557       return 1;
4558     }
4559
4560   datasize = tframe->data_size;
4561   database = dataptr = &tframe->data[0];
4562
4563   /* Iterate through a traceframe's blocks, looking for memory.  */
4564   while ((dataptr = traceframe_find_block_type (dataptr,
4565                                                 datasize - (dataptr - database),
4566                                                 tfnum, 'M')) != NULL)
4567     {
4568       memcpy (&maddr, dataptr, sizeof (maddr));
4569       dataptr += sizeof (maddr);
4570       memcpy (&mlen, dataptr, sizeof (mlen));
4571       dataptr += sizeof (mlen);
4572       trace_debug ("traceframe %d has %d bytes at %s",
4573                    tfnum, mlen, paddress (maddr));
4574
4575       /* Check that requested data is in bounds.  */
4576       if (maddr <= addr && (addr + length) <= (maddr + mlen))
4577         {
4578           /* Block includes the requested range, copy it out.  */
4579           memcpy (buf, dataptr + (addr - maddr), length);
4580           *nbytes = length;
4581           return 0;
4582         }
4583
4584       /* Skip over this block.  */
4585       dataptr += mlen;
4586     }
4587
4588   trace_debug ("traceframe %d has no memory data for the desired region",
4589                tfnum);
4590
4591   *nbytes = 0;
4592   return 0;
4593 }
4594
4595 static int
4596 traceframe_read_tsv (int tsvnum, LONGEST *val)
4597 {
4598   int tfnum;
4599   struct traceframe *tframe;
4600   unsigned char *database, *dataptr;
4601   unsigned int datasize;
4602   int vnum;
4603
4604   trace_debug ("traceframe_read_tsv");
4605
4606   tfnum = current_traceframe;
4607
4608   if (tfnum < 0)
4609     {
4610       trace_debug ("no current traceframe");
4611       return 1;
4612     }
4613
4614   tframe = find_traceframe (tfnum);
4615
4616   if (tframe == NULL)
4617     {
4618       trace_debug ("traceframe %d not found", tfnum);
4619       return 1;
4620     }
4621
4622   datasize = tframe->data_size;
4623   database = dataptr = &tframe->data[0];
4624
4625   /* Iterate through a traceframe's blocks, looking for the tsv.  */
4626   while ((dataptr = traceframe_find_block_type (dataptr,
4627                                                 datasize - (dataptr - database),
4628                                                 tfnum, 'V')) != NULL)
4629     {
4630       memcpy (&vnum, dataptr, sizeof (vnum));
4631       dataptr += sizeof (vnum);
4632
4633       trace_debug ("traceframe %d has variable %d", tfnum, vnum);
4634
4635       /* Check that this is the variable we want.  */
4636       if (tsvnum == vnum)
4637         {
4638           memcpy (val, dataptr, sizeof (*val));
4639           return 0;
4640         }
4641
4642       /* Skip over this block.  */
4643       dataptr += sizeof (LONGEST);
4644     }
4645
4646   trace_debug ("traceframe %d has no data for variable %d",
4647                tfnum, tsvnum);
4648   return 1;
4649 }
4650
4651 /* Return the first fast tracepoint whose jump pad contains PC.  */
4652
4653 static struct tracepoint *
4654 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
4655 {
4656   struct tracepoint *tpoint;
4657
4658   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4659     if (tpoint->type == fast_tracepoint)
4660       if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
4661         return tpoint;
4662
4663   return NULL;
4664 }
4665
4666 /* Return GDBserver's tracepoint that matches the IP Agent's
4667    tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
4668    address space.  */
4669
4670 static struct tracepoint *
4671 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
4672 {
4673   struct tracepoint *tpoint;
4674
4675   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4676     if (tpoint->type == fast_tracepoint)
4677       if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
4678         return tpoint;
4679
4680   return NULL;
4681 }
4682
4683 #endif
4684
4685 /* The type of the object that is used to synchronize fast tracepoint
4686    collection.  */
4687
4688 typedef struct collecting_t
4689 {
4690   /* The fast tracepoint number currently collecting.  */
4691   uintptr_t tpoint;
4692
4693   /* A number that GDBserver can use to identify the thread that is
4694      presently holding the collect lock.  This need not (and usually
4695      is not) the thread id, as getting the current thread ID usually
4696      requires a system call, which we want to avoid like the plague.
4697      Usually this is thread's TCB, found in the TLS (pseudo-)
4698      register, which is readable with a single insn on several
4699      architectures.  */
4700   uintptr_t thread_area;
4701 } collecting_t;
4702
4703 #ifndef IN_PROCESS_AGENT
4704
4705 void
4706 force_unlock_trace_buffer (void)
4707 {
4708   write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
4709 }
4710
4711 /* Check if the thread identified by THREAD_AREA which is stopped at
4712    STOP_PC, is presently locking the fast tracepoint collection, and
4713    if so, gather some status of said collection.  Returns 0 if the
4714    thread isn't collecting or in the jump pad at all.  1, if in the
4715    jump pad (or within gdb_collect) and hasn't executed the adjusted
4716    original insn yet (can set a breakpoint there and run to it).  2,
4717    if presently executing the adjusted original insn --- in which
4718    case, if we want to move the thread out of the jump pad, we need to
4719    single-step it until this function returns 0.  */
4720
4721 int
4722 fast_tracepoint_collecting (CORE_ADDR thread_area,
4723                             CORE_ADDR stop_pc,
4724                             struct fast_tpoint_collect_status *status)
4725 {
4726   CORE_ADDR ipa_collecting;
4727   CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
4728   struct tracepoint *tpoint;
4729   int needs_breakpoint;
4730
4731   /* The thread THREAD_AREA is either:
4732
4733       0. not collecting at all, not within the jump pad, or within
4734          gdb_collect or one of its callees.
4735
4736       1. in the jump pad and haven't reached gdb_collect
4737
4738       2. within gdb_collect (out of the jump pad) (collect is set)
4739
4740       3. we're in the jump pad, after gdb_collect having returned,
4741          possibly executing the adjusted insns.
4742
4743       For cases 1 and 3, `collecting' may or not be set.  The jump pad
4744       doesn't have any complicated jump logic, so we can tell if the
4745       thread is executing the adjust original insn or not by just
4746       matching STOP_PC with known jump pad addresses.  If we it isn't
4747       yet executing the original insn, set a breakpoint there, and let
4748       the thread run to it, so to quickly step over a possible (many
4749       insns) gdb_collect call.  Otherwise, or when the breakpoint is
4750       hit, only a few (small number of) insns are left to be executed
4751       in the jump pad.  Single-step the thread until it leaves the
4752       jump pad.  */
4753
4754  again:
4755   tpoint = NULL;
4756   needs_breakpoint = 0;
4757   trace_debug ("fast_tracepoint_collecting");
4758
4759   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
4760                                   &ipa_gdb_jump_pad_buffer))
4761     fatal ("error extracting `gdb_jump_pad_buffer'");
4762   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
4763                                   &ipa_gdb_jump_pad_buffer_end))
4764     fatal ("error extracting `gdb_jump_pad_buffer_end'");
4765
4766   if (ipa_gdb_jump_pad_buffer <= stop_pc && stop_pc < ipa_gdb_jump_pad_buffer_end)
4767     {
4768       /* We can tell which tracepoint(s) the thread is collecting by
4769          matching the jump pad address back to the tracepoint.  */
4770       tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
4771       if (tpoint == NULL)
4772         {
4773           warning ("in jump pad, but no matching tpoint?");
4774           return 0;
4775         }
4776       else
4777         {
4778           trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
4779                        "adj_insn(%s, %s)",
4780                        tpoint->number, paddress (tpoint->address),
4781                        paddress (tpoint->jump_pad),
4782                        paddress (tpoint->jump_pad_end),
4783                        paddress (tpoint->adjusted_insn_addr),
4784                        paddress (tpoint->adjusted_insn_addr_end));
4785         }
4786
4787       /* Definitely in the jump pad.  May or may not need
4788          fast-exit-jump-pad breakpoint.  */
4789       if (tpoint->jump_pad <= stop_pc
4790           && stop_pc < tpoint->adjusted_insn_addr)
4791         needs_breakpoint =  1;
4792     }
4793   else
4794     {
4795       collecting_t ipa_collecting_obj;
4796
4797       /* If `collecting' is set/locked, then the THREAD_AREA thread
4798          may or not be the one holding the lock.  We have to read the
4799          lock to find out.  */
4800
4801       if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
4802                                       &ipa_collecting))
4803         {
4804           trace_debug ("fast_tracepoint_collecting:"
4805                        " failed reading 'collecting' in the inferior");
4806           return 0;
4807         }
4808
4809       if (!ipa_collecting)
4810         {
4811           trace_debug ("fast_tracepoint_collecting: not collecting"
4812                        " (and nobody is).");
4813           return 0;
4814         }
4815
4816       /* Some thread is collecting.  Check which.  */
4817       if (read_inferior_memory (ipa_collecting,
4818                                 (unsigned char *) &ipa_collecting_obj,
4819                                 sizeof (ipa_collecting_obj)) != 0)
4820         goto again;
4821
4822       if (ipa_collecting_obj.thread_area != thread_area)
4823         {
4824           trace_debug ("fast_tracepoint_collecting: not collecting "
4825                        "(another thread is)");
4826           return 0;
4827         }
4828
4829       tpoint
4830         = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
4831       if (tpoint == NULL)
4832         {
4833           warning ("fast_tracepoint_collecting: collecting, "
4834                    "but tpoint %s not found?",
4835                    paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
4836           return 0;
4837         }
4838
4839       /* The thread is within `gdb_collect', skip over the rest of
4840          fast tracepoint collection quickly using a breakpoint.  */
4841       needs_breakpoint = 1;
4842     }
4843
4844   /* The caller wants a bit of status detail.  */
4845   if (status != NULL)
4846     {
4847       status->tpoint_num = tpoint->number;
4848       status->tpoint_addr = tpoint->address;
4849       status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
4850       status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
4851     }
4852
4853   if (needs_breakpoint)
4854     {
4855       /* Hasn't executed the original instruction yet.  Set breakpoint
4856          there, and wait till it's hit, then single-step until exiting
4857          the jump pad.  */
4858
4859       trace_debug ("\
4860 fast_tracepoint_collecting, returning continue-until-break at %s",
4861                    paddress (tpoint->adjusted_insn_addr));
4862
4863       return 1; /* continue */
4864     }
4865   else
4866     {
4867       /* Just single-step until exiting the jump pad.  */
4868
4869       trace_debug ("fast_tracepoint_collecting, returning "
4870                    "need-single-step (%s-%s)",
4871                    paddress (tpoint->adjusted_insn_addr),
4872                    paddress (tpoint->adjusted_insn_addr_end));
4873
4874       return 2; /* single-step */
4875     }
4876 }
4877
4878 #endif
4879
4880 #ifdef IN_PROCESS_AGENT
4881
4882 /* The global fast tracepoint collect lock.  Points to a collecting_t
4883    object built on the stack by the jump pad, if presently locked;
4884    NULL if it isn't locked.  Note that this lock *must* be set while
4885    executing any *function other than the jump pad.  See
4886    fast_tracepoint_collecting.  */
4887 static collecting_t * ATTR_USED collecting;
4888
4889 /* This routine, called from the jump pad (in asm) is designed to be
4890    called from the jump pads of fast tracepoints, thus it is on the
4891    critical path.  */
4892
4893 IP_AGENT_EXPORT void ATTR_USED
4894 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
4895 {
4896   struct fast_tracepoint_ctx ctx;
4897
4898   /* Don't do anything until the trace run is completely set up.  */
4899   if (!tracing)
4900     return;
4901
4902   ctx.base.type = fast_tracepoint;
4903   ctx.regs = regs;
4904   ctx.regcache_initted = 0;
4905   ctx.tpoint = tpoint;
4906
4907   /* Wrap the regblock in a register cache (in the stack, we don't
4908      want to malloc here).  */
4909   ctx.regspace = alloca (register_cache_size ());
4910   if (ctx.regspace == NULL)
4911     {
4912       trace_debug ("Trace buffer block allocation failed, skipping");
4913       return;
4914     }
4915
4916   /* Test the condition if present, and collect if true.  */
4917   if (tpoint->cond == NULL
4918       || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4919                                        tpoint))
4920     {
4921       collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4922                                   tpoint->address, tpoint);
4923
4924       /* Note that this will cause original insns to be written back
4925          to where we jumped from, but that's OK because we're jumping
4926          back to the next whole instruction.  This will go badly if
4927          instruction restoration is not atomic though.  */
4928       if (stopping_tracepoint
4929           || trace_buffer_is_full
4930           || expr_eval_result != expr_eval_no_error)
4931         stop_tracing ();
4932     }
4933   else
4934     {
4935       /* If there was a condition and it evaluated to false, the only
4936          way we would stop tracing is if there was an error during
4937          condition expression evaluation.  */
4938       if (expr_eval_result != expr_eval_no_error)
4939         stop_tracing ();
4940     }
4941 }
4942
4943 #endif
4944
4945 #ifndef IN_PROCESS_AGENT
4946
4947 /* We'll need to adjust these when we consider bi-arch setups, and big
4948    endian machines.  */
4949
4950 static int
4951 write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr)
4952 {
4953   return write_inferior_memory (where,
4954                                 (unsigned char *) &ptr, sizeof (void *));
4955 }
4956
4957 /* The base pointer of the IPA's heap.  This is the only memory the
4958    IPA is allowed to use.  The IPA should _not_ call the inferior's
4959    `malloc' during operation.  That'd be slow, and, most importantly,
4960    it may not be safe.  We may be collecting a tracepoint in a signal
4961    handler, for example.  */
4962 static CORE_ADDR target_tp_heap;
4963
4964 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
4965    to 8 bytes.  */
4966
4967 static CORE_ADDR
4968 target_malloc (ULONGEST size)
4969 {
4970   CORE_ADDR ptr;
4971
4972   if (target_tp_heap == 0)
4973     {
4974       /* We have the pointer *address*, need what it points to.  */
4975       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
4976                                       &target_tp_heap))
4977         fatal ("could get target heap head pointer");
4978     }
4979
4980   ptr = target_tp_heap;
4981   target_tp_heap += size;
4982
4983   /* Pad to 8-byte alignment.  */
4984   target_tp_heap = ((target_tp_heap + 7) & ~0x7);
4985
4986   return ptr;
4987 }
4988
4989 static CORE_ADDR
4990 download_agent_expr (struct agent_expr *expr)
4991 {
4992   CORE_ADDR expr_addr;
4993   CORE_ADDR expr_bytes;
4994
4995   expr_addr = target_malloc (sizeof (*expr));
4996   write_inferior_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
4997
4998   expr_bytes = target_malloc (expr->length);
4999   write_inferior_data_ptr (expr_addr + offsetof (struct agent_expr, bytes),
5000                            expr_bytes);
5001   write_inferior_memory (expr_bytes, expr->bytes, expr->length);
5002
5003   return expr_addr;
5004 }
5005
5006 /* Align V up to N bits.  */
5007 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5008
5009 static void
5010 download_tracepoints (void)
5011 {
5012   CORE_ADDR tpptr = 0, prev_tpptr = 0;
5013   struct tracepoint *tpoint;
5014
5015   /* Start out empty.  */
5016   write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, 0);
5017
5018   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5019     {
5020       struct tracepoint target_tracepoint;
5021
5022       if (tpoint->type != fast_tracepoint)
5023         continue;
5024
5025       target_tracepoint = *tpoint;
5026
5027       prev_tpptr = tpptr;
5028       tpptr = target_malloc (sizeof (*tpoint));
5029       tpoint->obj_addr_on_target = tpptr;
5030
5031       if (tpoint == tracepoints)
5032         {
5033           /* First object in list, set the head pointer in the
5034              inferior.  */
5035           write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, tpptr);
5036         }
5037       else
5038         {
5039           write_inferior_data_ptr (prev_tpptr + offsetof (struct tracepoint,
5040                                                           next),
5041                                    tpptr);
5042         }
5043
5044       /* Write the whole object.  We'll fix up its pointers in a bit.
5045          Assume no next for now.  This is fixed up above on the next
5046          iteration, if there's any.  */
5047       target_tracepoint.next = NULL;
5048       /* Need to clear this here too, since we're downloading the
5049          tracepoints before clearing our own copy.  */
5050       target_tracepoint.hit_count = 0;
5051
5052       write_inferior_memory (tpptr, (unsigned char *) &target_tracepoint,
5053                              sizeof (target_tracepoint));
5054
5055       if (tpoint->cond)
5056         write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
5057                                                    cond),
5058                                  download_agent_expr (tpoint->cond));
5059
5060       if (tpoint->numactions)
5061         {
5062           int i;
5063           CORE_ADDR actions_array;
5064
5065           /* The pointers array.  */
5066           actions_array
5067             = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
5068           write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
5069                                                      actions),
5070                                    actions_array);
5071
5072           /* Now for each pointer, download the action.  */
5073           for (i = 0; i < tpoint->numactions; i++)
5074             {
5075               CORE_ADDR ipa_action = 0;
5076               struct tracepoint_action *action = tpoint->actions[i];
5077
5078               switch (action->type)
5079                 {
5080                 case 'M':
5081                   ipa_action
5082                     = target_malloc (sizeof (struct collect_memory_action));
5083                   write_inferior_memory (ipa_action,
5084                                          (unsigned char *) action,
5085                                          sizeof (struct collect_memory_action));
5086                   break;
5087                 case 'R':
5088                   ipa_action
5089                     = target_malloc (sizeof (struct collect_registers_action));
5090                   write_inferior_memory (ipa_action,
5091                                          (unsigned char *) action,
5092                                          sizeof (struct collect_registers_action));
5093                   break;
5094                 case 'X':
5095                   {
5096                     CORE_ADDR expr;
5097                     struct eval_expr_action *eaction
5098                       = (struct eval_expr_action *) action;
5099
5100                     ipa_action = target_malloc (sizeof (*eaction));
5101                     write_inferior_memory (ipa_action,
5102                                            (unsigned char *) eaction,
5103                                            sizeof (*eaction));
5104
5105                     expr = download_agent_expr (eaction->expr);
5106                     write_inferior_data_ptr
5107                       (ipa_action + offsetof (struct eval_expr_action, expr),
5108                        expr);
5109                     break;
5110                   }
5111                 default:
5112                   trace_debug ("unknown trace action '%c', ignoring",
5113                                action->type);
5114                   break;
5115                 }
5116
5117               if (ipa_action != 0)
5118                 write_inferior_data_ptr
5119                   (actions_array + i * sizeof (sizeof (*tpoint->actions)),
5120                    ipa_action);
5121             }
5122         }
5123     }
5124 }
5125
5126 static void
5127 download_trace_state_variables (void)
5128 {
5129   CORE_ADDR ptr = 0, prev_ptr = 0;
5130   struct trace_state_variable *tsv;
5131
5132   /* Start out empty.  */
5133   write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables, 0);
5134
5135   for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
5136     {
5137       struct trace_state_variable target_tsv;
5138
5139       /* TSV's with a getter have been initialized equally in both the
5140          inferior and GDBserver.  Skip them.  */
5141       if (tsv->getter != NULL)
5142         continue;
5143
5144       target_tsv = *tsv;
5145
5146       prev_ptr = ptr;
5147       ptr = target_malloc (sizeof (*tsv));
5148
5149       if (tsv == trace_state_variables)
5150         {
5151           /* First object in list, set the head pointer in the
5152              inferior.  */
5153
5154           write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables,
5155                                    ptr);
5156         }
5157       else
5158         {
5159           write_inferior_data_ptr (prev_ptr
5160                                    + offsetof (struct trace_state_variable,
5161                                                next),
5162                                    ptr);
5163         }
5164
5165       /* Write the whole object.  We'll fix up its pointers in a bit.
5166          Assume no next, fixup when needed.  */
5167       target_tsv.next = NULL;
5168
5169       write_inferior_memory (ptr, (unsigned char *) &target_tsv,
5170                              sizeof (target_tsv));
5171
5172       if (tsv->name != NULL)
5173         {
5174           size_t size = strlen (tsv->name) + 1;
5175           CORE_ADDR name_addr = target_malloc (size);
5176           write_inferior_memory (name_addr,
5177                                  (unsigned char *) tsv->name, size);
5178           write_inferior_data_ptr (ptr
5179                                    + offsetof (struct trace_state_variable,
5180                                                name),
5181                                    name_addr);
5182         }
5183
5184       if (tsv->getter != NULL)
5185         {
5186           fatal ("what to do with these?");
5187         }
5188     }
5189
5190   if (prev_ptr != 0)
5191     {
5192       /* Fixup the next pointer in the last item in the list.  */
5193       write_inferior_data_ptr (prev_ptr + offsetof (struct trace_state_variable,
5194                                                     next), 0);
5195     }
5196 }
5197
5198 /* Upload complete trace frames out of the IP Agent's trace buffer
5199    into GDBserver's trace buffer.  This always uploads either all or
5200    no trace frames.  This is the counter part of
5201    `trace_alloc_trace_buffer'.  See its description of the atomic
5202    synching mechanism.  */
5203
5204 static void
5205 upload_fast_traceframes (void)
5206 {
5207   unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
5208   unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
5209   CORE_ADDR tf;
5210   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
5211   unsigned int curr_tbctrl_idx;
5212   unsigned int ipa_trace_buffer_ctrl_curr;
5213   unsigned int ipa_trace_buffer_ctrl_curr_old;
5214   CORE_ADDR ipa_trace_buffer_ctrl_addr;
5215   struct breakpoint *about_to_request_buffer_space_bkpt;
5216   CORE_ADDR ipa_trace_buffer_lo;
5217   CORE_ADDR ipa_trace_buffer_hi;
5218
5219   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5220                               &ipa_traceframe_read_count_racy))
5221     {
5222       /* This will happen in most targets if the current thread is
5223          running.  */
5224       return;
5225     }
5226
5227   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5228                               &ipa_traceframe_write_count_racy))
5229     return;
5230
5231   trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
5232                ipa_traceframe_write_count_racy - ipa_traceframe_read_count_racy,
5233                ipa_traceframe_write_count_racy, ipa_traceframe_read_count_racy);
5234
5235   if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
5236     return;
5237
5238   about_to_request_buffer_space_bkpt
5239     = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
5240                          NULL);
5241
5242   if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5243                               &ipa_trace_buffer_ctrl_curr))
5244     return;
5245
5246   ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
5247
5248   curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
5249
5250   {
5251     unsigned int prev, counter;
5252
5253     /* Update the token, with new counters, and the GDBserver stamp
5254        bit.  Alway reuse the current TBC index.  */
5255     prev = ipa_trace_buffer_ctrl_curr & 0x0007ff00;
5256     counter = (prev + 0x100) & 0x0007ff00;
5257
5258     ipa_trace_buffer_ctrl_curr = (0x80000000
5259                                   | (prev << 12)
5260                                   | counter
5261                                   | curr_tbctrl_idx);
5262   }
5263
5264   if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5265                                ipa_trace_buffer_ctrl_curr))
5266     return;
5267
5268   trace_debug ("Lib: Committed %08x -> %08x",
5269                ipa_trace_buffer_ctrl_curr_old,
5270                ipa_trace_buffer_ctrl_curr);
5271
5272   /* Re-read these, now that we've installed the
5273      `about_to_request_buffer_space' breakpoint/lock.  A thread could
5274      have finished a traceframe between the last read of these
5275      counters and setting the breakpoint above.  If we start
5276      uploading, we never want to leave this function with
5277      traceframe_read_count != 0, otherwise, GDBserver could end up
5278      incrementing the counter tokens more than once (due to event loop
5279      nesting), which would break the IP agent's "effective" detection
5280      (see trace_alloc_trace_buffer).  */
5281   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5282                               &ipa_traceframe_read_count))
5283     return;
5284   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5285                               &ipa_traceframe_write_count))
5286     return;
5287
5288   if (debug_threads)
5289     {
5290       trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
5291                    ipa_traceframe_write_count - ipa_traceframe_read_count,
5292                    ipa_traceframe_write_count, ipa_traceframe_read_count);
5293
5294       if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
5295           || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
5296         trace_debug ("note that ipa_traceframe_count's parts changed");
5297     }
5298
5299   /* Get the address of the current TBC object (the IP agent has an
5300      array of 3 such objects).  The index is stored in the TBC
5301      token.  */
5302   ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
5303   ipa_trace_buffer_ctrl_addr
5304     += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
5305
5306   if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
5307                             (unsigned char *) &ipa_trace_buffer_ctrl,
5308                             sizeof (struct ipa_trace_buffer_control)))
5309     return;
5310
5311   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
5312                                   &ipa_trace_buffer_lo))
5313     return;
5314   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
5315                                   &ipa_trace_buffer_hi))
5316     return;
5317
5318   /* Offsets are easier to grok for debugging than raw addresses,
5319      especially for the small trace buffer sizes that are useful for
5320      testing.  */
5321   trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
5322                "endfree=%d wrap=%d hi=%d",
5323                curr_tbctrl_idx,
5324                (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
5325                (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
5326                (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
5327                (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
5328                (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
5329
5330   /* Note that the IPA's buffer is always circular.  */
5331
5332 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
5333
5334 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ)                \
5335   ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
5336
5337 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ)                                  \
5338   (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ)                                    \
5339    - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
5340       ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo)              \
5341       : 0))
5342
5343   tf = IPA_FIRST_TRACEFRAME ();
5344
5345   while (ipa_traceframe_write_count - ipa_traceframe_read_count)
5346     {
5347       struct tracepoint *tpoint;
5348       struct traceframe *tframe;
5349       unsigned char *block;
5350       struct traceframe ipa_tframe;
5351
5352       if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
5353                                 offsetof (struct traceframe, data)))
5354         error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
5355
5356       if (ipa_tframe.tpnum == 0)
5357         fatal ("Uploading: No (more) fast traceframes, but "
5358                "ipa_traceframe_count == %u??\n",
5359                ipa_traceframe_write_count - ipa_traceframe_read_count);
5360
5361       /* Note that this will be incorrect for multi-location
5362          tracepoints...  */
5363       tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
5364
5365       tframe = add_traceframe (tpoint);
5366       if (tframe == NULL)
5367         {
5368           trace_buffer_is_full = 1;
5369           trace_debug ("Uploading: trace buffer is full");
5370         }
5371       else
5372         {
5373           /* Copy the whole set of blocks in one go for now.  FIXME:
5374              split this in smaller blocks.  */
5375           block = add_traceframe_block (tframe, ipa_tframe.data_size);
5376           if (block != NULL)
5377             {
5378               if (read_inferior_memory (tf + offsetof (struct traceframe, data),
5379                                         block, ipa_tframe.data_size))
5380                 error ("Uploading: Couldn't read traceframe data at %s\n",
5381                        paddress (tf + offsetof (struct traceframe, data)));
5382             }
5383
5384           trace_debug ("Uploading: traceframe didn't fit");
5385           finish_traceframe (tframe);
5386         }
5387
5388       tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
5389
5390       /* If we freed the traceframe that wrapped around, go back
5391          to the non-wrap case.  */
5392       if (tf < ipa_trace_buffer_ctrl.start)
5393         {
5394           trace_debug ("Lib: Discarding past the wraparound");
5395           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
5396         }
5397       ipa_trace_buffer_ctrl.start = tf;
5398       ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
5399       ++ipa_traceframe_read_count;
5400
5401       if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
5402           && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
5403         {
5404           trace_debug ("Lib: buffer is fully empty.  "
5405                        "Trace buffer [%d] start=%d free=%d endfree=%d",
5406                        curr_tbctrl_idx,
5407                        (int) (ipa_trace_buffer_ctrl.start
5408                               - ipa_trace_buffer_lo),
5409                        (int) (ipa_trace_buffer_ctrl.free
5410                               - ipa_trace_buffer_lo),
5411                        (int) (ipa_trace_buffer_ctrl.end_free
5412                               - ipa_trace_buffer_lo));
5413
5414           ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
5415           ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
5416           ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
5417           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
5418         }
5419
5420       trace_debug ("Uploaded a traceframe\n"
5421                    "Lib: Trace buffer [%d] start=%d free=%d "
5422                    "endfree=%d wrap=%d hi=%d",
5423                    curr_tbctrl_idx,
5424                    (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
5425                    (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
5426                    (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
5427                    (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
5428                    (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
5429     }
5430
5431   if (write_inferior_memory (ipa_trace_buffer_ctrl_addr,
5432                              (unsigned char *) &ipa_trace_buffer_ctrl,
5433                              sizeof (struct ipa_trace_buffer_control)))
5434     return;
5435
5436   write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
5437                           ipa_traceframe_read_count);
5438
5439   trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
5440
5441   pause_all (1);
5442   cancel_breakpoints ();
5443
5444   delete_breakpoint (about_to_request_buffer_space_bkpt);
5445   about_to_request_buffer_space_bkpt = NULL;
5446
5447   unpause_all (1);
5448
5449   if (trace_buffer_is_full)
5450     stop_tracing ();
5451 }
5452 #endif
5453
5454 #ifdef IN_PROCESS_AGENT
5455
5456 #include <sys/mman.h>
5457 #include <fcntl.h>
5458
5459 IP_AGENT_EXPORT char *gdb_tp_heap_buffer;
5460 IP_AGENT_EXPORT char *gdb_jump_pad_buffer;
5461 IP_AGENT_EXPORT char *gdb_jump_pad_buffer_end;
5462
5463 static void __attribute__ ((constructor))
5464 initialize_tracepoint_ftlib (void)
5465 {
5466   initialize_tracepoint ();
5467 }
5468
5469 #endif
5470
5471 static LONGEST
5472 tsv_get_timestamp (void)
5473 {
5474    struct timeval tv;
5475
5476    if (gettimeofday (&tv, 0) != 0)
5477      return -1;
5478    else
5479      return (LONGEST) tv.tv_sec * 1000000 + tv.tv_usec;
5480 }
5481
5482 void
5483 initialize_tracepoint (void)
5484 {
5485   /* There currently no way to change the buffer size.  */
5486   const int sizeOfBuffer = 5 * 1024 * 1024;
5487   unsigned char *buf = xmalloc (sizeOfBuffer);
5488   init_trace_buffer (buf, sizeOfBuffer);
5489
5490   /* Wire trace state variable 1 to be the timestamp.  This will be
5491      uploaded to GDB upon connection and become one of its trace state
5492      variables.  (In case you're wondering, if GDB already has a trace
5493      variable numbered 1, it will be renumbered.)  */
5494   create_trace_state_variable (1, 0);
5495   set_trace_state_variable_name (1, "trace_timestamp");
5496   set_trace_state_variable_getter (1, tsv_get_timestamp);
5497
5498 #ifdef IN_PROCESS_AGENT
5499   {
5500     int pagesize;
5501     pagesize = sysconf (_SC_PAGE_SIZE);
5502     if (pagesize == -1)
5503       fatal ("sysconf");
5504
5505     gdb_tp_heap_buffer = xmalloc (5 * 1024 * 1024);
5506
5507     /* Allocate scratch buffer aligned on a page boundary.  */
5508     gdb_jump_pad_buffer = memalign (pagesize, pagesize * 20);
5509     gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + pagesize * 20;
5510
5511     /* Make it writable and executable.  */
5512     if (mprotect (gdb_jump_pad_buffer, pagesize * 20,
5513                   PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
5514       fatal ("\
5515 initialize_tracepoint: mprotect(%p, %d, PROT_READ|PROT_EXEC) failed with %s",
5516              gdb_jump_pad_buffer, pagesize * 20, strerror (errno));
5517   }
5518
5519   initialize_low_tracepoint ();
5520 #endif
5521 }