OSDN Git Service

run copyright.sh for 2011.
[pf3gnuchains/pf3gnuchains4x.git] / gdb / gdbserver / tracepoint.c
1 /* Tracepoint code for remote server for GDB.
2    Copyright (C) 2009, 2010, 2011 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_STDINT_H
26 #include <stdint.h>
27 #endif
28
29 /* This file is built for both both GDBserver, and the in-process
30    agent (IPA), a shared library that includes a tracing agent that is
31    loaded by the inferior to support fast tracepoints.  Fast
32    tracepoints (or more accurately, jump based tracepoints) are
33    implemented by patching the tracepoint location with a jump into a
34    small trampoline function whose job is to save the register state,
35    call the in-process tracing agent, and then execute the original
36    instruction that was under the tracepoint jump (possibly adjusted,
37    if PC-relative, or some such).
38
39    The current synchronization design is pull based.  That means,
40    GDBserver does most of the work, by peeking/poking at the inferior
41    agent's memory directly for downloading tracepoint and associated
42    objects, and for uploading trace frames.  Whenever the IPA needs
43    something from GDBserver (trace buffer is full, tracing stopped for
44    some reason, etc.) the IPA calls a corresponding hook function
45    where GDBserver has placed a breakpoint.
46
47    Each of the agents has its own trace buffer.  When browsing the
48    trace frames built from slow and fast tracepoints from GDB (tfind
49    mode), there's no guarantee the user is seeing the trace frames in
50    strict chronological creation order, although, GDBserver tries to
51    keep the order relatively reasonable, by syncing the trace buffers
52    at appropriate times.
53
54 */
55
56 static void trace_vdebug (const char *, ...) ATTR_FORMAT (printf, 1, 2);
57
58 static void
59 trace_vdebug (const char *fmt, ...)
60 {
61   char buf[1024];
62   va_list ap;
63
64   va_start (ap, fmt);
65   vsprintf (buf, fmt, ap);
66   fprintf (stderr, "gdbserver/tracepoint: %s\n", buf);
67   va_end (ap);
68 }
69
70 #define trace_debug_1(level, fmt, args...)      \
71   do {                                          \
72     if (level <= debug_threads)                 \
73       trace_vdebug ((fmt), ##args);             \
74   } while (0)
75
76 #define trace_debug(FMT, args...)               \
77   trace_debug_1 (1, FMT, ##args)
78
79 #if defined(__GNUC__)
80 #  define ATTR_USED __attribute__((used))
81 #  define ATTR_NOINLINE __attribute__((noinline))
82 #  define ATTR_CONSTRUCTOR __attribute__ ((constructor))
83 #else
84 #  define ATTR_USED
85 #  define ATTR_NOINLINE
86 #  define ATTR_CONSTRUCTOR
87 #endif
88
89 /* Make sure the functions the IPA needs to export (symbols GDBserver
90    needs to query GDB about) are exported.  */
91
92 #ifdef IN_PROCESS_AGENT
93 # if defined _WIN32 || defined __CYGWIN__
94 #   define IP_AGENT_EXPORT __declspec(dllexport) ATTR_USED
95 # else
96 #   if __GNUC__ >= 4
97 #     define IP_AGENT_EXPORT \
98   __attribute__ ((visibility("default"))) ATTR_USED
99 #   else
100 #     define IP_AGENT_EXPORT ATTR_USED
101 #   endif
102 # endif
103 #else
104 #  define IP_AGENT_EXPORT
105 #endif
106
107 /* Prefix exported symbols, for good citizenship.  All the symbols
108    that need exporting are defined in this module.  */
109 #ifdef IN_PROCESS_AGENT
110 # define gdb_tp_heap_buffer gdb_agent_gdb_tp_heap_buffer
111 # define gdb_jump_pad_buffer gdb_agent_gdb_jump_pad_buffer
112 # define gdb_jump_pad_buffer_end gdb_agent_gdb_jump_pad_buffer_end
113 # define collecting gdb_agent_collecting
114 # define gdb_collect gdb_agent_gdb_collect
115 # define stop_tracing gdb_agent_stop_tracing
116 # define flush_trace_buffer gdb_agent_flush_trace_buffer
117 # define about_to_request_buffer_space gdb_agent_about_to_request_buffer_space
118 # define trace_buffer_is_full gdb_agent_trace_buffer_is_full
119 # define stopping_tracepoint gdb_agent_stopping_tracepoint
120 # define expr_eval_result gdb_agent_expr_eval_result
121 # define error_tracepoint gdb_agent_error_tracepoint
122 # define tracepoints gdb_agent_tracepoints
123 # define tracing gdb_agent_tracing
124 # define trace_buffer_ctrl gdb_agent_trace_buffer_ctrl
125 # define trace_buffer_ctrl_curr gdb_agent_trace_buffer_ctrl_curr
126 # define trace_buffer_lo gdb_agent_trace_buffer_lo
127 # define trace_buffer_hi gdb_agent_trace_buffer_hi
128 # define traceframe_read_count gdb_agent_traceframe_read_count
129 # define traceframe_write_count gdb_agent_traceframe_write_count
130 # define traceframes_created gdb_agent_traceframes_created
131 # define trace_state_variables gdb_agent_trace_state_variables
132 # define get_raw_reg gdb_agent_get_raw_reg
133 # define get_trace_state_variable_value gdb_agent_get_trace_state_variable_value
134 # define set_trace_state_variable_value gdb_agent_set_trace_state_variable_value
135 # define ust_loaded gdb_agent_ust_loaded
136 # define helper_thread_id gdb_agent_helper_thread_id
137 # define cmd_buf gdb_agent_cmd_buf
138 #endif
139
140 #ifndef IN_PROCESS_AGENT
141
142 /* Addresses of in-process agent's symbols GDBserver cares about.  */
143
144 struct ipa_sym_addresses
145 {
146   CORE_ADDR addr_gdb_tp_heap_buffer;
147   CORE_ADDR addr_gdb_jump_pad_buffer;
148   CORE_ADDR addr_gdb_jump_pad_buffer_end;
149   CORE_ADDR addr_collecting;
150   CORE_ADDR addr_gdb_collect;
151   CORE_ADDR addr_stop_tracing;
152   CORE_ADDR addr_flush_trace_buffer;
153   CORE_ADDR addr_about_to_request_buffer_space;
154   CORE_ADDR addr_trace_buffer_is_full;
155   CORE_ADDR addr_stopping_tracepoint;
156   CORE_ADDR addr_expr_eval_result;
157   CORE_ADDR addr_error_tracepoint;
158   CORE_ADDR addr_tracepoints;
159   CORE_ADDR addr_tracing;
160   CORE_ADDR addr_trace_buffer_ctrl;
161   CORE_ADDR addr_trace_buffer_ctrl_curr;
162   CORE_ADDR addr_trace_buffer_lo;
163   CORE_ADDR addr_trace_buffer_hi;
164   CORE_ADDR addr_traceframe_read_count;
165   CORE_ADDR addr_traceframe_write_count;
166   CORE_ADDR addr_traceframes_created;
167   CORE_ADDR addr_trace_state_variables;
168   CORE_ADDR addr_get_raw_reg;
169   CORE_ADDR addr_get_trace_state_variable_value;
170   CORE_ADDR addr_set_trace_state_variable_value;
171   CORE_ADDR addr_ust_loaded;
172   CORE_ADDR addr_helper_thread_id;
173   CORE_ADDR addr_cmd_buf;
174 };
175
176 #define STRINGIZE_1(STR) #STR
177 #define STRINGIZE(STR) STRINGIZE_1(STR)
178 #define IPA_SYM(SYM)                            \
179   {                                                     \
180     STRINGIZE (gdb_agent_ ## SYM),                      \
181     offsetof (struct ipa_sym_addresses, addr_ ## SYM)   \
182   }
183
184 static struct
185 {
186   const char *name;
187   int offset;
188   int required;
189 } symbol_list[] = {
190   IPA_SYM(gdb_tp_heap_buffer),
191   IPA_SYM(gdb_jump_pad_buffer),
192   IPA_SYM(gdb_jump_pad_buffer_end),
193   IPA_SYM(collecting),
194   IPA_SYM(gdb_collect),
195   IPA_SYM(stop_tracing),
196   IPA_SYM(flush_trace_buffer),
197   IPA_SYM(about_to_request_buffer_space),
198   IPA_SYM(trace_buffer_is_full),
199   IPA_SYM(stopping_tracepoint),
200   IPA_SYM(expr_eval_result),
201   IPA_SYM(error_tracepoint),
202   IPA_SYM(tracepoints),
203   IPA_SYM(tracing),
204   IPA_SYM(trace_buffer_ctrl),
205   IPA_SYM(trace_buffer_ctrl_curr),
206   IPA_SYM(trace_buffer_lo),
207   IPA_SYM(trace_buffer_hi),
208   IPA_SYM(traceframe_read_count),
209   IPA_SYM(traceframe_write_count),
210   IPA_SYM(traceframes_created),
211   IPA_SYM(trace_state_variables),
212   IPA_SYM(get_raw_reg),
213   IPA_SYM(get_trace_state_variable_value),
214   IPA_SYM(set_trace_state_variable_value),
215   IPA_SYM(ust_loaded),
216   IPA_SYM(helper_thread_id),
217   IPA_SYM(cmd_buf),
218 };
219
220 struct ipa_sym_addresses ipa_sym_addrs;
221
222 int all_tracepoint_symbols_looked_up;
223
224 int
225 in_process_agent_loaded (void)
226 {
227   return all_tracepoint_symbols_looked_up;
228 }
229
230 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
231
232 /* Returns true if both the in-process agent library and the static
233    tracepoints libraries are loaded in the inferior.  */
234
235 static int
236 in_process_agent_loaded_ust (void)
237 {
238   int loaded = 0;
239
240   if (!in_process_agent_loaded ())
241     {
242       warning ("In-process agent not loaded");
243       return 0;
244     }
245
246   if (read_inferior_integer (ipa_sym_addrs.addr_ust_loaded, &loaded))
247     {
248       warning ("Error reading ust_loaded in lib");
249       return 0;
250     }
251
252   return loaded;
253 }
254
255 static void
256 write_e_ipa_not_loaded (char *buffer)
257 {
258   sprintf (buffer,
259            "E.In-process agent library not loaded in process.  "
260            "Fast and static tracepoints unavailable.");
261 }
262
263 /* Write an error to BUFFER indicating that UST isn't loaded in the
264    inferior.  */
265
266 static void
267 write_e_ust_not_loaded (char *buffer)
268 {
269 #ifdef HAVE_UST
270   sprintf (buffer,
271            "E.UST library not loaded in process.  "
272            "Static tracepoints unavailable.");
273 #else
274   sprintf (buffer, "E.GDBserver was built without static tracepoints support");
275 #endif
276 }
277
278 /* If the in-process agent library isn't loaded in the inferior, write
279    an error to BUFFER, and return 1.  Otherwise, return 0.  */
280
281 static int
282 maybe_write_ipa_not_loaded (char *buffer)
283 {
284   if (!in_process_agent_loaded ())
285     {
286       write_e_ipa_not_loaded (buffer);
287       return 1;
288     }
289   return 0;
290 }
291
292 /* If the in-process agent library and the ust (static tracepoints)
293    library aren't loaded in the inferior, write an error to BUFFER,
294    and return 1.  Otherwise, return 0.  */
295
296 static int
297 maybe_write_ipa_ust_not_loaded (char *buffer)
298 {
299   if (!in_process_agent_loaded ())
300     {
301       write_e_ipa_not_loaded (buffer);
302       return 1;
303     }
304   else if (!in_process_agent_loaded_ust ())
305     {
306       write_e_ust_not_loaded (buffer);
307       return 1;
308     }
309   return 0;
310 }
311
312 /* Cache all future symbols that the tracepoints module might request.
313    We can not request symbols at arbitrary states in the remote
314    protocol, only when the client tells us that new symbols are
315    available.  So when we load the in-process library, make sure to
316    check the entire list.  */
317
318 void
319 tracepoint_look_up_symbols (void)
320 {
321   int all_ok;
322   int i;
323
324   if (all_tracepoint_symbols_looked_up)
325     return;
326
327   all_ok = 1;
328   for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
329     {
330       CORE_ADDR *addrp =
331         (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
332
333       if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
334         {
335           if (debug_threads)
336             fprintf (stderr, "symbol `%s' not found\n", symbol_list[i].name);
337           all_ok = 0;
338         }
339     }
340
341   all_tracepoint_symbols_looked_up = all_ok;
342 }
343
344 #endif
345
346 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
347    of the "stop_tracing" function.  When this breakpoint is hit,
348    tracing stopped in the IPA for some reason.  E.g., due to
349    tracepoint reaching the pass count, hitting conditional expression
350    evaluation error, etc.
351
352    The IPA's trace buffer is never in circular tracing mode: instead,
353    GDBserver's is, and whenever the in-process buffer fills, it calls
354    "flush_trace_buffer", which triggers an internal breakpoint.
355    GDBserver reacts to this breakpoint by pulling the meanwhile
356    collected data.  Old frames discarding is always handled on the
357    GDBserver side.  */
358
359 #ifdef IN_PROCESS_AGENT
360 int debug_threads = 0;
361
362 int
363 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
364 {
365   memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
366   return 0;
367 }
368
369 /* Call this in the functions where GDBserver places a breakpoint, so
370    that the compiler doesn't try to be clever and skip calling the
371    function at all.  This is necessary, even if we tell the compiler
372    to not inline said functions.  */
373
374 #if defined(__GNUC__)
375 #  define UNKNOWN_SIDE_EFFECTS() asm ("")
376 #else
377 #  define UNKNOWN_SIDE_EFFECTS() do {} while (0)
378 #endif
379
380 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
381 stop_tracing (void)
382 {
383   /* GDBserver places breakpoint here.  */
384   UNKNOWN_SIDE_EFFECTS();
385 }
386
387 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
388 flush_trace_buffer (void)
389 {
390   /* GDBserver places breakpoint here.  */
391   UNKNOWN_SIDE_EFFECTS();
392 }
393
394 #endif
395
396 #ifndef IN_PROCESS_AGENT
397 static int
398 tracepoint_handler (CORE_ADDR address)
399 {
400   trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
401                paddress (address));
402   return 0;
403 }
404
405 /* Breakpoint at "stop_tracing" in the inferior lib.  */
406 struct breakpoint *stop_tracing_bkpt;
407 static int stop_tracing_handler (CORE_ADDR);
408
409 /* Breakpoint at "flush_trace_buffer" in the inferior lib.  */
410 struct breakpoint *flush_trace_buffer_bkpt;
411 static int flush_trace_buffer_handler (CORE_ADDR);
412
413 static void download_tracepoints (void);
414 static void download_trace_state_variables (void);
415 static void upload_fast_traceframes (void);
416
417 static int run_inferior_command (char *cmd);
418
419 static int
420 read_inferior_integer (CORE_ADDR symaddr, int *val)
421 {
422   return read_inferior_memory (symaddr, (unsigned char *) val,
423                                sizeof (*val));
424 }
425
426 static int
427 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
428 {
429   return read_inferior_memory (symaddr, (unsigned char *) val,
430                                sizeof (*val));
431 }
432
433 static int
434 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
435 {
436   void *pval = (void *) (uintptr_t) val;
437   int ret;
438
439   ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
440   *val = (uintptr_t) pval;
441   return ret;
442 }
443
444 static int
445 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
446 {
447   void *pval = (void *) (uintptr_t) val;
448   return write_inferior_memory (symaddr,
449                                 (unsigned char *) &pval, sizeof (pval));
450 }
451
452 static int
453 write_inferior_integer (CORE_ADDR symaddr, int val)
454 {
455   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
456 }
457
458 static int
459 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
460 {
461   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
462 }
463
464 #endif
465
466 /* This enum must exactly match what is documented in
467    gdb/doc/agentexpr.texi, including all the numerical values.  */
468
469 enum gdb_agent_op
470   {
471     gdb_agent_op_float = 0x01,
472     gdb_agent_op_add = 0x02,
473     gdb_agent_op_sub = 0x03,
474     gdb_agent_op_mul = 0x04,
475     gdb_agent_op_div_signed = 0x05,
476     gdb_agent_op_div_unsigned = 0x06,
477     gdb_agent_op_rem_signed = 0x07,
478     gdb_agent_op_rem_unsigned = 0x08,
479     gdb_agent_op_lsh = 0x09,
480     gdb_agent_op_rsh_signed = 0x0a,
481     gdb_agent_op_rsh_unsigned = 0x0b,
482     gdb_agent_op_trace = 0x0c,
483     gdb_agent_op_trace_quick = 0x0d,
484     gdb_agent_op_log_not = 0x0e,
485     gdb_agent_op_bit_and = 0x0f,
486     gdb_agent_op_bit_or = 0x10,
487     gdb_agent_op_bit_xor = 0x11,
488     gdb_agent_op_bit_not = 0x12,
489     gdb_agent_op_equal = 0x13,
490     gdb_agent_op_less_signed = 0x14,
491     gdb_agent_op_less_unsigned = 0x15,
492     gdb_agent_op_ext = 0x16,
493     gdb_agent_op_ref8 = 0x17,
494     gdb_agent_op_ref16 = 0x18,
495     gdb_agent_op_ref32 = 0x19,
496     gdb_agent_op_ref64 = 0x1a,
497     gdb_agent_op_ref_float = 0x1b,
498     gdb_agent_op_ref_double = 0x1c,
499     gdb_agent_op_ref_long_double = 0x1d,
500     gdb_agent_op_l_to_d = 0x1e,
501     gdb_agent_op_d_to_l = 0x1f,
502     gdb_agent_op_if_goto = 0x20,
503     gdb_agent_op_goto = 0x21,
504     gdb_agent_op_const8 = 0x22,
505     gdb_agent_op_const16 = 0x23,
506     gdb_agent_op_const32 = 0x24,
507     gdb_agent_op_const64 = 0x25,
508     gdb_agent_op_reg = 0x26,
509     gdb_agent_op_end = 0x27,
510     gdb_agent_op_dup = 0x28,
511     gdb_agent_op_pop = 0x29,
512     gdb_agent_op_zero_ext = 0x2a,
513     gdb_agent_op_swap = 0x2b,
514     gdb_agent_op_getv = 0x2c,
515     gdb_agent_op_setv = 0x2d,
516     gdb_agent_op_tracev = 0x2e,
517     gdb_agent_op_trace16 = 0x30,
518     gdb_agent_op_last
519   };
520
521 static const char *gdb_agent_op_names [gdb_agent_op_last] =
522   {
523     "?undef?",
524     "float",
525     "add",
526     "sub",
527     "mul",
528     "div_signed",
529     "div_unsigned",
530     "rem_signed",
531     "rem_unsigned",
532     "lsh",
533     "rsh_signed",
534     "rsh_unsigned",
535     "trace",
536     "trace_quick",
537     "log_not",
538     "bit_and",
539     "bit_or",
540     "bit_xor",
541     "bit_not",
542     "equal",
543     "less_signed",
544     "less_unsigned",
545     "ext",
546     "ref8",
547     "ref16",
548     "ref32",
549     "ref64",
550     "ref_float",
551     "ref_double",
552     "ref_long_double",
553     "l_to_d",
554     "d_to_l",
555     "if_goto",
556     "goto",
557     "const8",
558     "const16",
559     "const32",
560     "const64",
561     "reg",
562     "end",
563     "dup",
564     "pop",
565     "zero_ext",
566     "swap",
567     "getv",
568     "setv",
569     "tracev",
570     "?undef?",
571     "trace16",
572   };
573
574 struct agent_expr
575 {
576   int length;
577
578   unsigned char *bytes;
579 };
580
581 /* Base action.  Concrete actions inherit this.  */
582
583 struct tracepoint_action
584 {
585   char type;
586 };
587
588 /* An 'M' (collect memory) action.  */
589 struct collect_memory_action
590 {
591   struct tracepoint_action base;
592
593   ULONGEST addr;
594   ULONGEST len;
595   int basereg;
596 };
597
598 /* An 'R' (collect registers) action.  */
599
600 struct collect_registers_action
601 {
602   struct tracepoint_action base;
603 };
604
605 /* An 'X' (evaluate expression) action.  */
606
607 struct eval_expr_action
608 {
609   struct tracepoint_action base;
610
611   struct agent_expr *expr;
612 };
613
614 /* An 'L' (collect static trace data) action.  */
615 struct collect_static_trace_data_action
616 {
617   struct tracepoint_action base;
618 };
619
620 /* This structure describes a piece of the source-level definition of
621    the tracepoint.  The contents are not interpreted by the target,
622    but preserved verbatim for uploading upon reconnection.  */
623
624 struct source_string
625 {
626   /* The type of string, such as "cond" for a conditional.  */
627   char *type;
628
629   /* The source-level string itself.  For the sake of target
630      debugging, we store it in plaintext, even though it is always
631      transmitted in hex.  */
632   char *str;
633
634   /* Link to the next one in the list.  We link them in the order
635      received, in case some make up an ordered list of commands or
636      some such.  */
637   struct source_string *next;
638 };
639
640 enum tracepoint_type
641 {
642   /* Trap based tracepoint.  */
643   trap_tracepoint,
644
645   /* A fast tracepoint implemented with a jump instead of a trap.  */
646   fast_tracepoint,
647
648   /* A static tracepoint, implemented by a program call into a tracing
649      library.  */
650   static_tracepoint
651 };
652
653 struct tracepoint_hit_ctx;
654
655 typedef enum eval_result_type (*condfn) (struct tracepoint_hit_ctx *,
656                                          ULONGEST *);
657
658 /* The definition of a tracepoint.  */
659
660 /* Tracepoints may have multiple locations, each at a different
661    address.  This can occur with optimizations, template
662    instantiation, etc.  Since the locations may be in different
663    scopes, the conditions and actions may be different for each
664    location.  Our target version of tracepoints is more like GDB's
665    notion of "breakpoint locations", but we have almost nothing that
666    is not per-location, so we bother having two kinds of objects.  The
667    key consequence is that numbers are not unique, and that it takes
668    both number and address to identify a tracepoint uniquely.  */
669
670 struct tracepoint
671 {
672   /* The number of the tracepoint, as specified by GDB.  Several
673      tracepoint objects here may share a number.  */
674   int number;
675
676   /* Address at which the tracepoint is supposed to trigger.  Several
677      tracepoints may share an address.  */
678   CORE_ADDR address;
679
680   /* Tracepoint type.  */
681   enum tracepoint_type type;
682
683   /* True if the tracepoint is currently enabled.  */
684   int enabled;
685
686   /* The number of single steps that will be performed after each
687      tracepoint hit.  */
688   long step_count;
689
690   /* The number of times the tracepoint may be hit before it will
691      terminate the entire tracing run.  */
692   long pass_count;
693
694   /* Pointer to the agent expression that is the tracepoint's
695      conditional, or NULL if the tracepoint is unconditional.  */
696   struct agent_expr *cond;
697
698   /* The list of actions to take when the tracepoint triggers.  */
699   int numactions;
700   struct tracepoint_action **actions;
701
702   /* Count of the times we've hit this tracepoint during the run.
703      Note that while-stepping steps are not counted as "hits".  */
704   long hit_count;
705
706   CORE_ADDR compiled_cond;
707
708   /* Link to the next tracepoint in the list.  */
709   struct tracepoint *next;
710
711 #ifndef IN_PROCESS_AGENT
712   /* The list of actions to take when the tracepoint triggers, in
713      string/packet form.  */
714   char **actions_str;
715
716   /* The collection of strings that describe the tracepoint as it was
717      entered into GDB.  These are not used by the target, but are
718      reported back to GDB upon reconnection.  */
719   struct source_string *source_strings;
720
721   /* The number of bytes displaced by fast tracepoints. It may subsume
722      multiple instructions, for multi-byte fast tracepoints.  This
723      field is only valid for fast tracepoints.  */
724   int orig_size;
725
726   /* Only for fast tracepoints.  */
727   CORE_ADDR obj_addr_on_target;
728
729   /* Address range where the original instruction under a fast
730      tracepoint was relocated to.  (_end is actually one byte past
731      the end).  */
732   CORE_ADDR adjusted_insn_addr;
733   CORE_ADDR adjusted_insn_addr_end;
734
735   /* The address range of the piece of the jump pad buffer that was
736      assigned to this fast tracepoint.  (_end is actually one byte
737      past the end).*/
738   CORE_ADDR jump_pad;
739   CORE_ADDR jump_pad_end;
740
741   /* The list of actions to take while in a stepping loop.  These
742      fields are only valid for patch-based tracepoints.  */
743   int num_step_actions;
744   struct tracepoint_action **step_actions;
745   /* Same, but in string/packet form.  */
746   char **step_actions_str;
747
748   /* Handle returned by the breakpoint or tracepoint module when we
749      inserted the trap or jump, or hooked into a static tracepoint.
750      NULL if we haven't inserted it yet.  */
751   void *handle;
752 #endif
753
754 };
755
756 #ifndef IN_PROCESS_AGENT
757
758 /* Given `while-stepping', a thread may be collecting data for more
759    than one tracepoint simultaneously.  On the other hand, the same
760    tracepoint with a while-stepping action may be hit by more than one
761    thread simultaneously (but not quite, each thread could be handling
762    a different step).  Each thread holds a list of these objects,
763    representing the current step of each while-stepping action being
764    collected.  */
765
766 struct wstep_state
767 {
768   struct wstep_state *next;
769
770   /* The tracepoint number.  */
771   int tp_number;
772   /* The tracepoint's address.  */
773   CORE_ADDR tp_address;
774
775   /* The number of the current step in this 'while-stepping'
776      action.  */
777   long current_step;
778 };
779
780 #endif
781
782 /* The linked list of all tracepoints.  Marked explicitly as used as
783    the in-process library doesn't use it for the fast tracepoints
784    support.  */
785 IP_AGENT_EXPORT struct tracepoint *tracepoints ATTR_USED;
786
787 #ifndef IN_PROCESS_AGENT
788
789 /* Pointer to the last tracepoint in the list, new tracepoints are
790    linked in at the end.  */
791
792 static struct tracepoint *last_tracepoint;
793 #endif
794
795 /* The first tracepoint to exceed its pass count.  */
796
797 IP_AGENT_EXPORT struct tracepoint *stopping_tracepoint;
798
799 /* True if the trace buffer is full or otherwise no longer usable.  */
800
801 IP_AGENT_EXPORT int trace_buffer_is_full;
802
803 /* Enumeration of the different kinds of things that can happen during
804    agent expression evaluation.  */
805
806 enum eval_result_type
807   {
808     expr_eval_no_error,
809     expr_eval_empty_expression,
810     expr_eval_empty_stack,
811     expr_eval_stack_overflow,
812     expr_eval_stack_underflow,
813     expr_eval_unhandled_opcode,
814     expr_eval_unrecognized_opcode,
815     expr_eval_divide_by_zero,
816     expr_eval_invalid_goto
817   };
818
819 static enum eval_result_type expr_eval_result = expr_eval_no_error;
820
821 #ifndef IN_PROCESS_AGENT
822
823 static const char *eval_result_names[] =
824   {
825     "terror:in the attic",  /* this should never be reported */
826     "terror:empty expression",
827     "terror:empty stack",
828     "terror:stack overflow",
829     "terror:stack underflow",
830     "terror:unhandled opcode",
831     "terror:unrecognized opcode",
832     "terror:divide by zero"
833   };
834
835 #endif
836
837 /* The tracepoint in which the error occurred.  */
838
839 static struct tracepoint *error_tracepoint;
840
841 struct trace_state_variable
842 {
843   /* This is the name of the variable as used in GDB.  The target
844      doesn't use the name, but needs to have it for saving and
845      reconnection purposes.  */
846   char *name;
847
848   /* This number identifies the variable uniquely.  Numbers may be
849      assigned either by the target (in the case of builtin variables),
850      or by GDB, and are presumed unique during the course of a trace
851      experiment.  */
852   int number;
853
854   /* The variable's initial value, a 64-bit signed integer always.  */
855   LONGEST initial_value;
856
857   /* The variable's value, a 64-bit signed integer always.  */
858   LONGEST value;
859
860   /* Pointer to a getter function, used to supply computed values.  */
861   LONGEST (*getter) (void);
862
863   /* Link to the next variable.  */
864   struct trace_state_variable *next;
865 };
866
867 /* Linked list of all trace state variables.  */
868
869 #ifdef IN_PROCESS_AGENT
870 struct trace_state_variable *alloced_trace_state_variables;
871 #endif
872
873 IP_AGENT_EXPORT struct trace_state_variable *trace_state_variables;
874
875 /* The results of tracing go into a fixed-size space known as the
876    "trace buffer".  Because usage follows a limited number of
877    patterns, we manage it ourselves rather than with malloc.  Basic
878    rules are that we create only one trace frame at a time, each is
879    variable in size, they are never moved once created, and we only
880    discard if we are doing a circular buffer, and then only the oldest
881    ones.  Each trace frame includes its own size, so we don't need to
882    link them together, and the trace frame number is relative to the
883    first one, so we don't need to record numbers.  A trace frame also
884    records the number of the tracepoint that created it.  The data
885    itself is a series of blocks, each introduced by a single character
886    and with a defined format.  Each type of block has enough
887    type/length info to allow scanners to jump quickly from one block
888    to the next without reading each byte in the block.  */
889
890 /* Trace buffer management would be simple - advance a free pointer
891    from beginning to end, then stop - were it not for the circular
892    buffer option, which is a useful way to prevent a trace run from
893    stopping prematurely because the buffer filled up.  In the circular
894    case, the location of the first trace frame (trace_buffer_start)
895    moves as old trace frames are discarded.  Also, since we grow trace
896    frames incrementally as actions are performed, we wrap around to
897    the beginning of the trace buffer.  This is per-block, so each
898    block within a trace frame remains contiguous.  Things get messy
899    when the wrapped-around trace frame is the one being discarded; the
900    free space ends up in two parts at opposite ends of the buffer.  */
901
902 #ifndef ATTR_PACKED
903 #  if defined(__GNUC__)
904 #    define ATTR_PACKED __attribute__ ((packed))
905 #  else
906 #    define ATTR_PACKED /* nothing */
907 #  endif
908 #endif
909
910 /* The data collected at a tracepoint hit.  This object should be as
911    small as possible, since there may be a great many of them.  We do
912    not need to keep a frame number, because they are all sequential
913    and there are no deletions; so the Nth frame in the buffer is
914    always frame number N.  */
915
916 struct traceframe
917 {
918   /* Number of the tracepoint that collected this traceframe.  A value
919      of 0 indicates the current end of the trace buffer.  We make this
920      a 16-bit field because it's never going to happen that GDB's
921      numbering of tracepoints reaches 32,000.  */
922   int tpnum : 16;
923
924   /* The size of the data in this trace frame.  We limit this to 32
925      bits, even on a 64-bit target, because it's just implausible that
926      one is validly going to collect 4 gigabytes of data at a single
927      tracepoint hit.  */
928   unsigned int data_size : 32;
929
930   /* The base of the trace data, which is contiguous from this point.  */
931   unsigned char data[0];
932
933 } ATTR_PACKED;
934
935 /* The traceframe to be used as the source of data to send back to
936    GDB.  A value of -1 means to get data from the live program.  */
937
938 int current_traceframe = -1;
939
940 /* This flag is true if the trace buffer is circular, meaning that
941    when it fills, the oldest trace frames are discarded in order to
942    make room.  */
943
944 #ifndef IN_PROCESS_AGENT
945 static int circular_trace_buffer;
946 #endif
947
948 /* Pointer to the block of memory that traceframes all go into.  */
949
950 static unsigned char *trace_buffer_lo;
951
952 /* Pointer to the end of the trace buffer, more precisely to the byte
953    after the end of the buffer.  */
954
955 static unsigned char *trace_buffer_hi;
956
957 /* Control structure holding the read/write/etc. pointers into the
958    trace buffer.  We need more than one of these to implement a
959    transaction-like mechanism to garantees that both GDBserver and the
960    in-process agent can try to change the trace buffer
961    simultaneously.  */
962
963 struct trace_buffer_control
964 {
965   /* Pointer to the first trace frame in the buffer.  In the
966      non-circular case, this is equal to trace_buffer_lo, otherwise it
967      moves around in the buffer.  */
968   unsigned char *start;
969
970   /* Pointer to the free part of the trace buffer.  Note that we clear
971      several bytes at and after this pointer, so that traceframe
972      scans/searches terminate properly.  */
973   unsigned char *free;
974
975   /* Pointer to the byte after the end of the free part.  Note that
976      this may be smaller than trace_buffer_free in the circular case,
977      and means that the free part is in two pieces.  Initially it is
978      equal to trace_buffer_hi, then is generally equivalent to
979      trace_buffer_start.  */
980   unsigned char *end_free;
981
982   /* Pointer to the wraparound.  If not equal to trace_buffer_hi, then
983      this is the point at which the trace data breaks, and resumes at
984      trace_buffer_lo.  */
985   unsigned char *wrap;
986 };
987
988 /* Same as above, to be used by GDBserver when updating the in-process
989    agent.  */
990 struct ipa_trace_buffer_control
991 {
992   uintptr_t start;
993   uintptr_t free;
994   uintptr_t end_free;
995   uintptr_t wrap;
996 };
997
998
999 /* We have possibly both GDBserver and an inferior thread accessing
1000    the same IPA trace buffer memory.  The IPA is the producer (tries
1001    to put new frames in the buffer), while GDBserver occasionally
1002    consumes them, that is, flushes the IPA's buffer into its own
1003    buffer.  Both sides need to update the trace buffer control
1004    pointers (current head, tail, etc.).  We can't use a global lock to
1005    synchronize the accesses, as otherwise we could deadlock GDBserver
1006    (if the thread holding the lock stops for a signal, say).  So
1007    instead of that, we use a transaction scheme where GDBserver writes
1008    always prevail over the IPAs writes, and, we have the IPA detect
1009    the commit failure/overwrite, and retry the whole attempt.  This is
1010    mainly implemented by having a global token object that represents
1011    who wrote last to the buffer control structure.  We need to freeze
1012    any inferior writing to the buffer while GDBserver touches memory,
1013    so that the inferior can correctly detect that GDBserver had been
1014    there, otherwise, it could mistakingly think its commit was
1015    successful; that's implemented by simply having GDBserver set a
1016    breakpoint the inferior hits if it is the critical region.
1017
1018    There are three cycling trace buffer control structure copies
1019    (buffer head, tail, etc.), with the token object including an index
1020    indicating which is current live copy.  The IPA tentatively builds
1021    an updated copy in a non-current control structure, while GDBserver
1022    always clobbers the current version directly.  The IPA then tries
1023    to atomically "commit" its version; if GDBserver clobbered the
1024    structure meanwhile, that will fail, and the IPA restarts the
1025    allocation process.
1026
1027    Listing the step in further detail, we have:
1028
1029   In-process agent (producer):
1030
1031   - passes by `about_to_request_buffer_space' breakpoint/lock
1032
1033   - reads current token, extracts current trace buffer control index,
1034     and starts tentatively updating the rightmost one (0->1, 1->2,
1035     2->0).  Note that only one inferior thread is executing this code
1036     at any given time, due to an outer lock in the jump pads.
1037
1038   - updates counters, and tries to commit the token.
1039
1040   - passes by second `about_to_request_buffer_space' breakpoint/lock,
1041     leaving the sync region.
1042
1043   - checks if the update was effective.
1044
1045   - if trace buffer was found full, hits flush_trace_buffer
1046     breakpoint, and restarts later afterwards.
1047
1048   GDBserver (consumer):
1049
1050   - sets `about_to_request_buffer_space' breakpoint/lock.
1051
1052   - updates the token unconditionally, using the current buffer
1053     control index, since it knows that the IP agent always writes to
1054     the rightmost, and due to the breakpoint, at most one IP thread
1055     can try to update the trace buffer concurrently to GDBserver, so
1056     there will be no danger of trace buffer control index wrap making
1057     the IPA write to the same index as GDBserver.
1058
1059   - flushes the IP agent's trace buffer completely, and updates the
1060     current trace buffer control structure.  GDBserver *always* wins.
1061
1062   - removes the `about_to_request_buffer_space' breakpoint.
1063
1064 The token is stored in the `trace_buffer_ctrl_curr' variable.
1065 Internally, it's bits are defined as:
1066
1067  |-------------+-----+-------------+--------+-------------+--------------|
1068  | Bit offsets |  31 |   30 - 20   |   19   |    18-8     |     7-0      |
1069  |-------------+-----+-------------+--------+-------------+--------------|
1070  | What        | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1071  |-------------+-----+-------------+--------+-------------+--------------|
1072
1073  GSB  - GDBserver Stamp Bit
1074  PC   - Previous Counter
1075  CC   - Current Counter
1076  TBCI - Trace Buffer Control Index
1077
1078
1079 An IPA update of `trace_buffer_ctrl_curr' does:
1080
1081     - read CC from the current token, save as PC.
1082     - updates pointers
1083     - atomically tries to write PC+1,CC
1084
1085 A GDBserver update of `trace_buffer_ctrl_curr' does:
1086
1087     - reads PC and CC from the current token.
1088     - updates pointers
1089     - writes GSB,PC,CC
1090 */
1091
1092 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1093    for the counters described below.  The cleared bits are used to
1094    hold the index of the items of the `trace_buffer_ctrl' array that
1095    is "current".  */
1096 #define GDBSERVER_FLUSH_COUNT_MASK        0xfffffff0
1097
1098 /* `trace_buffer_ctrl_curr' contains two counters.  The `previous'
1099    counter, and the `current' counter.  */
1100
1101 #define GDBSERVER_FLUSH_COUNT_MASK_PREV   0x7ff00000
1102 #define GDBSERVER_FLUSH_COUNT_MASK_CURR   0x0007ff00
1103
1104 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1105    always stamps this bit as set.  */
1106 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1107
1108 #ifdef IN_PROCESS_AGENT
1109 IP_AGENT_EXPORT struct trace_buffer_control trace_buffer_ctrl[3];
1110 IP_AGENT_EXPORT unsigned int trace_buffer_ctrl_curr;
1111
1112 # define TRACE_BUFFER_CTRL_CURR \
1113   (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1114
1115 #else
1116
1117 /* The GDBserver side agent only needs one instance of this object, as
1118    it doesn't need to sync with itself.  Define it as array anyway so
1119    that the rest of the code base doesn't need to care for the
1120    difference.  */
1121 struct trace_buffer_control trace_buffer_ctrl[1];
1122 # define TRACE_BUFFER_CTRL_CURR 0
1123 #endif
1124
1125 /* These are convenience macros used to access the current trace
1126    buffer control in effect.  */
1127 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1128 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1129 #define trace_buffer_end_free \
1130   (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1131 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1132
1133
1134 /* Macro that returns a pointer to the first traceframe in the buffer.  */
1135
1136 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1137
1138 /* Macro that returns a pointer to the next traceframe in the buffer.
1139    If the computed location is beyond the wraparound point, subtract
1140    the offset of the wraparound.  */
1141
1142 #define NEXT_TRACEFRAME_1(TF) \
1143   (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1144
1145 #define NEXT_TRACEFRAME(TF) \
1146   ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF)  \
1147                           - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1148                              ? (trace_buffer_wrap - trace_buffer_lo)    \
1149                              : 0)))
1150
1151 /* The difference between these counters represents the total number
1152    of complete traceframes present in the trace buffer.  The IP agent
1153    writes to the write count, GDBserver writes to read count.  */
1154
1155 IP_AGENT_EXPORT unsigned int traceframe_write_count;
1156 IP_AGENT_EXPORT unsigned int traceframe_read_count;
1157
1158 /* Convenience macro.  */
1159
1160 #define traceframe_count \
1161   ((unsigned int) (traceframe_write_count - traceframe_read_count))
1162
1163 /* The count of all traceframes created in the current run, including
1164    ones that were discarded to make room.  */
1165
1166 IP_AGENT_EXPORT int traceframes_created;
1167
1168 #ifndef IN_PROCESS_AGENT
1169
1170 /* Read-only regions are address ranges whose contents don't change,
1171    and so can be read from target memory even while looking at a trace
1172    frame.  Without these, disassembly for instance will likely fail,
1173    because the program code is not usually collected into a trace
1174    frame.  This data structure does not need to be very complicated or
1175    particularly efficient, it's only going to be used occasionally,
1176    and only by some commands.  */
1177
1178 struct readonly_region
1179 {
1180   /* The bounds of the region.  */
1181   CORE_ADDR start, end;
1182
1183   /* Link to the next one.  */
1184   struct readonly_region *next;
1185 };
1186
1187 /* Linked list of readonly regions.  This list stays in effect from
1188    one tstart to the next.  */
1189
1190 static struct readonly_region *readonly_regions;
1191
1192 #endif
1193
1194 /* The global that controls tracing overall.  */
1195
1196 IP_AGENT_EXPORT int tracing;
1197
1198 #ifndef IN_PROCESS_AGENT
1199
1200 /* Controls whether tracing should continue after GDB disconnects.  */
1201
1202 int disconnected_tracing;
1203
1204 /* The reason for the last tracing run to have stopped.  We initialize
1205    to a distinct string so that GDB can distinguish between "stopped
1206    after running" and "stopped because never run" cases.  */
1207
1208 static const char *tracing_stop_reason = "tnotrun";
1209
1210 static int tracing_stop_tpnum;
1211
1212 #endif
1213
1214 /* Functions local to this file.  */
1215
1216 /* Base "class" for tracepoint type specific data to be passed down to
1217    collect_data_at_tracepoint.  */
1218 struct tracepoint_hit_ctx
1219 {
1220   enum tracepoint_type type;
1221 };
1222
1223 #ifdef IN_PROCESS_AGENT
1224
1225 /* Fast/jump tracepoint specific data to be passed down to
1226    collect_data_at_tracepoint.  */
1227 struct fast_tracepoint_ctx
1228 {
1229   struct tracepoint_hit_ctx base;
1230
1231   struct regcache regcache;
1232   int regcache_initted;
1233   unsigned char *regspace;
1234
1235   unsigned char *regs;
1236   struct tracepoint *tpoint;
1237 };
1238
1239 /* Static tracepoint specific data to be passed down to
1240    collect_data_at_tracepoint.  */
1241 struct static_tracepoint_ctx
1242 {
1243   struct tracepoint_hit_ctx base;
1244
1245   /* The regcache corresponding to the registers state at the time of
1246      the tracepoint hit.  Initialized lazily, from REGS.  */
1247   struct regcache regcache;
1248   int regcache_initted;
1249
1250   /* The buffer space REGCACHE above uses.  We use a separate buffer
1251      instead of letting the regcache malloc for both signal safety and
1252      performance reasons; this is allocated on the stack instead.  */
1253   unsigned char *regspace;
1254
1255   /* The register buffer as passed on by lttng/ust.  */
1256   struct registers *regs;
1257
1258   /* The "printf" formatter and the args the user passed to the marker
1259      call.  We use this to be able to collect "static trace data"
1260      ($_sdata).  */
1261   const char *fmt;
1262   va_list *args;
1263
1264   /* The GDB tracepoint matching the probed marker that was "hit".  */
1265   struct tracepoint *tpoint;
1266 };
1267
1268 #else
1269
1270 /* Static tracepoint specific data to be passed down to
1271    collect_data_at_tracepoint.  */
1272 struct trap_tracepoint_ctx
1273 {
1274   struct tracepoint_hit_ctx base;
1275
1276   struct regcache *regcache;
1277 };
1278
1279 #endif
1280
1281 #ifndef IN_PROCESS_AGENT
1282 static struct agent_expr *parse_agent_expr (char **actparm);
1283 static char *unparse_agent_expr (struct agent_expr *aexpr);
1284 #endif
1285 static enum eval_result_type eval_agent_expr (struct tracepoint_hit_ctx *ctx,
1286                                               struct traceframe *tframe,
1287                                               struct agent_expr *aexpr,
1288                                               ULONGEST *rslt);
1289
1290 static int agent_mem_read (struct traceframe *tframe,
1291                            unsigned char *to, CORE_ADDR from, ULONGEST len);
1292 static int agent_tsv_read (struct traceframe *tframe, int n);
1293
1294 #ifndef IN_PROCESS_AGENT
1295 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1296 static int traceframe_read_tsv (int num, LONGEST *val);
1297 #endif
1298
1299 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1300                                          struct tracepoint *tpoint);
1301
1302 #ifndef IN_PROCESS_AGENT
1303 static void clear_readonly_regions (void);
1304 static void clear_installed_tracepoints (void);
1305 #endif
1306
1307 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1308                                         CORE_ADDR stop_pc,
1309                                         struct tracepoint *tpoint);
1310 #ifndef IN_PROCESS_AGENT
1311 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1312                                   CORE_ADDR stop_pc,
1313                                   struct tracepoint *tpoint, int current_step);
1314 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1315                                           CORE_ADDR *jump_entry);
1316 #endif
1317 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1318                                      CORE_ADDR stop_pc,
1319                                      struct tracepoint *tpoint,
1320                                      struct traceframe *tframe,
1321                                      struct tracepoint_action *taction);
1322
1323 #ifndef IN_PROCESS_AGENT
1324 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1325 #endif
1326
1327 #if defined(__GNUC__)
1328 #  define memory_barrier() asm volatile ("" : : : "memory")
1329 #else
1330 #  define memory_barrier() do {} while (0)
1331 #endif
1332
1333 /* We only build the IPA if this builtin is supported, and there are
1334    no uses of this in GDBserver itself, so we're safe in defining this
1335    unconditionally.  */
1336 #define cmpxchg(mem, oldval, newval) \
1337   __sync_val_compare_and_swap (mem, oldval, newval)
1338
1339 /* The size in bytes of the buffer used to talk to the IPA helper
1340    thread.  */
1341 #define CMD_BUF_SIZE 1024
1342
1343 /* Record that an error occurred during expression evaluation.  */
1344
1345 static void
1346 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1347                          enum eval_result_type rtype)
1348 {
1349   trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1350                tpoint->number, paddress (tpoint->address), which, rtype);
1351
1352 #ifdef IN_PROCESS_AGENT
1353   /* Only record the first error we get.  */
1354   if (cmpxchg (&expr_eval_result,
1355                expr_eval_no_error,
1356                rtype) != expr_eval_no_error)
1357     return;
1358 #else
1359   if (expr_eval_result != expr_eval_no_error)
1360     return;
1361 #endif
1362
1363   error_tracepoint = tpoint;
1364 }
1365
1366 /* Trace buffer management.  */
1367
1368 static void
1369 clear_trace_buffer (void)
1370 {
1371   trace_buffer_start = trace_buffer_lo;
1372   trace_buffer_free = trace_buffer_lo;
1373   trace_buffer_end_free = trace_buffer_hi;
1374   trace_buffer_wrap = trace_buffer_hi;
1375   /* A traceframe with zeroed fields marks the end of trace data.  */
1376   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1377   ((struct traceframe *) trace_buffer_free)->data_size = 0;
1378   traceframe_read_count = traceframe_write_count = 0;
1379   traceframes_created = 0;
1380 }
1381
1382 #ifndef IN_PROCESS_AGENT
1383
1384 static void
1385 clear_inferior_trace_buffer (void)
1386 {
1387   CORE_ADDR ipa_trace_buffer_lo;
1388   CORE_ADDR ipa_trace_buffer_hi;
1389   struct traceframe ipa_traceframe = { 0 };
1390   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1391
1392   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1393                               &ipa_trace_buffer_lo);
1394   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1395                               &ipa_trace_buffer_hi);
1396
1397   ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1398   ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1399   ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1400   ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1401
1402   /* A traceframe with zeroed fields marks the end of trace data.  */
1403   write_inferior_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1404                          (unsigned char *) &ipa_trace_buffer_ctrl,
1405                          sizeof (ipa_trace_buffer_ctrl));
1406
1407   write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1408
1409   /* A traceframe with zeroed fields marks the end of trace data.  */
1410   write_inferior_memory (ipa_trace_buffer_lo,
1411                          (unsigned char *) &ipa_traceframe,
1412                          sizeof (ipa_traceframe));
1413
1414   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1415   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1416   write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1417 }
1418
1419 #endif
1420
1421 static void
1422 init_trace_buffer (unsigned char *buf, int bufsize)
1423 {
1424   trace_buffer_lo = buf;
1425   trace_buffer_hi = trace_buffer_lo + bufsize;
1426
1427   clear_trace_buffer ();
1428 }
1429
1430 #ifdef IN_PROCESS_AGENT
1431
1432 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
1433 about_to_request_buffer_space (void)
1434 {
1435   /* GDBserver places breakpoint here while it goes about to flush
1436      data at random times.  */
1437   UNKNOWN_SIDE_EFFECTS();
1438 }
1439
1440 #endif
1441
1442 /* Carve out a piece of the trace buffer, returning NULL in case of
1443    failure.  */
1444
1445 static void *
1446 trace_buffer_alloc (size_t amt)
1447 {
1448   unsigned char *rslt;
1449   struct trace_buffer_control *tbctrl;
1450   unsigned int curr;
1451 #ifdef IN_PROCESS_AGENT
1452   unsigned int prev, prev_filtered;
1453   unsigned int commit_count;
1454   unsigned int commit;
1455   unsigned int readout;
1456 #else
1457   struct traceframe *oldest;
1458   unsigned char *new_start;
1459 #endif
1460
1461   trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1462                (long) amt, (long) sizeof (struct traceframe));
1463
1464   /* Account for the EOB marker.  */
1465   amt += sizeof (struct traceframe);
1466
1467 #ifdef IN_PROCESS_AGENT
1468  again:
1469   memory_barrier ();
1470
1471   /* Read the current token and extract the index to try to write to,
1472      storing it in CURR.  */
1473   prev = trace_buffer_ctrl_curr;
1474   prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1475   curr = prev_filtered + 1;
1476   if (curr > 2)
1477     curr = 0;
1478
1479   about_to_request_buffer_space ();
1480
1481   /* Start out with a copy of the current state.  GDBserver may be
1482      midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1483      be able to commit anyway if that happens.  */
1484   trace_buffer_ctrl[curr]
1485     = trace_buffer_ctrl[prev_filtered];
1486   trace_debug ("trying curr=%u", curr);
1487 #else
1488   /* The GDBserver's agent doesn't need all that syncing, and always
1489      updates TCB 0 (there's only one, mind you).  */
1490   curr = 0;
1491 #endif
1492   tbctrl = &trace_buffer_ctrl[curr];
1493
1494   /* Offsets are easier to grok for debugging than raw addresses,
1495      especially for the small trace buffer sizes that are useful for
1496      testing.  */
1497   trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1498                curr,
1499                (int) (tbctrl->start - trace_buffer_lo),
1500                (int) (tbctrl->free - trace_buffer_lo),
1501                (int) (tbctrl->end_free - trace_buffer_lo),
1502                (int) (tbctrl->wrap - trace_buffer_lo),
1503                (int) (trace_buffer_hi - trace_buffer_lo));
1504
1505   /* The algorithm here is to keep trying to get a contiguous block of
1506      the requested size, possibly discarding older traceframes to free
1507      up space.  Since free space might come in one or two pieces,
1508      depending on whether discarded traceframes wrapped around at the
1509      high end of the buffer, we test both pieces after each
1510      discard.  */
1511   while (1)
1512     {
1513       /* First, if we have two free parts, try the upper one first.  */
1514       if (tbctrl->end_free < tbctrl->free)
1515         {
1516           if (tbctrl->free + amt <= trace_buffer_hi)
1517             /* We have enough in the upper part.  */
1518             break;
1519           else
1520             {
1521               /* Our high part of free space wasn't enough.  Give up
1522                  on it for now, set wraparound.  We will recover the
1523                  space later, if/when the wrapped-around traceframe is
1524                  discarded.  */
1525               trace_debug ("Upper part too small, setting wraparound");
1526               tbctrl->wrap = tbctrl->free;
1527               tbctrl->free = trace_buffer_lo;
1528             }
1529         }
1530
1531       /* The normal case.  */
1532       if (tbctrl->free + amt <= tbctrl->end_free)
1533         break;
1534
1535 #ifdef IN_PROCESS_AGENT
1536       /* The IP Agent's buffer is always circular.  It isn't used
1537          currently, but `circular_trace_buffer' could represent
1538          GDBserver's mode.  If we didn't find space, ask GDBserver to
1539          flush.  */
1540
1541       flush_trace_buffer ();
1542       memory_barrier ();
1543       if (tracing)
1544         {
1545           trace_debug ("gdbserver flushed buffer, retrying");
1546           goto again;
1547         }
1548
1549       /* GDBserver cancelled the tracing.  Bail out as well.  */
1550       return NULL;
1551 #else
1552       /* If we're here, then neither part is big enough, and
1553          non-circular trace buffers are now full.  */
1554       if (!circular_trace_buffer)
1555         {
1556           trace_debug ("Not enough space in the trace buffer");
1557           return NULL;
1558         }
1559
1560       trace_debug ("Need more space in the trace buffer");
1561
1562       /* If we have a circular buffer, we can try discarding the
1563          oldest traceframe and see if that helps.  */
1564       oldest = FIRST_TRACEFRAME ();
1565       if (oldest->tpnum == 0)
1566         {
1567           /* Not good; we have no traceframes to free.  Perhaps we're
1568              asking for a block that is larger than the buffer?  In
1569              any case, give up.  */
1570           trace_debug ("No traceframes to discard");
1571           return NULL;
1572         }
1573
1574       /* We don't run this code in the in-process agent currently.
1575          E.g., we could leave the in-process agent in autonomous
1576          circular mode if we only have fast tracepoints.  If we do
1577          that, then this bit becomes racy with GDBserver, which also
1578          writes to this counter.  */
1579       --traceframe_write_count;
1580
1581       new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1582       /* If we freed the traceframe that wrapped around, go back
1583          to the non-wrap case.  */
1584       if (new_start < tbctrl->start)
1585         {
1586           trace_debug ("Discarding past the wraparound");
1587           tbctrl->wrap = trace_buffer_hi;
1588         }
1589       tbctrl->start = new_start;
1590       tbctrl->end_free = tbctrl->start;
1591
1592       trace_debug ("Discarded a traceframe\n"
1593                    "Trace buffer [%d], start=%d free=%d "
1594                    "endfree=%d wrap=%d hi=%d",
1595                    curr,
1596                    (int) (tbctrl->start - trace_buffer_lo),
1597                    (int) (tbctrl->free - trace_buffer_lo),
1598                    (int) (tbctrl->end_free - trace_buffer_lo),
1599                    (int) (tbctrl->wrap - trace_buffer_lo),
1600                    (int) (trace_buffer_hi - trace_buffer_lo));
1601
1602       /* Now go back around the loop.  The discard might have resulted
1603          in either one or two pieces of free space, so we want to try
1604          both before freeing any more traceframes.  */
1605 #endif
1606     }
1607
1608   /* If we get here, we know we can provide the asked-for space.  */
1609
1610   rslt = tbctrl->free;
1611
1612   /* Adjust the request back down, now that we know we have space for
1613      the marker, but don't commit to AMT yet, we may still need to
1614      restart the operation if GDBserver touches the trace buffer
1615      (obviously only important in the in-process agent's version).  */
1616   tbctrl->free += (amt - sizeof (struct traceframe));
1617
1618   /* Or not.  If GDBserver changed the trace buffer behind our back,
1619      we get to restart a new allocation attempt.  */
1620
1621 #ifdef IN_PROCESS_AGENT
1622   /* Build the tentative token.  */
1623   commit_count = (((prev & 0x0007ff00) + 0x100) & 0x0007ff00);
1624   commit = (((prev & 0x0007ff00) << 12)
1625             | commit_count
1626             | curr);
1627
1628   /* Try to commit it.  */
1629   readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1630   if (readout != prev)
1631     {
1632       trace_debug ("GDBserver has touched the trace buffer, restarting."
1633                    " (prev=%08x, commit=%08x, readout=%08x)",
1634                    prev, commit, readout);
1635       goto again;
1636     }
1637
1638   /* Hold your horses here.  Even if that change was committed,
1639      GDBserver could come in, and clobber it.  We need to hold to be
1640      able to tell if GDBserver clobbers before or after we committed
1641      the change.  Whenever GDBserver goes about touching the IPA
1642      buffer, it sets a breakpoint in this routine, so we have a sync
1643      point here.  */
1644   about_to_request_buffer_space ();
1645
1646   /* Check if the change has been effective, even if GDBserver stopped
1647      us at the breakpoint.  */
1648
1649   {
1650     unsigned int refetch;
1651
1652     memory_barrier ();
1653
1654     refetch = trace_buffer_ctrl_curr;
1655
1656     if ((refetch == commit
1657          || ((refetch & 0x7ff00000) >> 12) == commit_count))
1658       {
1659         /* effective */
1660         trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1661                      "readout=%08x, refetch=%08x)",
1662                      prev, commit, readout, refetch);
1663       }
1664     else
1665       {
1666         trace_debug ("GDBserver has touched the trace buffer, not effective."
1667                      " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1668                      prev, commit, readout, refetch);
1669         goto again;
1670       }
1671   }
1672 #endif
1673
1674   /* We have a new piece of the trace buffer.  Hurray!  */
1675
1676   /* Add an EOB marker just past this allocation.  */
1677   ((struct traceframe *) tbctrl->free)->tpnum = 0;
1678   ((struct traceframe *) tbctrl->free)->data_size = 0;
1679
1680   /* Adjust the request back down, now that we know we have space for
1681      the marker.  */
1682   amt -= sizeof (struct traceframe);
1683
1684   if (debug_threads)
1685     {
1686       trace_debug ("Allocated %d bytes", (int) amt);
1687       trace_debug ("Trace buffer [%d] start=%d free=%d "
1688                    "endfree=%d wrap=%d hi=%d",
1689                    curr,
1690                    (int) (tbctrl->start - trace_buffer_lo),
1691                    (int) (tbctrl->free - trace_buffer_lo),
1692                    (int) (tbctrl->end_free - trace_buffer_lo),
1693                    (int) (tbctrl->wrap - trace_buffer_lo),
1694                    (int) (trace_buffer_hi - trace_buffer_lo));
1695     }
1696
1697   return rslt;
1698 }
1699
1700 #ifndef IN_PROCESS_AGENT
1701
1702 /* Return the total free space.  This is not necessarily the largest
1703    block we can allocate, because of the two-part case.  */
1704
1705 static int
1706 free_space (void)
1707 {
1708   if (trace_buffer_free <= trace_buffer_end_free)
1709     return trace_buffer_end_free - trace_buffer_free;
1710   else
1711     return ((trace_buffer_end_free - trace_buffer_lo)
1712             + (trace_buffer_hi - trace_buffer_free));
1713 }
1714
1715 /* An 'S' in continuation packets indicates remainder are for
1716    while-stepping.  */
1717
1718 static int seen_step_action_flag;
1719
1720 /* Create a tracepoint (location) with given number and address.  */
1721
1722 static struct tracepoint *
1723 add_tracepoint (int num, CORE_ADDR addr)
1724 {
1725   struct tracepoint *tpoint;
1726
1727   tpoint = xmalloc (sizeof (struct tracepoint));
1728   tpoint->number = num;
1729   tpoint->address = addr;
1730   tpoint->numactions = 0;
1731   tpoint->actions = NULL;
1732   tpoint->actions_str = NULL;
1733   tpoint->cond = NULL;
1734   tpoint->num_step_actions = 0;
1735   tpoint->step_actions = NULL;
1736   tpoint->step_actions_str = NULL;
1737   /* Start all off as regular (slow) tracepoints.  */
1738   tpoint->type = trap_tracepoint;
1739   tpoint->orig_size = -1;
1740   tpoint->source_strings = NULL;
1741   tpoint->compiled_cond = 0;
1742   tpoint->handle = NULL;
1743   tpoint->next = NULL;
1744
1745   if (!last_tracepoint)
1746     tracepoints = tpoint;
1747   else
1748     last_tracepoint->next = tpoint;
1749   last_tracepoint = tpoint;
1750
1751   seen_step_action_flag = 0;
1752
1753   return tpoint;
1754 }
1755
1756 #ifndef IN_PROCESS_AGENT
1757
1758 /* Return the tracepoint with the given number and address, or NULL.  */
1759
1760 static struct tracepoint *
1761 find_tracepoint (int id, CORE_ADDR addr)
1762 {
1763   struct tracepoint *tpoint;
1764
1765   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1766     if (tpoint->number == id && tpoint->address == addr)
1767       return tpoint;
1768
1769   return NULL;
1770 }
1771
1772 /* There may be several tracepoints with the same number (because they
1773    are "locations", in GDB parlance); return the next one after the
1774    given tracepoint, or search from the beginning of the list if the
1775    first argument is NULL.  */
1776
1777 static struct tracepoint *
1778 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1779 {
1780   struct tracepoint *tpoint;
1781
1782   if (prev_tp)
1783     tpoint = prev_tp->next;
1784   else
1785     tpoint = tracepoints;
1786   for (; tpoint; tpoint = tpoint->next)
1787     if (tpoint->number == num)
1788       return tpoint;
1789
1790   return NULL;
1791 }
1792
1793 #endif
1794
1795 static char *
1796 save_string (const char *str, size_t len)
1797 {
1798   char *s;
1799
1800   s = xmalloc (len + 1);
1801   memcpy (s, str, len);
1802   s[len] = '\0';
1803
1804   return s;
1805 }
1806
1807 /* Append another action to perform when the tracepoint triggers.  */
1808
1809 static void
1810 add_tracepoint_action (struct tracepoint *tpoint, char *packet)
1811 {
1812   char *act;
1813
1814   if (*packet == 'S')
1815     {
1816       seen_step_action_flag = 1;
1817       ++packet;
1818     }
1819
1820   act = packet;
1821
1822   while (*act)
1823     {
1824       char *act_start = act;
1825       struct tracepoint_action *action = NULL;
1826
1827       switch (*act)
1828         {
1829         case 'M':
1830           {
1831             struct collect_memory_action *maction;
1832             ULONGEST basereg;
1833             int is_neg;
1834
1835             maction = xmalloc (sizeof *maction);
1836             maction->base.type = *act;
1837             action = &maction->base;
1838
1839             ++act;
1840             is_neg = (*act == '-');
1841             if (*act == '-')
1842               ++act;
1843             act = unpack_varlen_hex (act, &basereg);
1844             ++act;
1845             act = unpack_varlen_hex (act, &maction->addr);
1846             ++act;
1847             act = unpack_varlen_hex (act, &maction->len);
1848             maction->basereg = (is_neg
1849                                 ? - (int) basereg
1850                                 : (int) basereg);
1851             trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1852                          pulongest (maction->len),
1853                          paddress (maction->addr), maction->basereg);
1854             break;
1855           }
1856         case 'R':
1857           {
1858             struct collect_registers_action *raction;
1859
1860             raction = xmalloc (sizeof *raction);
1861             raction->base.type = *act;
1862             action = &raction->base;
1863
1864             trace_debug ("Want to collect registers");
1865             ++act;
1866             /* skip past hex digits of mask for now */
1867             while (isxdigit(*act))
1868               ++act;
1869             break;
1870           }
1871         case 'L':
1872           {
1873             struct collect_static_trace_data_action *raction;
1874
1875             raction = xmalloc (sizeof *raction);
1876             raction->base.type = *act;
1877             action = &raction->base;
1878
1879             trace_debug ("Want to collect static trace data");
1880             ++act;
1881             break;
1882           }
1883         case 'S':
1884           trace_debug ("Unexpected step action, ignoring");
1885           ++act;
1886           break;
1887         case 'X':
1888           {
1889             struct eval_expr_action *xaction;
1890
1891             xaction = xmalloc (sizeof (*xaction));
1892             xaction->base.type = *act;
1893             action = &xaction->base;
1894
1895             trace_debug ("Want to evaluate expression");
1896             xaction->expr = parse_agent_expr (&act);
1897             break;
1898           }
1899         default:
1900           trace_debug ("unknown trace action '%c', ignoring...", *act);
1901           break;
1902         case '-':
1903           break;
1904         }
1905
1906       if (action == NULL)
1907         break;
1908
1909       if (seen_step_action_flag)
1910         {
1911           tpoint->num_step_actions++;
1912
1913           tpoint->step_actions
1914             = xrealloc (tpoint->step_actions,
1915                         (sizeof (*tpoint->step_actions)
1916                          * tpoint->num_step_actions));
1917           tpoint->step_actions_str
1918             = xrealloc (tpoint->step_actions_str,
1919                         (sizeof (*tpoint->step_actions_str)
1920                          * tpoint->num_step_actions));
1921           tpoint->step_actions[tpoint->num_step_actions - 1] = action;
1922           tpoint->step_actions_str[tpoint->num_step_actions - 1]
1923             = save_string (act_start, act - act_start);
1924         }
1925       else
1926         {
1927           tpoint->numactions++;
1928           tpoint->actions
1929             = xrealloc (tpoint->actions,
1930                         sizeof (*tpoint->actions) * tpoint->numactions);
1931           tpoint->actions_str
1932             = xrealloc (tpoint->actions_str,
1933                         sizeof (*tpoint->actions_str) * tpoint->numactions);
1934           tpoint->actions[tpoint->numactions - 1] = action;
1935           tpoint->actions_str[tpoint->numactions - 1]
1936             = save_string (act_start, act - act_start);
1937         }
1938     }
1939 }
1940
1941 #endif
1942
1943 /* Find or create a trace state variable with the given number.  */
1944
1945 static struct trace_state_variable *
1946 get_trace_state_variable (int num)
1947 {
1948   struct trace_state_variable *tsv;
1949
1950 #ifdef IN_PROCESS_AGENT
1951   /* Search for an existing variable.  */
1952   for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
1953     if (tsv->number == num)
1954       return tsv;
1955 #endif
1956
1957   /* Search for an existing variable.  */
1958   for (tsv = trace_state_variables; tsv; tsv = tsv->next)
1959     if (tsv->number == num)
1960       return tsv;
1961
1962   return NULL;
1963 }
1964
1965 /* Find or create a trace state variable with the given number.  */
1966
1967 static struct trace_state_variable *
1968 create_trace_state_variable (int num, int gdb)
1969 {
1970   struct trace_state_variable *tsv;
1971
1972   tsv = get_trace_state_variable (num);
1973   if (tsv != NULL)
1974     return tsv;
1975
1976   /* Create a new variable.  */
1977   tsv = xmalloc (sizeof (struct trace_state_variable));
1978   tsv->number = num;
1979   tsv->initial_value = 0;
1980   tsv->value = 0;
1981   tsv->getter = NULL;
1982   tsv->name = NULL;
1983 #ifdef IN_PROCESS_AGENT
1984   if (!gdb)
1985     {
1986       tsv->next = alloced_trace_state_variables;
1987       alloced_trace_state_variables = tsv;
1988     }
1989   else
1990 #endif
1991     {
1992       tsv->next = trace_state_variables;
1993       trace_state_variables = tsv;
1994     }
1995   return tsv;
1996 }
1997
1998 IP_AGENT_EXPORT LONGEST
1999 get_trace_state_variable_value (int num)
2000 {
2001   struct trace_state_variable *tsv;
2002
2003   tsv = get_trace_state_variable (num);
2004
2005   if (!tsv)
2006     {
2007       trace_debug ("No trace state variable %d, skipping value get", num);
2008       return 0;
2009     }
2010
2011   /* Call a getter function if we have one.  While it's tempting to
2012      set up something to only call the getter once per tracepoint hit,
2013      it could run afoul of thread races. Better to let the getter
2014      handle it directly, if necessary to worry about it.  */
2015   if (tsv->getter)
2016     tsv->value = (tsv->getter) ();
2017
2018   trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2019                num, plongest (tsv->value));
2020
2021   return tsv->value;
2022 }
2023
2024 IP_AGENT_EXPORT void
2025 set_trace_state_variable_value (int num, LONGEST val)
2026 {
2027   struct trace_state_variable *tsv;
2028
2029   tsv = get_trace_state_variable (num);
2030
2031   if (!tsv)
2032     {
2033       trace_debug ("No trace state variable %d, skipping value set", num);
2034       return;
2035     }
2036
2037   tsv->value = val;
2038 }
2039
2040 static void
2041 set_trace_state_variable_name (int num, const char *name)
2042 {
2043   struct trace_state_variable *tsv;
2044
2045   tsv = get_trace_state_variable (num);
2046
2047   if (!tsv)
2048     {
2049       trace_debug ("No trace state variable %d, skipping name set", num);
2050       return;
2051     }
2052
2053   tsv->name = (char *) name;
2054 }
2055
2056 static void
2057 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2058 {
2059   struct trace_state_variable *tsv;
2060
2061   tsv = get_trace_state_variable (num);
2062
2063   if (!tsv)
2064     {
2065       trace_debug ("No trace state variable %d, skipping getter set", num);
2066       return;
2067     }
2068
2069   tsv->getter = getter;
2070 }
2071
2072 /* Add a raw traceframe for the given tracepoint.  */
2073
2074 static struct traceframe *
2075 add_traceframe (struct tracepoint *tpoint)
2076 {
2077   struct traceframe *tframe;
2078
2079   tframe = trace_buffer_alloc (sizeof (struct traceframe));
2080
2081   if (tframe == NULL)
2082     return NULL;
2083
2084   tframe->tpnum = tpoint->number;
2085   tframe->data_size = 0;
2086
2087   return tframe;
2088 }
2089
2090 /* Add a block to the traceframe currently being worked on.  */
2091
2092 static unsigned char *
2093 add_traceframe_block (struct traceframe *tframe, int amt)
2094 {
2095   unsigned char *block;
2096
2097   if (!tframe)
2098     return NULL;
2099
2100   block = trace_buffer_alloc (amt);
2101
2102   if (!block)
2103     return NULL;
2104
2105   tframe->data_size += amt;
2106
2107   return block;
2108 }
2109
2110 /* Flag that the current traceframe is finished.  */
2111
2112 static void
2113 finish_traceframe (struct traceframe *tframe)
2114 {
2115   ++traceframe_write_count;
2116   ++traceframes_created;
2117 }
2118
2119 #ifndef IN_PROCESS_AGENT
2120
2121 /* Given a traceframe number NUM, find the NUMth traceframe in the
2122    buffer.  */
2123
2124 static struct traceframe *
2125 find_traceframe (int num)
2126 {
2127   struct traceframe *tframe;
2128   int tfnum = 0;
2129
2130   for (tframe = FIRST_TRACEFRAME ();
2131        tframe->tpnum != 0;
2132        tframe = NEXT_TRACEFRAME (tframe))
2133     {
2134       if (tfnum == num)
2135         return tframe;
2136       ++tfnum;
2137     }
2138
2139   return NULL;
2140 }
2141
2142 static CORE_ADDR
2143 get_traceframe_address (struct traceframe *tframe)
2144 {
2145   CORE_ADDR addr;
2146   struct tracepoint *tpoint;
2147
2148   addr = traceframe_get_pc (tframe);
2149
2150   if (addr)
2151     return addr;
2152
2153   /* Fallback strategy, will be incorrect for while-stepping frames
2154      and multi-location tracepoints.  */
2155   tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2156   return tpoint->address;
2157 }
2158
2159 /* Search for the next traceframe whose address is inside or outside
2160    the given range.  */
2161
2162 static struct traceframe *
2163 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2164                                int *tfnump)
2165 {
2166   struct traceframe *tframe;
2167   CORE_ADDR tfaddr;
2168
2169   *tfnump = current_traceframe + 1;
2170   tframe = find_traceframe (*tfnump);
2171   /* The search is not supposed to wrap around.  */
2172   if (!tframe)
2173     {
2174       *tfnump = -1;
2175       return NULL;
2176     }
2177
2178   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2179     {
2180       tfaddr = get_traceframe_address (tframe);
2181       if (inside_p
2182           ? (lo <= tfaddr && tfaddr <= hi)
2183           : (lo > tfaddr || tfaddr > hi))
2184         return tframe;
2185       ++*tfnump;
2186     }
2187
2188   *tfnump = -1;
2189   return NULL;
2190 }
2191
2192 /* Search for the next traceframe recorded by the given tracepoint.
2193    Note that for multi-location tracepoints, this will find whatever
2194    location appears first.  */
2195
2196 static struct traceframe *
2197 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2198 {
2199   struct traceframe *tframe;
2200
2201   *tfnump = current_traceframe + 1;
2202   tframe = find_traceframe (*tfnump);
2203   /* The search is not supposed to wrap around.  */
2204   if (!tframe)
2205     {
2206       *tfnump = -1;
2207       return NULL;
2208     }
2209
2210   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2211     {
2212       if (tframe->tpnum == num)
2213         return tframe;
2214       ++*tfnump;
2215     }
2216
2217   *tfnump = -1;
2218   return NULL;
2219 }
2220
2221 #endif
2222
2223 #ifndef IN_PROCESS_AGENT
2224
2225 /* Clear all past trace state.  */
2226
2227 static void
2228 cmd_qtinit (char *packet)
2229 {
2230   struct trace_state_variable *tsv, *prev, *next;
2231
2232   /* Make sure we don't try to read from a trace frame.  */
2233   current_traceframe = -1;
2234
2235   trace_debug ("Initializing the trace");
2236
2237   clear_installed_tracepoints ();
2238   clear_readonly_regions ();
2239
2240   tracepoints = NULL;
2241   last_tracepoint = NULL;
2242
2243   /* Clear out any leftover trace state variables.  Ones with target
2244      defined getters should be kept however.  */
2245   prev = NULL;
2246   tsv = trace_state_variables;
2247   while (tsv)
2248     {
2249       trace_debug ("Looking at var %d", tsv->number);
2250       if (tsv->getter == NULL)
2251         {
2252           next = tsv->next;
2253           if (prev)
2254             prev->next = next;
2255           else
2256             trace_state_variables = next;
2257           trace_debug ("Deleting var %d", tsv->number);
2258           free (tsv);
2259           tsv = next;
2260         }
2261       else
2262         {
2263           prev = tsv;
2264           tsv = tsv->next;
2265         }
2266     }
2267
2268   clear_trace_buffer ();
2269   clear_inferior_trace_buffer ();
2270
2271   write_ok (packet);
2272 }
2273
2274 /* Unprobe the UST marker at ADDRESS.  */
2275
2276 static void
2277 unprobe_marker_at (CORE_ADDR address)
2278 {
2279   char cmd[CMD_BUF_SIZE];
2280
2281   sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
2282   run_inferior_command (cmd);
2283 }
2284
2285 /* Restore the program to its pre-tracing state.  This routine may be called
2286    in error situations, so it needs to be careful about only restoring
2287    from known-valid bits.  */
2288
2289 static void
2290 clear_installed_tracepoints (void)
2291 {
2292   struct tracepoint *tpoint;
2293   struct tracepoint *prev_stpoint;
2294
2295   pause_all (1);
2296   cancel_breakpoints ();
2297
2298   prev_stpoint = NULL;
2299
2300   /* Restore any bytes overwritten by tracepoints.  */
2301   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2302     {
2303       if (!tpoint->enabled)
2304         continue;
2305
2306       /* Catch the case where we might try to remove a tracepoint that
2307          was never actually installed.  */
2308       if (tpoint->handle == NULL)
2309         {
2310           trace_debug ("Tracepoint %d at 0x%s was "
2311                        "never installed, nothing to clear",
2312                        tpoint->number, paddress (tpoint->address));
2313           continue;
2314         }
2315
2316       switch (tpoint->type)
2317         {
2318         case trap_tracepoint:
2319           delete_breakpoint (tpoint->handle);
2320           break;
2321         case fast_tracepoint:
2322           delete_fast_tracepoint_jump (tpoint->handle);
2323           break;
2324         case static_tracepoint:
2325           if (prev_stpoint != NULL
2326               && prev_stpoint->address == tpoint->address)
2327             /* Nothing to do.  We already unprobed a tracepoint set at
2328                this marker address (and there can only be one probe
2329                per marker).  */
2330             ;
2331           else
2332             {
2333               unprobe_marker_at (tpoint->address);
2334               prev_stpoint = tpoint;
2335             }
2336           break;
2337         }
2338
2339       tpoint->handle = NULL;
2340     }
2341
2342   unpause_all (1);
2343 }
2344
2345 /* Parse a packet that defines a tracepoint.  */
2346
2347 static void
2348 cmd_qtdp (char *own_buf)
2349 {
2350   int tppacket;
2351   ULONGEST num;
2352   ULONGEST addr;
2353   ULONGEST count;
2354   struct tracepoint *tpoint;
2355   char *actparm;
2356   char *packet = own_buf;
2357
2358   packet += strlen ("QTDP:");
2359
2360   /* A hyphen at the beginning marks a packet specifying actions for a
2361      tracepoint already supplied.  */
2362   tppacket = 1;
2363   if (*packet == '-')
2364     {
2365       tppacket = 0;
2366       ++packet;
2367     }
2368   packet = unpack_varlen_hex (packet, &num);
2369   ++packet; /* skip a colon */
2370   packet = unpack_varlen_hex (packet, &addr);
2371   ++packet; /* skip a colon */
2372
2373   /* See if we already have this tracepoint.  */
2374   tpoint = find_tracepoint (num, addr);
2375
2376   if (tppacket)
2377     {
2378       /* Duplicate tracepoints are never allowed.  */
2379       if (tpoint)
2380         {
2381           trace_debug ("Tracepoint error: tracepoint %d"
2382                        " at 0x%s already exists",
2383                        (int) num, paddress (addr));
2384           write_enn (own_buf);
2385           return;
2386         }
2387
2388       tpoint = add_tracepoint (num, addr);
2389
2390       tpoint->enabled = (*packet == 'E');
2391       ++packet; /* skip 'E' */
2392       ++packet; /* skip a colon */
2393       packet = unpack_varlen_hex (packet, &count);
2394       tpoint->step_count = count;
2395       ++packet; /* skip a colon */
2396       packet = unpack_varlen_hex (packet, &count);
2397       tpoint->pass_count = count;
2398       /* See if we have any of the additional optional fields.  */
2399       while (*packet == ':')
2400         {
2401           ++packet;
2402           if (*packet == 'F')
2403             {
2404               tpoint->type = fast_tracepoint;
2405               ++packet;
2406               packet = unpack_varlen_hex (packet, &count);
2407               tpoint->orig_size = count;
2408             }
2409           else if (*packet == 'S')
2410             {
2411               tpoint->type = static_tracepoint;
2412               ++packet;
2413             }
2414           else if (*packet == 'X')
2415             {
2416               actparm = (char *) packet;
2417               tpoint->cond = parse_agent_expr (&actparm);
2418               packet = actparm;
2419             }
2420           else if (*packet == '-')
2421             break;
2422           else if (*packet == '\0')
2423             break;
2424           else
2425             trace_debug ("Unknown optional tracepoint field");
2426         }
2427       if (*packet == '-')
2428         trace_debug ("Also has actions\n");
2429
2430       trace_debug ("Defined %stracepoint %d at 0x%s, "
2431                    "enabled %d step %ld pass %ld",
2432                    tpoint->type == fast_tracepoint ? "fast "
2433                    : "",
2434                    tpoint->number, paddress (tpoint->address), tpoint->enabled,
2435                    tpoint->step_count, tpoint->pass_count);
2436     }
2437   else if (tpoint)
2438     add_tracepoint_action (tpoint, packet);
2439   else
2440     {
2441       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2442                    (int) num, paddress (addr));
2443       write_enn (own_buf);
2444       return;
2445     }
2446
2447   write_ok (own_buf);
2448 }
2449
2450 static void
2451 cmd_qtdpsrc (char *own_buf)
2452 {
2453   ULONGEST num, addr, start, slen;
2454   struct tracepoint *tpoint;
2455   char *packet = own_buf;
2456   char *saved, *srctype, *src;
2457   size_t nbytes;
2458   struct source_string *last, *newlast;
2459
2460   packet += strlen ("QTDPsrc:");
2461
2462   packet = unpack_varlen_hex (packet, &num);
2463   ++packet; /* skip a colon */
2464   packet = unpack_varlen_hex (packet, &addr);
2465   ++packet; /* skip a colon */
2466
2467   /* See if we already have this tracepoint.  */
2468   tpoint = find_tracepoint (num, addr);
2469
2470   if (!tpoint)
2471     {
2472       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2473                    (int) num, paddress (addr));
2474       write_enn (own_buf);
2475       return;
2476     }
2477
2478   saved = packet;
2479   packet = strchr (packet, ':');
2480   srctype = xmalloc (packet - saved + 1);
2481   memcpy (srctype, saved, packet - saved);
2482   srctype[packet - saved] = '\0';
2483   ++packet;
2484   packet = unpack_varlen_hex (packet, &start);
2485   ++packet; /* skip a colon */
2486   packet = unpack_varlen_hex (packet, &slen);
2487   ++packet; /* skip a colon */
2488   src = xmalloc (slen + 1);
2489   nbytes = unhexify (src, packet, strlen (packet) / 2);
2490   src[nbytes] = '\0';
2491
2492   newlast = xmalloc (sizeof (struct source_string));
2493   newlast->type = srctype;
2494   newlast->str = src;
2495   newlast->next = NULL;
2496   /* Always add a source string to the end of the list;
2497      this keeps sequences of actions/commands in the right
2498      order.  */
2499   if (tpoint->source_strings)
2500     {
2501       for (last = tpoint->source_strings; last->next; last = last->next)
2502         ;
2503       last->next = newlast;
2504     }
2505   else
2506     tpoint->source_strings = newlast;
2507
2508   write_ok (own_buf);
2509 }
2510
2511 static void
2512 cmd_qtdv (char *own_buf)
2513 {
2514   ULONGEST num, val, builtin;
2515   char *varname;
2516   size_t nbytes;
2517   struct trace_state_variable *tsv;
2518   char *packet = own_buf;
2519
2520   packet += strlen ("QTDV:");
2521
2522   packet = unpack_varlen_hex (packet, &num);
2523   ++packet; /* skip a colon */
2524   packet = unpack_varlen_hex (packet, &val);
2525   ++packet; /* skip a colon */
2526   packet = unpack_varlen_hex (packet, &builtin);
2527   ++packet; /* skip a colon */
2528
2529   nbytes = strlen (packet) / 2;
2530   varname = xmalloc (nbytes + 1);
2531   nbytes = unhexify (varname, packet, nbytes);
2532   varname[nbytes] = '\0';
2533
2534   tsv = create_trace_state_variable (num, 1);
2535   tsv->initial_value = (LONGEST) val;
2536   tsv->name = varname;
2537
2538   set_trace_state_variable_value (num, (LONGEST) val);
2539
2540   write_ok (own_buf);
2541 }
2542
2543 static void
2544 cmd_qtv (char *own_buf)
2545 {
2546   ULONGEST num;
2547   LONGEST val;
2548   int err;
2549   char *packet = own_buf;
2550
2551   packet += strlen ("qTV:");
2552   packet = unpack_varlen_hex (packet, &num);
2553
2554   if (current_traceframe >= 0)
2555     {
2556       err = traceframe_read_tsv ((int) num, &val);
2557       if (err)
2558         {
2559           strcpy (own_buf, "U");
2560           return;
2561         }
2562     }
2563   /* Only make tsv's be undefined before the first trace run.  After a
2564      trace run is over, the user might want to see the last value of
2565      the tsv, and it might not be available in a traceframe.  */
2566   else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2567     {
2568       strcpy (own_buf, "U");
2569       return;
2570     }
2571   else
2572     val = get_trace_state_variable_value (num);
2573
2574   sprintf (own_buf, "V%s", phex_nz (val, 0));
2575 }
2576
2577 /* Clear out the list of readonly regions.  */
2578
2579 static void
2580 clear_readonly_regions (void)
2581 {
2582   struct readonly_region *roreg;
2583
2584   while (readonly_regions)
2585     {
2586       roreg = readonly_regions;
2587       readonly_regions = readonly_regions->next;
2588       free (roreg);
2589     }
2590 }
2591
2592 /* Parse the collection of address ranges whose contents GDB believes
2593    to be unchanging and so can be read directly from target memory
2594    even while looking at a traceframe.  */
2595
2596 static void
2597 cmd_qtro (char *own_buf)
2598 {
2599   ULONGEST start, end;
2600   struct readonly_region *roreg;
2601   char *packet = own_buf;
2602
2603   trace_debug ("Want to mark readonly regions");
2604
2605   clear_readonly_regions ();
2606
2607   packet += strlen ("QTro");
2608
2609   while (*packet == ':')
2610     {
2611       ++packet;  /* skip a colon */
2612       packet = unpack_varlen_hex (packet, &start);
2613       ++packet;  /* skip a comma */
2614       packet = unpack_varlen_hex (packet, &end);
2615       roreg = xmalloc (sizeof (struct readonly_region));
2616       roreg->start = start;
2617       roreg->end = end;
2618       roreg->next = readonly_regions;
2619       readonly_regions = roreg;
2620       trace_debug ("Added readonly region from 0x%s to 0x%s",
2621                    paddress (roreg->start), paddress (roreg->end));
2622     }
2623
2624   write_ok (own_buf);
2625 }
2626
2627 /* Test to see if the given range is in our list of readonly ranges.
2628    We only test for being entirely within a range, GDB is not going to
2629    send a single memory packet that spans multiple regions.  */
2630
2631 int
2632 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2633 {
2634   struct readonly_region *roreg;
2635
2636   for (roreg = readonly_regions; roreg; roreg = roreg->next)
2637     if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2638       return 1;
2639
2640   return 0;
2641 }
2642
2643 /* The maximum size of a jump pad entry.  */
2644 static const int max_jump_pad_size = 0x100;
2645
2646 static CORE_ADDR gdb_jump_pad_head;
2647
2648 /* Return the address of the next free jump space.  */
2649
2650 static CORE_ADDR
2651 get_jump_space_head (void)
2652 {
2653   if (gdb_jump_pad_head == 0)
2654     {
2655       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2656                                       &gdb_jump_pad_head))
2657         fatal ("error extracting jump_pad_buffer");
2658     }
2659
2660   return gdb_jump_pad_head;
2661 }
2662
2663 /* Reserve USED bytes from the jump space.  */
2664
2665 static void
2666 claim_jump_space (ULONGEST used)
2667 {
2668   trace_debug ("claim_jump_space reserves %s bytes at %s",
2669                pulongest (used), paddress (gdb_jump_pad_head));
2670   gdb_jump_pad_head += used;
2671 }
2672
2673 /* Sort tracepoints by PC, using a bubble sort.  */
2674
2675 static void
2676 sort_tracepoints (void)
2677 {
2678   struct tracepoint *lst, *tmp, *prev = NULL;
2679   int i, j, n = 0;
2680
2681   if (tracepoints == NULL)
2682     return;
2683
2684   /* Count nodes.  */
2685   for (tmp = tracepoints; tmp->next; tmp = tmp->next)
2686     n++;
2687
2688   for (i = 0; i < n - 1; i++)
2689     for (j = 0, lst = tracepoints;
2690          lst && lst->next && (j <= n - 1 - i);
2691          j++)
2692       {
2693         /* If we're at beginning, the start node is the prev
2694            node.  */
2695         if (j == 0)
2696           prev = lst;
2697
2698         /* Compare neighbors.  */
2699         if (lst->next->address < lst->address)
2700           {
2701             struct tracepoint *p;
2702
2703             /* Swap'em.  */
2704             tmp = (lst->next ? lst->next->next : NULL);
2705
2706             if (j == 0 && prev == tracepoints)
2707               tracepoints = lst->next;
2708
2709             p = lst->next;
2710             prev->next = lst->next;
2711             lst->next->next = lst;
2712             lst->next = tmp;
2713             prev = p;
2714           }
2715         else
2716           {
2717             lst = lst->next;
2718             /* Keep track of the previous node.  We need it if we need
2719                to swap nodes.  */
2720             if (j != 0)
2721               prev = prev->next;
2722           }
2723       }
2724 }
2725
2726 /* Ask the IPA to probe the marker at ADDRESS.  Returns -1 if running
2727    the command fails, or 0 otherwise.  If the command ran
2728    successfully, but probing the marker failed, ERROUT will be filled
2729    with the error to reply to GDB, and -1 is also returned.  This
2730    allows directly passing IPA errors to GDB.  */
2731
2732 static int
2733 probe_marker_at (CORE_ADDR address, char *errout)
2734 {
2735   char cmd[CMD_BUF_SIZE];
2736   int err;
2737
2738   sprintf (cmd, "probe_marker_at:%s", paddress (address));
2739   err = run_inferior_command (cmd);
2740
2741   if (err == 0)
2742     {
2743       if (*cmd == 'E')
2744         {
2745           strcpy (errout, cmd);
2746           return -1;
2747         }
2748     }
2749
2750   return err;
2751 }
2752
2753 #define MAX_JUMP_SIZE 20
2754
2755 static void
2756 cmd_qtstart (char *packet)
2757 {
2758   struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
2759   int slow_tracepoint_count, fast_count;
2760   CORE_ADDR jump_entry;
2761
2762   /* The jump to the jump pad of the last fast tracepoint
2763      installed.  */
2764   unsigned char fjump[MAX_JUMP_SIZE];
2765   ULONGEST fjump_size;
2766
2767   trace_debug ("Starting the trace");
2768
2769   slow_tracepoint_count = fast_count = 0;
2770
2771   /* Sort tracepoints by ascending address.  This makes installing
2772      fast tracepoints at the same address easier to handle. */
2773   sort_tracepoints ();
2774
2775   /* Pause all threads temporarily while we patch tracepoints.  */
2776   pause_all (0);
2777
2778   /* Get threads out of jump pads.  Safe to do here, since this is a
2779      top level command.  And, required to do here, since we're
2780      deleting/rewriting jump pads.  */
2781
2782   stabilize_threads ();
2783
2784   /* Freeze threads.  */
2785   pause_all (1);
2786
2787   /* Sync the fast tracepoints list in the inferior ftlib.  */
2788   if (in_process_agent_loaded ())
2789     {
2790       download_tracepoints ();
2791       download_trace_state_variables ();
2792     }
2793
2794   /* No previous fast tpoint yet.  */
2795   prev_ftpoint = NULL;
2796
2797   /* No previous static tpoint yet.  */
2798   prev_stpoint = NULL;
2799
2800   *packet = '\0';
2801
2802   /* Install tracepoints.  */
2803   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2804     {
2805       /* Ensure all the hit counts start at zero.  */
2806       tpoint->hit_count = 0;
2807
2808       if (!tpoint->enabled)
2809         continue;
2810
2811       if (tpoint->type == trap_tracepoint)
2812         {
2813           ++slow_tracepoint_count;
2814
2815           /* Tracepoints are installed as memory breakpoints.  Just go
2816              ahead and install the trap.  The breakpoints module
2817              handles duplicated breakpoints, and the memory read
2818              routine handles un-patching traps from memory reads.  */
2819           tpoint->handle = set_breakpoint_at (tpoint->address,
2820                                               tracepoint_handler);
2821         }
2822       else if (tpoint->type == fast_tracepoint)
2823         {
2824           ++fast_count;
2825
2826           if (maybe_write_ipa_not_loaded (packet))
2827             {
2828               trace_debug ("Requested a fast tracepoint, but fast "
2829                            "tracepoints aren't supported.");
2830               break;
2831             }
2832
2833           if (prev_ftpoint != NULL && prev_ftpoint->address == tpoint->address)
2834             {
2835               tpoint->handle = set_fast_tracepoint_jump (tpoint->address,
2836                                                          fjump,
2837                                                          fjump_size);
2838               tpoint->jump_pad = prev_ftpoint->jump_pad;
2839               tpoint->jump_pad_end = prev_ftpoint->jump_pad_end;
2840               tpoint->adjusted_insn_addr = prev_ftpoint->adjusted_insn_addr;
2841               tpoint->adjusted_insn_addr_end
2842                 = prev_ftpoint->adjusted_insn_addr_end;
2843             }
2844           else
2845             {
2846               CORE_ADDR jentry;
2847               int err = 0;
2848
2849               prev_ftpoint = NULL;
2850
2851               jentry = jump_entry = get_jump_space_head ();
2852
2853               /* Install the jump pad.  */
2854               err = install_fast_tracepoint_jump_pad
2855                 (tpoint->obj_addr_on_target,
2856                  tpoint->address,
2857                  ipa_sym_addrs.addr_gdb_collect,
2858                  ipa_sym_addrs.addr_collecting,
2859                  tpoint->orig_size,
2860                  &jentry,
2861                  fjump, &fjump_size,
2862                  &tpoint->adjusted_insn_addr,
2863                  &tpoint->adjusted_insn_addr_end);
2864
2865               /* Wire it in.  */
2866               if (!err)
2867                 tpoint->handle = set_fast_tracepoint_jump (tpoint->address,
2868                                                            fjump, fjump_size);
2869
2870               if (tpoint->handle != NULL)
2871                 {
2872                   tpoint->jump_pad = jump_entry;
2873                   tpoint->jump_pad_end = jentry;
2874
2875                   /* Pad to 8-byte alignment.  */
2876                   jentry = ((jentry + 7) & ~0x7);
2877                   claim_jump_space (jentry - jump_entry);
2878
2879                   /* So that we can handle multiple fast tracepoints
2880                      at the same address easily.  */
2881                   prev_ftpoint = tpoint;
2882                 }
2883             }
2884         }
2885       else if (tpoint->type == static_tracepoint)
2886         {
2887           if (maybe_write_ipa_ust_not_loaded (packet))
2888             {
2889               trace_debug ("Requested a static tracepoint, but static "
2890                            "tracepoints are not supported.");
2891               break;
2892             }
2893
2894           /* Can only probe a given marker once.  */
2895           if (prev_stpoint != NULL && prev_stpoint->address == tpoint->address)
2896             {
2897               tpoint->handle = (void *) -1;
2898             }
2899           else
2900             {
2901               if (probe_marker_at (tpoint->address, packet) == 0)
2902                 {
2903                   tpoint->handle = (void *) -1;
2904
2905                   /* So that we can handle multiple static tracepoints
2906                      at the same address easily.  */
2907                   prev_stpoint = tpoint;
2908                 }
2909             }
2910         }
2911
2912       /* Any failure in the inner loop is sufficient cause to give
2913          up.  */
2914       if (tpoint->handle == NULL)
2915         break;
2916     }
2917
2918   /* Any error in tracepoint insertion is unacceptable; better to
2919      address the problem now, than end up with a useless or misleading
2920      trace run.  */
2921   if (tpoint != NULL)
2922     {
2923       clear_installed_tracepoints ();
2924       if (*packet == '\0')
2925         write_enn (packet);
2926       unpause_all (1);
2927       return;
2928     }
2929
2930   stopping_tracepoint = NULL;
2931   trace_buffer_is_full = 0;
2932   expr_eval_result = expr_eval_no_error;
2933   error_tracepoint = NULL;
2934
2935   /* Tracing is now active, hits will now start being logged.  */
2936   tracing = 1;
2937
2938   if (in_process_agent_loaded ())
2939     {
2940       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
2941         fatal ("Error setting tracing variable in lib");
2942
2943       if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
2944                                        0))
2945         fatal ("Error clearing stopping_tracepoint variable in lib");
2946
2947       if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
2948         fatal ("Error clearing trace_buffer_is_full variable in lib");
2949
2950       stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
2951                                              stop_tracing_handler);
2952       if (stop_tracing_bkpt == NULL)
2953         error ("Error setting stop_tracing breakpoint");
2954
2955       flush_trace_buffer_bkpt
2956         = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
2957                              flush_trace_buffer_handler);
2958       if (flush_trace_buffer_bkpt == NULL)
2959         error ("Error setting flush_trace_buffer breakpoint");
2960     }
2961
2962   unpause_all (1);
2963
2964   write_ok (packet);
2965 }
2966
2967 /* End a tracing run, filling in a stop reason to report back to GDB,
2968    and removing the tracepoints from the code.  */
2969
2970 void
2971 stop_tracing (void)
2972 {
2973   if (!tracing)
2974     {
2975       trace_debug ("Tracing is already off, ignoring");
2976       return;
2977     }
2978
2979   trace_debug ("Stopping the trace");
2980
2981   /* Pause all threads before removing fast jumps from memory,
2982      breakpoints, and touching IPA state variables (inferior memory).
2983      Some thread may hit the internal tracing breakpoints, or be
2984      collecting this moment, but that's ok, we don't release the
2985      tpoint object's memory or the jump pads here (we only do that
2986      when we're sure we can move all threads out of the jump pads).
2987      We can't now, since we may be getting here due to the inferior
2988      agent calling us.  */
2989   pause_all (1);
2990   /* Since we're removing breakpoints, cancel breakpoint hits,
2991      possibly related to the breakpoints we're about to delete.  */
2992   cancel_breakpoints ();
2993
2994   /* Stop logging. Tracepoints can still be hit, but they will not be
2995      recorded.  */
2996   tracing = 0;
2997   if (in_process_agent_loaded ())
2998     {
2999       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3000         fatal ("Error clearing tracing variable in lib");
3001     }
3002
3003   tracing_stop_reason = "t???";
3004   tracing_stop_tpnum = 0;
3005   if (stopping_tracepoint)
3006     {
3007       trace_debug ("Stopping the trace because "
3008                    "tracepoint %d was hit %ld times",
3009                    stopping_tracepoint->number,
3010                    stopping_tracepoint->pass_count);
3011       tracing_stop_reason = "tpasscount";
3012       tracing_stop_tpnum = stopping_tracepoint->number;
3013     }
3014   else if (trace_buffer_is_full)
3015     {
3016       trace_debug ("Stopping the trace because the trace buffer is full");
3017       tracing_stop_reason = "tfull";
3018     }
3019   else if (expr_eval_result != expr_eval_no_error)
3020     {
3021       trace_debug ("Stopping the trace because of an expression eval error");
3022       tracing_stop_reason = eval_result_names[expr_eval_result];
3023       tracing_stop_tpnum = error_tracepoint->number;
3024     }
3025 #ifndef IN_PROCESS_AGENT
3026   else if (!gdb_connected ())
3027     {
3028       trace_debug ("Stopping the trace because GDB disconnected");
3029       tracing_stop_reason = "tdisconnected";
3030     }
3031 #endif
3032   else
3033     {
3034       trace_debug ("Stopping the trace because of a tstop command");
3035       tracing_stop_reason = "tstop";
3036     }
3037
3038   stopping_tracepoint = NULL;
3039   error_tracepoint = NULL;
3040
3041   /* Clear out the tracepoints.  */
3042   clear_installed_tracepoints ();
3043
3044   if (in_process_agent_loaded ())
3045     {
3046       /* Pull in fast tracepoint trace frames from the inferior lib
3047          buffer into our buffer, even if our buffer is already full,
3048          because we want to present the full number of created frames
3049          in addition to what fit in the trace buffer.  */
3050       upload_fast_traceframes ();
3051     }
3052
3053   if (stop_tracing_bkpt != NULL)
3054     {
3055       delete_breakpoint (stop_tracing_bkpt);
3056       stop_tracing_bkpt = NULL;
3057     }
3058
3059   if (flush_trace_buffer_bkpt != NULL)
3060     {
3061       delete_breakpoint (flush_trace_buffer_bkpt);
3062       flush_trace_buffer_bkpt = NULL;
3063     }
3064
3065   unpause_all (1);
3066 }
3067
3068 static int
3069 stop_tracing_handler (CORE_ADDR addr)
3070 {
3071   trace_debug ("lib hit stop_tracing");
3072
3073   /* Don't actually handle it here.  When we stop tracing we remove
3074      breakpoints from the inferior, and that is not allowed in a
3075      breakpoint handler (as the caller is walking the breakpoint
3076      list).  */
3077   return 0;
3078 }
3079
3080 static int
3081 flush_trace_buffer_handler (CORE_ADDR addr)
3082 {
3083   trace_debug ("lib hit flush_trace_buffer");
3084   return 0;
3085 }
3086
3087 static void
3088 cmd_qtstop (char *packet)
3089 {
3090   stop_tracing ();
3091   write_ok (packet);
3092 }
3093
3094 static void
3095 cmd_qtdisconnected (char *own_buf)
3096 {
3097   ULONGEST setting;
3098   char *packet = own_buf;
3099
3100   packet += strlen ("QTDisconnected:");
3101
3102   unpack_varlen_hex (packet, &setting);
3103
3104   write_ok (own_buf);
3105
3106   disconnected_tracing = setting;
3107 }
3108
3109 static void
3110 cmd_qtframe (char *own_buf)
3111 {
3112   ULONGEST frame, pc, lo, hi, num;
3113   int tfnum, tpnum;
3114   struct traceframe *tframe;
3115   char *packet = own_buf;
3116
3117   packet += strlen ("QTFrame:");
3118
3119   if (strncmp (packet, "pc:", strlen ("pc:")) == 0)
3120     {
3121       packet += strlen ("pc:");
3122       packet = unpack_varlen_hex (packet, &pc);
3123       trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3124       tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3125     }
3126   else if (strncmp (packet, "range:", strlen ("range:")) == 0)
3127     {
3128       packet += strlen ("range:");
3129       packet = unpack_varlen_hex (packet, &lo);
3130       ++packet;
3131       packet = unpack_varlen_hex (packet, &hi);
3132       trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3133                    paddress (lo), paddress (hi));
3134       tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3135     }
3136   else if (strncmp (packet, "outside:", strlen ("outside:")) == 0)
3137     {
3138       packet += strlen ("outside:");
3139       packet = unpack_varlen_hex (packet, &lo);
3140       ++packet;
3141       packet = unpack_varlen_hex (packet, &hi);
3142       trace_debug ("Want to find next traceframe "
3143                    "outside the range 0x%s to 0x%s",
3144                    paddress (lo), paddress (hi));
3145       tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3146     }
3147   else if (strncmp (packet, "tdp:", strlen ("tdp:")) == 0)
3148     {
3149       packet += strlen ("tdp:");
3150       packet = unpack_varlen_hex (packet, &num);
3151       tpnum = (int) num;
3152       trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3153       tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3154     }
3155   else
3156     {
3157       unpack_varlen_hex (packet, &frame);
3158       tfnum = (int) frame;
3159       if (tfnum == -1)
3160         {
3161           trace_debug ("Want to stop looking at traceframes");
3162           current_traceframe = -1;
3163           write_ok (own_buf);
3164           return;
3165         }
3166       trace_debug ("Want to look at traceframe %d", tfnum);
3167       tframe = find_traceframe (tfnum);
3168     }
3169
3170   if (tframe)
3171     {
3172       current_traceframe = tfnum;
3173       sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3174     }
3175   else
3176     sprintf (own_buf, "F-1");
3177 }
3178
3179 static void
3180 cmd_qtstatus (char *packet)
3181 {
3182   char *stop_reason_rsp = NULL;
3183
3184   trace_debug ("Returning trace status as %d, stop reason %s",
3185                tracing, tracing_stop_reason);
3186
3187   if (in_process_agent_loaded ())
3188     {
3189       pause_all (1);
3190
3191       upload_fast_traceframes ();
3192
3193       unpause_all (1);
3194    }
3195
3196   stop_reason_rsp = (char *) tracing_stop_reason;
3197
3198   /* The user visible error string in terror needs to be hex encoded.
3199      We leave it as plain string in `tracepoint_stop_reason' to ease
3200      debugging.  */
3201   if (strncmp (stop_reason_rsp, "terror:", strlen ("terror:")) == 0)
3202     {
3203       const char *result_name;
3204       int hexstr_len;
3205       char *p;
3206
3207       result_name = stop_reason_rsp + strlen ("terror:");
3208       hexstr_len = strlen (result_name) * 2;
3209       p = stop_reason_rsp = alloca (strlen ("terror:") + hexstr_len + 1);
3210       strcpy (p, "terror:");
3211       p += strlen (p);
3212       convert_int_to_ascii ((gdb_byte *) result_name, p, strlen (result_name));
3213     }
3214
3215   sprintf (packet,
3216            "T%d;"
3217            "%s:%x;"
3218            "tframes:%x;tcreated:%x;"
3219            "tfree:%x;tsize:%s;"
3220            "circular:%d;"
3221            "disconn:%d",
3222            tracing ? 1 : 0,
3223            stop_reason_rsp, tracing_stop_tpnum,
3224            traceframe_count, traceframes_created,
3225            free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3226            circular_trace_buffer,
3227            disconnected_tracing);
3228 }
3229
3230 /* State variables to help return all the tracepoint bits.  */
3231 static struct tracepoint *cur_tpoint;
3232 static int cur_action;
3233 static int cur_step_action;
3234 static struct source_string *cur_source_string;
3235 static struct trace_state_variable *cur_tsv;
3236
3237 /* Compose a response that is an imitation of the syntax by which the
3238    tracepoint was originally downloaded.  */
3239
3240 static void
3241 response_tracepoint (char *packet, struct tracepoint *tpoint)
3242 {
3243   char *buf;
3244
3245   sprintf (packet, "T%x:%s:%c:%lx:%lx", tpoint->number,
3246            paddress (tpoint->address),
3247            (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3248            tpoint->pass_count);
3249   if (tpoint->type == fast_tracepoint)
3250     sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3251   else if (tpoint->type == static_tracepoint)
3252     sprintf (packet + strlen (packet), ":S");
3253
3254   if (tpoint->cond)
3255     {
3256       buf = unparse_agent_expr (tpoint->cond);
3257       sprintf (packet + strlen (packet), ":X%x,%s",
3258                tpoint->cond->length, buf);
3259       free (buf);
3260     }
3261 }
3262
3263 /* Compose a response that is an imitation of the syntax by which the
3264    tracepoint action was originally downloaded (with the difference
3265    that due to the way we store the actions, this will output a packet
3266    per action, while GDB could have combined more than one action
3267    per-packet.  */
3268
3269 static void
3270 response_action (char *packet, struct tracepoint *tpoint,
3271                  char *taction, int step)
3272 {
3273   sprintf (packet, "%c%x:%s:%s",
3274            (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3275            taction);
3276 }
3277
3278 /* Compose a response that is an imitation of the syntax by which the
3279    tracepoint source piece was originally downloaded.  */
3280
3281 static void
3282 response_source (char *packet,
3283                  struct tracepoint *tpoint, struct source_string *src)
3284 {
3285   char *buf;
3286   int len;
3287
3288   len = strlen (src->str);
3289   buf = alloca (len * 2 + 1);
3290   convert_int_to_ascii ((gdb_byte *) src->str, buf, len);
3291
3292   sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3293            tpoint->number, paddress (tpoint->address),
3294            src->type, 0, len, buf);
3295 }
3296
3297 /* Return the first piece of tracepoint definition, and initialize the
3298    state machine that will iterate through all the tracepoint
3299    bits.  */
3300
3301 static void
3302 cmd_qtfp (char *packet)
3303 {
3304   trace_debug ("Returning first tracepoint definition piece");
3305
3306   cur_tpoint = tracepoints;
3307   cur_action = cur_step_action = -1;
3308   cur_source_string = NULL;
3309
3310   if (cur_tpoint)
3311     response_tracepoint (packet, cur_tpoint);
3312   else
3313     strcpy (packet, "l");
3314 }
3315
3316 /* Return additional pieces of tracepoint definition.  Each action and
3317    stepping action must go into its own packet, because of packet size
3318    limits, and so we use state variables to deliver one piece at a
3319    time.  */
3320
3321 static void
3322 cmd_qtsp (char *packet)
3323 {
3324   trace_debug ("Returning subsequent tracepoint definition piece");
3325
3326   if (!cur_tpoint)
3327     {
3328       /* This case would normally never occur, but be prepared for
3329          GDB misbehavior.  */
3330       strcpy (packet, "l");
3331     }
3332   else if (cur_action < cur_tpoint->numactions - 1)
3333     {
3334       ++cur_action;
3335       response_action (packet, cur_tpoint,
3336                        cur_tpoint->actions_str[cur_action], 0);
3337     }
3338   else if (cur_step_action < cur_tpoint->num_step_actions - 1)
3339     {
3340       ++cur_step_action;
3341       response_action (packet, cur_tpoint,
3342                        cur_tpoint->step_actions_str[cur_step_action], 1);
3343     }
3344   else if ((cur_source_string
3345             ? cur_source_string->next
3346             : cur_tpoint->source_strings))
3347     {
3348       if (cur_source_string)
3349         cur_source_string = cur_source_string->next;
3350       else
3351         cur_source_string = cur_tpoint->source_strings;
3352       response_source (packet, cur_tpoint, cur_source_string);
3353     }
3354   else
3355     {
3356       cur_tpoint = cur_tpoint->next;
3357       cur_action = cur_step_action = -1;
3358       cur_source_string = NULL;
3359       if (cur_tpoint)
3360         response_tracepoint (packet, cur_tpoint);
3361       else
3362         strcpy (packet, "l");
3363     }
3364 }
3365
3366 /* Compose a response that is an imitation of the syntax by which the
3367    trace state variable was originally downloaded.  */
3368
3369 static void
3370 response_tsv (char *packet, struct trace_state_variable *tsv)
3371 {
3372   char *buf = (char *) "";
3373   int namelen;
3374
3375   if (tsv->name)
3376     {
3377       namelen = strlen (tsv->name);
3378       buf = alloca (namelen * 2 + 1);
3379       convert_int_to_ascii ((gdb_byte *) tsv->name, buf, namelen);
3380     }
3381
3382   sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3383            tsv->getter ? 1 : 0, buf);
3384 }
3385
3386 /* Return the first trace state variable definition, and initialize
3387    the state machine that will iterate through all the tsv bits.  */
3388
3389 static void
3390 cmd_qtfv (char *packet)
3391 {
3392   trace_debug ("Returning first trace state variable definition");
3393
3394   cur_tsv = trace_state_variables;
3395
3396   if (cur_tsv)
3397     response_tsv (packet, cur_tsv);
3398   else
3399     strcpy (packet, "l");
3400 }
3401
3402 /* Return additional trace state variable definitions. */
3403
3404 static void
3405 cmd_qtsv (char *packet)
3406 {
3407   trace_debug ("Returning first trace state variable definition");
3408
3409   if (!cur_tpoint)
3410     {
3411       /* This case would normally never occur, but be prepared for
3412          GDB misbehavior.  */
3413       strcpy (packet, "l");
3414     }
3415   else if (cur_tsv)
3416     {
3417       cur_tsv = cur_tsv->next;
3418       if (cur_tsv)
3419         response_tsv (packet, cur_tsv);
3420       else
3421         strcpy (packet, "l");
3422     }
3423   else
3424     strcpy (packet, "l");
3425 }
3426
3427 /* Return the first static tracepoint marker, and initialize the state
3428    machine that will iterate through all the static tracepoints
3429    markers.  */
3430
3431 static void
3432 cmd_qtfstm (char *packet)
3433 {
3434   if (!maybe_write_ipa_ust_not_loaded (packet))
3435     run_inferior_command (packet);
3436 }
3437
3438 /* Return additional static tracepoints markers.  */
3439
3440 static void
3441 cmd_qtsstm (char *packet)
3442 {
3443   if (!maybe_write_ipa_ust_not_loaded (packet))
3444     run_inferior_command (packet);
3445 }
3446
3447 /* Return the definition of the static tracepoint at a given address.
3448    Result packet is the same as qTsST's.  */
3449
3450 static void
3451 cmd_qtstmat (char *packet)
3452 {
3453   if (!maybe_write_ipa_ust_not_loaded (packet))
3454     run_inferior_command (packet);
3455 }
3456
3457 /* Respond to qTBuffer packet with a block of raw data from the trace
3458    buffer.  GDB may ask for a lot, but we are allowed to reply with
3459    only as much as will fit within packet limits or whatever.  */
3460
3461 static void
3462 cmd_qtbuffer (char *own_buf)
3463 {
3464   ULONGEST offset, num, tot;
3465   unsigned char *tbp;
3466   char *packet = own_buf;
3467
3468   packet += strlen ("qTBuffer:");
3469
3470   packet = unpack_varlen_hex (packet, &offset);
3471   ++packet; /* skip a comma */
3472   packet = unpack_varlen_hex (packet, &num);
3473
3474   trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3475                (int) num, pulongest (offset));
3476
3477   tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3478
3479   /* If we're right at the end, reply specially that we're done.  */
3480   if (offset == tot)
3481     {
3482       strcpy (own_buf, "l");
3483       return;
3484     }
3485
3486   /* Object to any other out-of-bounds request.  */
3487   if (offset > tot)
3488     {
3489       write_enn (own_buf);
3490       return;
3491     }
3492
3493   /* Compute the pointer corresponding to the given offset, accounting
3494      for wraparound.  */
3495   tbp = trace_buffer_start + offset;
3496   if (tbp >= trace_buffer_wrap)
3497     tbp -= (trace_buffer_wrap - trace_buffer_lo);
3498
3499   /* Trim to the remaining bytes if we're close to the end.  */
3500   if (num > tot - offset)
3501     num = tot - offset;
3502
3503   /* Trim to available packet size.  */
3504   if (num >= (PBUFSIZ - 16) / 2 )
3505     num = (PBUFSIZ - 16) / 2;
3506
3507   convert_int_to_ascii (tbp, own_buf, num);
3508   own_buf[num] = '\0';
3509 }
3510
3511 static void
3512 cmd_bigqtbuffer (char *own_buf)
3513 {
3514   ULONGEST val;
3515   char *packet = own_buf;
3516
3517   packet += strlen ("QTBuffer:");
3518
3519   if (strncmp ("circular:", packet, strlen ("circular:")) == 0)
3520     {
3521       packet += strlen ("circular:");
3522       packet = unpack_varlen_hex (packet, &val);
3523       circular_trace_buffer = val;
3524       trace_debug ("Trace buffer is now %s",
3525                    circular_trace_buffer ? "circular" : "linear");
3526       write_ok (own_buf);
3527     }
3528   else
3529     write_enn (own_buf);
3530 }
3531
3532 int
3533 handle_tracepoint_general_set (char *packet)
3534 {
3535   if (strcmp ("QTinit", packet) == 0)
3536     {
3537       cmd_qtinit (packet);
3538       return 1;
3539     }
3540   else if (strncmp ("QTDP:", packet, strlen ("QTDP:")) == 0)
3541     {
3542       cmd_qtdp (packet);
3543       return 1;
3544     }
3545   else if (strncmp ("QTDPsrc:", packet, strlen ("QTDPsrc:")) == 0)
3546     {
3547       cmd_qtdpsrc (packet);
3548       return 1;
3549     }
3550   else if (strncmp ("QTDV:", packet, strlen ("QTDV:")) == 0)
3551     {
3552       cmd_qtdv (packet);
3553       return 1;
3554     }
3555   else if (strncmp ("QTro:", packet, strlen ("QTro:")) == 0)
3556     {
3557       cmd_qtro (packet);
3558       return 1;
3559     }
3560   else if (strcmp ("QTStart", packet) == 0)
3561     {
3562       cmd_qtstart (packet);
3563       return 1;
3564     }
3565   else if (strcmp ("QTStop", packet) == 0)
3566     {
3567       cmd_qtstop (packet);
3568       return 1;
3569     }
3570   else if (strncmp ("QTDisconnected:", packet,
3571                     strlen ("QTDisconnected:")) == 0)
3572     {
3573       cmd_qtdisconnected (packet);
3574       return 1;
3575     }
3576   else if (strncmp ("QTFrame:", packet, strlen ("QTFrame:")) == 0)
3577     {
3578       cmd_qtframe (packet);
3579       return 1;
3580     }
3581   else if (strncmp ("QTBuffer:", packet, strlen ("QTBuffer:")) == 0)
3582     {
3583       cmd_bigqtbuffer (packet);
3584       return 1;
3585     }
3586
3587   return 0;
3588 }
3589
3590 int
3591 handle_tracepoint_query (char *packet)
3592 {
3593   if (strcmp ("qTStatus", packet) == 0)
3594     {
3595       cmd_qtstatus (packet);
3596       return 1;
3597     }
3598   else if (strcmp ("qTfP", packet) == 0)
3599     {
3600       cmd_qtfp (packet);
3601       return 1;
3602     }
3603   else if (strcmp ("qTsP", packet) == 0)
3604     {
3605       cmd_qtsp (packet);
3606       return 1;
3607     }
3608   else if (strcmp ("qTfV", packet) == 0)
3609     {
3610       cmd_qtfv (packet);
3611       return 1;
3612     }
3613   else if (strcmp ("qTsV", packet) == 0)
3614     {
3615       cmd_qtsv (packet);
3616       return 1;
3617     }
3618   else if (strncmp ("qTV:", packet, strlen ("qTV:")) == 0)
3619     {
3620       cmd_qtv (packet);
3621       return 1;
3622     }
3623   else if (strncmp ("qTBuffer:", packet, strlen ("qTBuffer:")) == 0)
3624     {
3625       cmd_qtbuffer (packet);
3626       return 1;
3627     }
3628   else if (strcmp ("qTfSTM", packet) == 0)
3629     {
3630       cmd_qtfstm (packet);
3631       return 1;
3632     }
3633   else if (strcmp ("qTsSTM", packet) == 0)
3634     {
3635       cmd_qtsstm (packet);
3636       return 1;
3637     }
3638   else if (strncmp ("qTSTMat:", packet, strlen ("qTSTMat:")) == 0)
3639     {
3640       cmd_qtstmat (packet);
3641       return 1;
3642     }
3643
3644   return 0;
3645 }
3646
3647 #endif
3648 #ifndef IN_PROCESS_AGENT
3649
3650 /* Call this when thread TINFO has hit the tracepoint defined by
3651    TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
3652    action.  This adds a while-stepping collecting state item to the
3653    threads' collecting state list, so that we can keep track of
3654    multiple simultaneous while-stepping actions being collected by the
3655    same thread.  This can happen in cases like:
3656
3657     ff0001  INSN1 <-- TP1, while-stepping 10 collect $regs
3658     ff0002  INSN2
3659     ff0003  INSN3 <-- TP2, collect $regs
3660     ff0004  INSN4 <-- TP3, while-stepping 10 collect $regs
3661     ff0005  INSN5
3662
3663    Notice that when instruction INSN5 is reached, the while-stepping
3664    actions of both TP1 and TP3 are still being collected, and that TP2
3665    had been collected meanwhile.  The whole range of ff0001-ff0005
3666    should be single-stepped, due to at least TP1's while-stepping
3667    action covering the whole range.  */
3668
3669 static void
3670 add_while_stepping_state (struct thread_info *tinfo,
3671                           int tp_number, CORE_ADDR tp_address)
3672 {
3673   struct wstep_state *wstep;
3674
3675   wstep = xmalloc (sizeof (*wstep));
3676   wstep->next = tinfo->while_stepping;
3677
3678   wstep->tp_number = tp_number;
3679   wstep->tp_address = tp_address;
3680   wstep->current_step = 0;
3681
3682   tinfo->while_stepping = wstep;
3683 }
3684
3685 /* Release the while-stepping collecting state WSTEP.  */
3686
3687 static void
3688 release_while_stepping_state (struct wstep_state *wstep)
3689 {
3690   free (wstep);
3691 }
3692
3693 /* Release all while-stepping collecting states currently associated
3694    with thread TINFO.  */
3695
3696 void
3697 release_while_stepping_state_list (struct thread_info *tinfo)
3698 {
3699   struct wstep_state *head;
3700
3701   while (tinfo->while_stepping)
3702     {
3703       head = tinfo->while_stepping;
3704       tinfo->while_stepping = head->next;
3705       release_while_stepping_state (head);
3706     }
3707 }
3708
3709 /* If TINFO was handling a 'while-stepping' action, the step has
3710    finished, so collect any step data needed, and check if any more
3711    steps are required.  Return true if the thread was indeed
3712    collecting tracepoint data, false otherwise.  */
3713
3714 int
3715 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
3716 {
3717   struct tracepoint *tpoint;
3718   struct wstep_state *wstep;
3719   struct wstep_state **wstep_link;
3720   struct trap_tracepoint_ctx ctx;
3721
3722   /* Pull in fast tracepoint trace frames from the inferior lib buffer into
3723      our buffer.  */
3724   if (in_process_agent_loaded ())
3725     upload_fast_traceframes ();
3726
3727   /* Check if we were indeed collecting data for one of more
3728      tracepoints with a 'while-stepping' count.  */
3729   if (tinfo->while_stepping == NULL)
3730     return 0;
3731
3732   if (!tracing)
3733     {
3734       /* We're not even tracing anymore.  Stop this thread from
3735          collecting.  */
3736       release_while_stepping_state_list (tinfo);
3737
3738       /* The thread had stopped due to a single-step request indeed
3739          explained by a tracepoint.  */
3740       return 1;
3741     }
3742
3743   wstep = tinfo->while_stepping;
3744   wstep_link = &tinfo->while_stepping;
3745
3746   trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
3747                target_pid_to_str (tinfo->entry.id),
3748                wstep->tp_number, paddress (wstep->tp_address));
3749
3750   ctx.base.type = trap_tracepoint;
3751   ctx.regcache = get_thread_regcache (tinfo, 1);
3752
3753   while (wstep != NULL)
3754     {
3755       tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
3756       if (tpoint == NULL)
3757         {
3758           trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
3759                        wstep->tp_number, paddress (wstep->tp_address),
3760                        target_pid_to_str (tinfo->entry.id));
3761
3762           /* Unlink.  */
3763           *wstep_link = wstep->next;
3764           release_while_stepping_state (wstep);
3765           continue;
3766         }
3767
3768       /* We've just finished one step.  */
3769       ++wstep->current_step;
3770
3771       /* Collect data.  */
3772       collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
3773                             stop_pc, tpoint, wstep->current_step);
3774
3775       if (wstep->current_step >= tpoint->step_count)
3776         {
3777           /* The requested numbers of steps have occurred.  */
3778           trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
3779                        target_pid_to_str (tinfo->entry.id),
3780                        wstep->tp_number, paddress (wstep->tp_address));
3781
3782           /* Unlink the wstep.  */
3783           *wstep_link = wstep->next;
3784           release_while_stepping_state (wstep);
3785           wstep = *wstep_link;
3786
3787           /* Only check the hit count now, which ensure that we do all
3788              our stepping before stopping the run.  */
3789           if (tpoint->pass_count > 0
3790               && tpoint->hit_count >= tpoint->pass_count
3791               && stopping_tracepoint == NULL)
3792             stopping_tracepoint = tpoint;
3793         }
3794       else
3795         {
3796           /* Keep single-stepping until the requested numbers of steps
3797              have occurred.  */
3798           wstep_link = &wstep->next;
3799           wstep = *wstep_link;
3800         }
3801
3802       if (stopping_tracepoint
3803           || trace_buffer_is_full
3804           || expr_eval_result != expr_eval_no_error)
3805         {
3806           stop_tracing ();
3807           break;
3808         }
3809     }
3810
3811   return 1;
3812 }
3813
3814 /* Handle any internal tracing control breakpoint hits.  That means,
3815    pull traceframes from the IPA to our buffer, and syncing both
3816    tracing agents when the IPA's tracing stops for some reason.  */
3817
3818 int
3819 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
3820 {
3821   /* Pull in fast tracepoint trace frames from the inferior in-process
3822      agent's buffer into our buffer.  */
3823
3824   if (!in_process_agent_loaded ())
3825     return 0;
3826
3827   upload_fast_traceframes ();
3828
3829   /* Check if the in-process agent had decided we should stop
3830      tracing.  */
3831   if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
3832     {
3833       int ipa_trace_buffer_is_full;
3834       CORE_ADDR ipa_stopping_tracepoint;
3835       int ipa_expr_eval_result;
3836       CORE_ADDR ipa_error_tracepoint;
3837
3838       trace_debug ("lib stopped at stop_tracing");
3839
3840       read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
3841                              &ipa_trace_buffer_is_full);
3842
3843       read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3844                                   &ipa_stopping_tracepoint);
3845       write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
3846
3847       read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
3848                                   &ipa_error_tracepoint);
3849       write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
3850
3851       read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
3852                              &ipa_expr_eval_result);
3853       write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
3854
3855       trace_debug ("lib: trace_buffer_is_full: %d, "
3856                    "stopping_tracepoint: %s, "
3857                    "ipa_expr_eval_result: %d, "
3858                    "error_tracepoint: %s, ",
3859                    ipa_trace_buffer_is_full,
3860                    paddress (ipa_stopping_tracepoint),
3861                    ipa_expr_eval_result,
3862                    paddress (ipa_error_tracepoint));
3863
3864       if (debug_threads)
3865         {
3866           if (ipa_trace_buffer_is_full)
3867             trace_debug ("lib stopped due to full buffer.");
3868           if (ipa_stopping_tracepoint)
3869             trace_debug ("lib stopped due to tpoint");
3870           if (ipa_stopping_tracepoint)
3871             trace_debug ("lib stopped due to error");
3872         }
3873
3874       if (ipa_stopping_tracepoint != 0)
3875         {
3876           stopping_tracepoint
3877             = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
3878         }
3879       else if (ipa_expr_eval_result != expr_eval_no_error)
3880         {
3881           expr_eval_result = ipa_expr_eval_result;
3882           error_tracepoint
3883             = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
3884         }
3885       stop_tracing ();
3886       return 1;
3887     }
3888   else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
3889     {
3890       trace_debug ("lib stopped at flush_trace_buffer");
3891       return 1;
3892     }
3893
3894   return 0;
3895 }
3896
3897 /* Return true if TINFO just hit a tracepoint.  Collect data if
3898    so.  */
3899
3900 int
3901 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
3902 {
3903   struct tracepoint *tpoint;
3904   int ret = 0;
3905   struct trap_tracepoint_ctx ctx;
3906
3907   /* Not tracing, don't handle.  */
3908   if (!tracing)
3909     return 0;
3910
3911   ctx.base.type = trap_tracepoint;
3912   ctx.regcache = get_thread_regcache (tinfo, 1);
3913
3914   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3915     {
3916       /* Note that we collect fast tracepoints here as well.  We'll
3917          step over the fast tracepoint jump later, which avoids the
3918          double collect.  */
3919       if (tpoint->enabled && stop_pc == tpoint->address)
3920         {
3921           trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
3922                        target_pid_to_str (tinfo->entry.id),
3923                        tpoint->number, paddress (tpoint->address));
3924
3925           /* Test the condition if present, and collect if true.  */
3926           if (!tpoint->cond
3927               || (condition_true_at_tracepoint
3928                   ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
3929             collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
3930                                         stop_pc, tpoint);
3931
3932           if (stopping_tracepoint
3933               || trace_buffer_is_full
3934               || expr_eval_result != expr_eval_no_error)
3935             {
3936               stop_tracing ();
3937             }
3938           /* If the tracepoint had a 'while-stepping' action, then set
3939              the thread to collect this tracepoint on the following
3940              single-steps.  */
3941           else if (tpoint->step_count > 0)
3942             {
3943               add_while_stepping_state (tinfo,
3944                                         tpoint->number, tpoint->address);
3945             }
3946
3947           ret = 1;
3948         }
3949     }
3950
3951   return ret;
3952 }
3953
3954 #endif
3955
3956 #if defined IN_PROCESS_AGENT && defined HAVE_UST
3957 struct ust_marker_data;
3958 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
3959                                             CORE_ADDR stop_pc,
3960                                             struct tracepoint *tpoint,
3961                                             struct traceframe *tframe);
3962 #endif
3963
3964 /* Create a trace frame for the hit of the given tracepoint in the
3965    given thread.  */
3966
3967 static void
3968 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
3969                             struct tracepoint *tpoint)
3970 {
3971   struct traceframe *tframe;
3972   int acti;
3973
3974   /* Only count it as a hit when we actually collect data.  */
3975   tpoint->hit_count++;
3976
3977   /* If we've exceeded a defined pass count, record the event for
3978      later, and finish the collection for this hit.  This test is only
3979      for nonstepping tracepoints, stepping tracepoints test at the end
3980      of their while-stepping loop.  */
3981   if (tpoint->pass_count > 0
3982       && tpoint->hit_count >= tpoint->pass_count
3983       && tpoint->step_count == 0
3984       && stopping_tracepoint == NULL)
3985     stopping_tracepoint = tpoint;
3986
3987   trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %ld",
3988                tpoint->number, paddress (tpoint->address), tpoint->hit_count);
3989
3990   tframe = add_traceframe (tpoint);
3991
3992   if (tframe)
3993     {
3994       for (acti = 0; acti < tpoint->numactions; ++acti)
3995         {
3996 #ifndef IN_PROCESS_AGENT
3997           trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
3998                        tpoint->number, paddress (tpoint->address),
3999                        tpoint->actions_str[acti]);
4000 #endif
4001
4002           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4003                                    tpoint->actions[acti]);
4004         }
4005
4006       finish_traceframe (tframe);
4007     }
4008
4009   if (tframe == NULL && tracing)
4010     trace_buffer_is_full = 1;
4011 }
4012
4013 #ifndef IN_PROCESS_AGENT
4014
4015 static void
4016 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4017                       CORE_ADDR stop_pc,
4018                       struct tracepoint *tpoint, int current_step)
4019 {
4020   struct traceframe *tframe;
4021   int acti;
4022
4023   trace_debug ("Making new step traceframe for "
4024                "tracepoint %d at 0x%s, step %d of %ld, hit %ld",
4025                tpoint->number, paddress (tpoint->address),
4026                current_step, tpoint->step_count,
4027                tpoint->hit_count);
4028
4029   tframe = add_traceframe (tpoint);
4030
4031   if (tframe)
4032     {
4033       for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4034         {
4035           trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4036                        tpoint->number, paddress (tpoint->address),
4037                        tpoint->step_actions_str[acti]);
4038
4039           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4040                                    tpoint->step_actions[acti]);
4041         }
4042
4043       finish_traceframe (tframe);
4044     }
4045
4046   if (tframe == NULL && tracing)
4047     trace_buffer_is_full = 1;
4048 }
4049
4050 #endif
4051
4052 static struct regcache *
4053 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4054 {
4055   struct regcache *regcache = NULL;
4056
4057 #ifdef IN_PROCESS_AGENT
4058   if (ctx->type == fast_tracepoint)
4059     {
4060       struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4061       if (!fctx->regcache_initted)
4062         {
4063           fctx->regcache_initted = 1;
4064           init_register_cache (&fctx->regcache, fctx->regspace);
4065           supply_regblock (&fctx->regcache, NULL);
4066           supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4067         }
4068       regcache = &fctx->regcache;
4069     }
4070 #ifdef HAVE_UST
4071   if (ctx->type == static_tracepoint)
4072     {
4073       struct static_tracepoint_ctx *sctx = (struct static_tracepoint_ctx *) ctx;
4074       if (!sctx->regcache_initted)
4075         {
4076           sctx->regcache_initted = 1;
4077           init_register_cache (&sctx->regcache, sctx->regspace);
4078           supply_regblock (&sctx->regcache, NULL);
4079           /* Pass down the tracepoint address, because REGS doesn't
4080              include the PC, but we know what it must have been.  */
4081           supply_static_tracepoint_registers (&sctx->regcache,
4082                                               (const unsigned char *)
4083                                               sctx->regs,
4084                                               sctx->tpoint->address);
4085         }
4086       regcache = &sctx->regcache;
4087     }
4088 #endif
4089 #else
4090   if (ctx->type == trap_tracepoint)
4091     {
4092       struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4093       regcache = tctx->regcache;
4094     }
4095 #endif
4096
4097   gdb_assert (regcache != NULL);
4098
4099   return regcache;
4100 }
4101
4102 static void
4103 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4104                          CORE_ADDR stop_pc,
4105                          struct tracepoint *tpoint,
4106                          struct traceframe *tframe,
4107                          struct tracepoint_action *taction)
4108 {
4109   enum eval_result_type err;
4110
4111   switch (taction->type)
4112     {
4113     case 'M':
4114       {
4115         struct collect_memory_action *maction;
4116
4117         maction = (struct collect_memory_action *) taction;
4118
4119         trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4120                      pulongest (maction->len),
4121                      paddress (maction->addr), maction->basereg);
4122         /* (should use basereg) */
4123         agent_mem_read (tframe, NULL,
4124                         (CORE_ADDR) maction->addr, maction->len);
4125         break;
4126       }
4127     case 'R':
4128       {
4129         unsigned char *regspace;
4130         struct regcache tregcache;
4131         struct regcache *context_regcache;
4132
4133
4134         trace_debug ("Want to collect registers");
4135
4136         /* Collect all registers for now.  */
4137         regspace = add_traceframe_block (tframe,
4138                                          1 + register_cache_size ());
4139         if (regspace == NULL)
4140           {
4141             trace_debug ("Trace buffer block allocation failed, skipping");
4142             break;
4143           }
4144         /* Identify a register block.  */
4145         *regspace = 'R';
4146
4147         context_regcache = get_context_regcache (ctx);
4148
4149         /* Wrap the regblock in a register cache (in the stack, we
4150            don't want to malloc here).  */
4151         init_register_cache (&tregcache, regspace + 1);
4152
4153         /* Copy the register data to the regblock.  */
4154         regcache_cpy (&tregcache, context_regcache);
4155
4156 #ifndef IN_PROCESS_AGENT
4157         /* On some platforms, trap-based tracepoints will have the PC
4158            pointing to the next instruction after the trap, but we
4159            don't want the user or GDB trying to guess whether the
4160            saved PC needs adjusting; so always record the adjusted
4161            stop_pc.  Note that we can't use tpoint->address instead,
4162            since it will be wrong for while-stepping actions.  This
4163            adjustment is a nop for fast tracepoints collected from the
4164            in-process lib (but not if GDBserver is collecting one
4165            preemptively), since the PC had already been adjusted to
4166            contain the tracepoint's address by the jump pad.  */
4167         trace_debug ("Storing stop pc (0x%s) in regblock",
4168                      paddress (tpoint->address));
4169
4170         /* This changes the regblock, not the thread's
4171            regcache.  */
4172         regcache_write_pc (&tregcache, stop_pc);
4173 #endif
4174       }
4175       break;
4176     case 'X':
4177       {
4178         struct eval_expr_action *eaction;
4179
4180         eaction = (struct eval_expr_action *) taction;
4181
4182         trace_debug ("Want to evaluate expression");
4183
4184         err = eval_agent_expr (ctx, tframe, eaction->expr, NULL);
4185
4186         if (err != expr_eval_no_error)
4187           {
4188             record_tracepoint_error (tpoint, "action expression", err);
4189             return;
4190           }
4191       }
4192       break;
4193     case 'L':
4194       {
4195 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4196         trace_debug ("Want to collect static trace data");
4197         collect_ust_data_at_tracepoint (ctx, stop_pc,
4198                                         tpoint, tframe);
4199 #else
4200         trace_debug ("warning: collecting static trace data, "
4201                      "but static tracepoints are not supported");
4202 #endif
4203       }
4204       break;
4205     default:
4206       trace_debug ("unknown trace action '%c', ignoring", taction->type);
4207       break;
4208     }
4209 }
4210
4211 static int
4212 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4213                               struct tracepoint *tpoint)
4214 {
4215   ULONGEST value = 0;
4216   enum eval_result_type err;
4217
4218   /* Presently, gdbserver doesn't run compiled conditions, only the
4219      IPA does.  If the program stops at a fast tracepoint's address
4220      (e.g., due to a breakpoint, trap tracepoint, or stepping),
4221      gdbserver preemptively collect the fast tracepoint.  Later, on
4222      resume, gdbserver steps over the fast tracepoint like it steps
4223      over breakpoints, so that the IPA doesn't see that fast
4224      tracepoint.  This avoids double collects of fast tracepoints in
4225      that stopping scenario.  Having gdbserver itself handle the fast
4226      tracepoint gives the user a consistent view of when fast or trap
4227      tracepoints are collected, compared to an alternative where only
4228      trap tracepoints are collected on stop, and fast tracepoints on
4229      resume.  When a fast tracepoint is being processed by gdbserver,
4230      it is always the non-compiled condition expression that is
4231      used.  */
4232 #ifdef IN_PROCESS_AGENT
4233   if (tpoint->compiled_cond)
4234     err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (ctx, &value);
4235   else
4236 #endif
4237     err = eval_agent_expr (ctx, NULL, tpoint->cond, &value);
4238
4239   if (err != expr_eval_no_error)
4240     {
4241       record_tracepoint_error (tpoint, "condition", err);
4242       /* The error case must return false.  */
4243       return 0;
4244     }
4245
4246   trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4247                tpoint->number, paddress (tpoint->address),
4248                pulongest (value));
4249   return (value ? 1 : 0);
4250 }
4251
4252 #ifndef IN_PROCESS_AGENT
4253
4254 /* The packet form of an agent expression consists of an 'X', number
4255    of bytes in expression, a comma, and then the bytes.  */
4256
4257 static struct agent_expr *
4258 parse_agent_expr (char **actparm)
4259 {
4260   char *act = *actparm;
4261   ULONGEST xlen;
4262   struct agent_expr *aexpr;
4263
4264   ++act;  /* skip the X */
4265   act = unpack_varlen_hex (act, &xlen);
4266   ++act;  /* skip a comma */
4267   aexpr = xmalloc (sizeof (struct agent_expr));
4268   aexpr->length = xlen;
4269   aexpr->bytes = xmalloc (xlen);
4270   convert_ascii_to_int (act, aexpr->bytes, xlen);
4271   *actparm = act + (xlen * 2);
4272   return aexpr;
4273 }
4274
4275 /* Convert the bytes of an agent expression back into hex digits, so
4276    they can be printed or uploaded.  This allocates the buffer,
4277    callers should free when they are done with it.  */
4278
4279 static char *
4280 unparse_agent_expr (struct agent_expr *aexpr)
4281 {
4282   char *rslt;
4283
4284   rslt = xmalloc (2 * aexpr->length + 1);
4285   convert_int_to_ascii (aexpr->bytes, rslt, aexpr->length);
4286   return rslt;
4287 }
4288
4289 #endif
4290
4291 /* The agent expression evaluator, as specified by the GDB docs. It
4292    returns 0 if everything went OK, and a nonzero error code
4293    otherwise.  */
4294
4295 static enum eval_result_type
4296 eval_agent_expr (struct tracepoint_hit_ctx *ctx,
4297                  struct traceframe *tframe,
4298                  struct agent_expr *aexpr,
4299                  ULONGEST *rslt)
4300 {
4301   int pc = 0;
4302 #define STACK_MAX 100
4303   ULONGEST stack[STACK_MAX], top;
4304   int sp = 0;
4305   unsigned char op;
4306   int arg;
4307
4308   /* This union is a convenient way to convert representations.  For
4309      now, assume a standard architecture where the hardware integer
4310      types have 8, 16, 32, 64 bit types.  A more robust solution would
4311      be to import stdint.h from gnulib.  */
4312   union
4313   {
4314     union
4315     {
4316       unsigned char bytes[1];
4317       unsigned char val;
4318     } u8;
4319     union
4320     {
4321       unsigned char bytes[2];
4322       unsigned short val;
4323     } u16;
4324     union
4325     {
4326       unsigned char bytes[4];
4327       unsigned int val;
4328     } u32;
4329     union
4330     {
4331       unsigned char bytes[8];
4332       ULONGEST val;
4333     } u64;
4334   } cnv;
4335
4336   if (aexpr->length == 0)
4337     {
4338       trace_debug ("empty agent expression");
4339       return expr_eval_empty_expression;
4340     }
4341
4342   /* Cache the stack top in its own variable. Much of the time we can
4343      operate on this variable, rather than dinking with the stack. It
4344      needs to be copied to the stack when sp changes.  */
4345   top = 0;
4346
4347   while (1)
4348     {
4349       op = aexpr->bytes[pc++];
4350
4351       trace_debug ("About to interpret byte 0x%x", op);
4352
4353       switch (op)
4354         {
4355         case gdb_agent_op_add:
4356           top += stack[--sp];
4357           break;
4358
4359         case gdb_agent_op_sub:
4360           top = stack[--sp] - top;
4361           break;
4362
4363         case gdb_agent_op_mul:
4364           top *= stack[--sp];
4365           break;
4366
4367         case gdb_agent_op_div_signed:
4368           if (top == 0)
4369             {
4370               trace_debug ("Attempted to divide by zero");
4371               return expr_eval_divide_by_zero;
4372             }
4373           top = ((LONGEST) stack[--sp]) / ((LONGEST) top);
4374           break;
4375
4376         case gdb_agent_op_div_unsigned:
4377           if (top == 0)
4378             {
4379               trace_debug ("Attempted to divide by zero");
4380               return expr_eval_divide_by_zero;
4381             }
4382           top = stack[--sp] / top;
4383           break;
4384
4385         case gdb_agent_op_rem_signed:
4386           if (top == 0)
4387             {
4388               trace_debug ("Attempted to divide by zero");
4389               return expr_eval_divide_by_zero;
4390             }
4391           top = ((LONGEST) stack[--sp]) % ((LONGEST) top);
4392           break;
4393
4394         case gdb_agent_op_rem_unsigned:
4395           if (top == 0)
4396             {
4397               trace_debug ("Attempted to divide by zero");
4398               return expr_eval_divide_by_zero;
4399             }
4400           top = stack[--sp] % top;
4401           break;
4402
4403         case gdb_agent_op_lsh:
4404           top = stack[--sp] << top;
4405           break;
4406
4407         case gdb_agent_op_rsh_signed:
4408           top = ((LONGEST) stack[--sp]) >> top;
4409           break;
4410
4411         case gdb_agent_op_rsh_unsigned:
4412           top = stack[--sp] >> top;
4413           break;
4414
4415         case gdb_agent_op_trace:
4416           agent_mem_read (tframe,
4417                           NULL, (CORE_ADDR) stack[--sp], (ULONGEST) top);
4418           if (--sp >= 0)
4419             top = stack[sp];
4420           break;
4421
4422         case gdb_agent_op_trace_quick:
4423           arg = aexpr->bytes[pc++];
4424           agent_mem_read (tframe, NULL, (CORE_ADDR) top, (ULONGEST) arg);
4425           break;
4426
4427         case gdb_agent_op_log_not:
4428           top = !top;
4429           break;
4430
4431         case gdb_agent_op_bit_and:
4432           top &= stack[--sp];
4433           break;
4434
4435         case gdb_agent_op_bit_or:
4436           top |= stack[--sp];
4437           break;
4438
4439         case gdb_agent_op_bit_xor:
4440           top ^= stack[--sp];
4441           break;
4442
4443         case gdb_agent_op_bit_not:
4444           top = ~top;
4445           break;
4446
4447         case gdb_agent_op_equal:
4448           top = (stack[--sp] == top);
4449           break;
4450
4451         case gdb_agent_op_less_signed:
4452           top = (((LONGEST) stack[--sp]) < ((LONGEST) top));
4453           break;
4454
4455         case gdb_agent_op_less_unsigned:
4456           top = (stack[--sp] < top);
4457           break;
4458
4459         case gdb_agent_op_ext:
4460           arg = aexpr->bytes[pc++];
4461           if (arg < (sizeof (LONGEST) * 8))
4462             {
4463               LONGEST mask = 1 << (arg - 1);
4464               top &= ((LONGEST) 1 << arg) - 1;
4465               top = (top ^ mask) - mask;
4466             }
4467           break;
4468
4469         case gdb_agent_op_ref8:
4470           agent_mem_read (tframe, cnv.u8.bytes, (CORE_ADDR) top, 1);
4471           top = cnv.u8.val;
4472           break;
4473
4474         case gdb_agent_op_ref16:
4475           agent_mem_read (tframe, cnv.u16.bytes, (CORE_ADDR) top, 2);
4476           top = cnv.u16.val;
4477           break;
4478
4479         case gdb_agent_op_ref32:
4480           agent_mem_read (tframe, cnv.u32.bytes, (CORE_ADDR) top, 4);
4481           top = cnv.u32.val;
4482           break;
4483
4484         case gdb_agent_op_ref64:
4485           agent_mem_read (tframe, cnv.u64.bytes, (CORE_ADDR) top, 8);
4486           top = cnv.u64.val;
4487           break;
4488
4489         case gdb_agent_op_if_goto:
4490           if (top)
4491             pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
4492           else
4493             pc += 2;
4494           if (--sp >= 0)
4495             top = stack[sp];
4496           break;
4497
4498         case gdb_agent_op_goto:
4499           pc = (aexpr->bytes[pc] << 8) + (aexpr->bytes[pc + 1]);
4500           break;
4501
4502         case gdb_agent_op_const8:
4503           /* Flush the cached stack top.  */
4504           stack[sp++] = top;
4505           top = aexpr->bytes[pc++];
4506           break;
4507
4508         case gdb_agent_op_const16:
4509           /* Flush the cached stack top.  */
4510           stack[sp++] = top;
4511           top = aexpr->bytes[pc++];
4512           top = (top << 8) + aexpr->bytes[pc++];
4513           break;
4514
4515         case gdb_agent_op_const32:
4516           /* Flush the cached stack top.  */
4517           stack[sp++] = top;
4518           top = aexpr->bytes[pc++];
4519           top = (top << 8) + aexpr->bytes[pc++];
4520           top = (top << 8) + aexpr->bytes[pc++];
4521           top = (top << 8) + aexpr->bytes[pc++];
4522           break;
4523
4524         case gdb_agent_op_const64:
4525           /* Flush the cached stack top.  */
4526           stack[sp++] = top;
4527           top = aexpr->bytes[pc++];
4528           top = (top << 8) + aexpr->bytes[pc++];
4529           top = (top << 8) + aexpr->bytes[pc++];
4530           top = (top << 8) + aexpr->bytes[pc++];
4531           top = (top << 8) + aexpr->bytes[pc++];
4532           top = (top << 8) + aexpr->bytes[pc++];
4533           top = (top << 8) + aexpr->bytes[pc++];
4534           top = (top << 8) + aexpr->bytes[pc++];
4535           break;
4536
4537         case gdb_agent_op_reg:
4538           /* Flush the cached stack top.  */
4539           stack[sp++] = top;
4540           arg = aexpr->bytes[pc++];
4541           arg = (arg << 8) + aexpr->bytes[pc++];
4542           {
4543             int regnum = arg;
4544             struct regcache *regcache;
4545
4546             regcache = get_context_regcache (ctx);
4547
4548             switch (register_size (regnum))
4549               {
4550               case 8:
4551                 collect_register (regcache, regnum, cnv.u64.bytes);
4552                 top = cnv.u64.val;
4553                 break;
4554               case 4:
4555                 collect_register (regcache, regnum, cnv.u32.bytes);
4556                 top = cnv.u32.val;
4557                 break;
4558               case 2:
4559                 collect_register (regcache, regnum, cnv.u16.bytes);
4560                 top = cnv.u16.val;
4561                 break;
4562               case 1:
4563                 collect_register (regcache, regnum, cnv.u8.bytes);
4564                 top = cnv.u8.val;
4565                 break;
4566               default:
4567                 internal_error (__FILE__, __LINE__,
4568                                 "unhandled register size");
4569               }
4570           }
4571           break;
4572
4573         case gdb_agent_op_end:
4574           trace_debug ("At end of expression, sp=%d, stack top cache=0x%s",
4575                        sp, pulongest (top));
4576           if (rslt)
4577             {
4578               if (sp <= 0)
4579                 {
4580                   /* This should be an error */
4581                   trace_debug ("Stack is empty, nothing to return");
4582                   return expr_eval_empty_stack;
4583                 }
4584               *rslt = top;
4585             }
4586           return expr_eval_no_error;
4587
4588         case gdb_agent_op_dup:
4589           stack[sp++] = top;
4590           break;
4591
4592         case gdb_agent_op_pop:
4593           if (--sp >= 0)
4594             top = stack[sp];
4595           break;
4596
4597         case gdb_agent_op_zero_ext:
4598           arg = aexpr->bytes[pc++];
4599           if (arg < (sizeof (LONGEST) * 8))
4600             top &= ((LONGEST) 1 << arg) - 1;
4601           break;
4602
4603         case gdb_agent_op_swap:
4604           /* Interchange top two stack elements, making sure top gets
4605              copied back onto stack.  */
4606           stack[sp] = top;
4607           top = stack[sp - 1];
4608           stack[sp - 1] = stack[sp];
4609           break;
4610
4611         case gdb_agent_op_getv:
4612           /* Flush the cached stack top.  */
4613           stack[sp++] = top;
4614           arg = aexpr->bytes[pc++];
4615           arg = (arg << 8) + aexpr->bytes[pc++];
4616           top = get_trace_state_variable_value (arg);
4617           break;
4618
4619         case gdb_agent_op_setv:
4620           arg = aexpr->bytes[pc++];
4621           arg = (arg << 8) + aexpr->bytes[pc++];
4622           set_trace_state_variable_value (arg, top);
4623           /* Note that we leave the value on the stack, for the
4624              benefit of later/enclosing expressions.  */
4625           break;
4626
4627         case gdb_agent_op_tracev:
4628           arg = aexpr->bytes[pc++];
4629           arg = (arg << 8) + aexpr->bytes[pc++];
4630           agent_tsv_read (tframe, arg);
4631           break;
4632
4633           /* GDB never (currently) generates any of these ops.  */
4634         case gdb_agent_op_float:
4635         case gdb_agent_op_ref_float:
4636         case gdb_agent_op_ref_double:
4637         case gdb_agent_op_ref_long_double:
4638         case gdb_agent_op_l_to_d:
4639         case gdb_agent_op_d_to_l:
4640         case gdb_agent_op_trace16:
4641           trace_debug ("Agent expression op 0x%x valid, but not handled",
4642                        op);
4643           /* If ever GDB generates any of these, we don't have the
4644              option of ignoring.  */
4645           return 1;
4646
4647         default:
4648           trace_debug ("Agent expression op 0x%x not recognized", op);
4649           /* Don't struggle on, things will just get worse.  */
4650           return expr_eval_unrecognized_opcode;
4651         }
4652
4653       /* Check for stack badness.  */
4654       if (sp >= (STACK_MAX - 1))
4655         {
4656           trace_debug ("Expression stack overflow");
4657           return expr_eval_stack_overflow;
4658         }
4659
4660       if (sp < 0)
4661         {
4662           trace_debug ("Expression stack underflow");
4663           return expr_eval_stack_underflow;
4664         }
4665
4666       trace_debug ("Op %s -> sp=%d, top=0x%s",
4667                    gdb_agent_op_names[op], sp, pulongest (top));
4668     }
4669 }
4670
4671 /* Do memory copies for bytecodes.  */
4672 /* Do the recording of memory blocks for actions and bytecodes.  */
4673
4674 static int
4675 agent_mem_read (struct traceframe *tframe,
4676                 unsigned char *to, CORE_ADDR from, ULONGEST len)
4677 {
4678   unsigned char *mspace;
4679   ULONGEST remaining = len;
4680   unsigned short blocklen;
4681
4682   /* If a 'to' buffer is specified, use it.  */
4683   if (to != NULL)
4684     {
4685       read_inferior_memory (from, to, len);
4686       return 0;
4687     }
4688
4689   /* Otherwise, create a new memory block in the trace buffer.  */
4690   while (remaining > 0)
4691     {
4692       size_t sp;
4693
4694       blocklen = (remaining > 65535 ? 65535 : remaining);
4695       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4696       mspace = add_traceframe_block (tframe, sp);
4697       if (mspace == NULL)
4698         return 1;
4699       /* Identify block as a memory block.  */
4700       *mspace = 'M';
4701       ++mspace;
4702       /* Record address and size.  */
4703       memcpy (mspace, &from, sizeof (from));
4704       mspace += sizeof (from);
4705       memcpy (mspace, &blocklen, sizeof (blocklen));
4706       mspace += sizeof (blocklen);
4707       /* Record the memory block proper.  */
4708       read_inferior_memory (from, mspace, blocklen);
4709       trace_debug ("%d bytes recorded", blocklen);
4710       remaining -= blocklen;
4711       from += blocklen;
4712     }
4713   return 0;
4714 }
4715
4716 /* Record the value of a trace state variable.  */
4717
4718 static int
4719 agent_tsv_read (struct traceframe *tframe, int n)
4720 {
4721   unsigned char *vspace;
4722   LONGEST val;
4723
4724   vspace = add_traceframe_block (tframe,
4725                                  1 + sizeof (n) + sizeof (LONGEST));
4726   if (vspace == NULL)
4727     return 1;
4728   /* Identify block as a variable.  */
4729   *vspace = 'V';
4730   /* Record variable's number and value.  */
4731   memcpy (vspace + 1, &n, sizeof (n));
4732   val = get_trace_state_variable_value (n);
4733   memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
4734   trace_debug ("Variable %d recorded", n);
4735   return 0;
4736 }
4737
4738 #ifndef IN_PROCESS_AGENT
4739
4740 static unsigned char *
4741 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
4742                             int tfnum, char type_wanted)
4743 {
4744   unsigned char *dataptr;
4745
4746   if (datasize == 0)
4747     {
4748       trace_debug ("traceframe %d has no data", tfnum);
4749       return NULL;
4750     }
4751
4752   /* Iterate through a traceframe's blocks, looking for a block of the
4753      requested type.  */
4754   for (dataptr = database;
4755        dataptr < database + datasize;
4756        /* nothing */)
4757     {
4758       char blocktype;
4759       unsigned short mlen;
4760
4761       if (dataptr == trace_buffer_wrap)
4762         {
4763           /* Adjust to reflect wrapping part of the frame around to
4764              the beginning.  */
4765           datasize = dataptr - database;
4766           dataptr = database = trace_buffer_lo;
4767         }
4768       blocktype = *dataptr++;
4769
4770       if (type_wanted == blocktype)
4771         return dataptr;
4772
4773       switch (blocktype)
4774         {
4775         case 'R':
4776           /* Skip over the registers block.  */
4777           dataptr += register_cache_size ();
4778           break;
4779         case 'M':
4780           /* Skip over the memory block.  */
4781           dataptr += sizeof (CORE_ADDR);
4782           memcpy (&mlen, dataptr, sizeof (mlen));
4783           dataptr += (sizeof (mlen) + mlen);
4784           break;
4785         case 'V':
4786           /* Skip over the TSV block.  */
4787           dataptr += (sizeof (int) + sizeof (LONGEST));
4788           break;
4789         case 'S':
4790           /* Skip over the static trace data block.  */
4791           memcpy (&mlen, dataptr, sizeof (mlen));
4792           dataptr += (sizeof (mlen) + mlen);
4793           break;
4794         default:
4795           trace_debug ("traceframe %d has unknown block type 0x%x",
4796                        tfnum, blocktype);
4797           return NULL;
4798         }
4799     }
4800
4801   return NULL;
4802 }
4803
4804 static unsigned char *
4805 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
4806 {
4807   unsigned char *regblock;
4808
4809   regblock = traceframe_find_block_type (tframe->data,
4810                                          tframe->data_size,
4811                                          tfnum, 'R');
4812
4813   if (regblock == NULL)
4814     trace_debug ("traceframe %d has no register data", tfnum);
4815
4816   return regblock;
4817 }
4818
4819 /* Get registers from a traceframe.  */
4820
4821 int
4822 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
4823 {
4824   unsigned char *dataptr;
4825   struct tracepoint *tpoint;
4826   struct traceframe *tframe;
4827
4828   tframe = find_traceframe (tfnum);
4829
4830   if (tframe == NULL)
4831     {
4832       trace_debug ("traceframe %d not found", tfnum);
4833       return 1;
4834     }
4835
4836   dataptr = traceframe_find_regblock (tframe, tfnum);
4837   if (dataptr == NULL)
4838     {
4839       /* We don't like making up numbers, but GDB has all manner of
4840          troubles when the target says there are no registers.  */
4841       supply_regblock (regcache, NULL);
4842
4843       /* We can generally guess at a PC, although this will be
4844          misleading for while-stepping frames and multi-location
4845          tracepoints.  */
4846       tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
4847       if (tpoint != NULL)
4848         regcache_write_pc (regcache, tpoint->address);
4849     }
4850   else
4851     supply_regblock (regcache, dataptr);
4852
4853   return 0;
4854 }
4855
4856 static CORE_ADDR
4857 traceframe_get_pc (struct traceframe *tframe)
4858 {
4859   struct regcache regcache;
4860   unsigned char *dataptr;
4861
4862   dataptr = traceframe_find_regblock (tframe, -1);
4863   if (dataptr == NULL)
4864     return 0;
4865
4866   init_register_cache (&regcache, dataptr);
4867   return regcache_read_pc (&regcache);
4868 }
4869
4870 /* Read a requested block of memory from a trace frame.  */
4871
4872 int
4873 traceframe_read_mem (int tfnum, CORE_ADDR addr,
4874                      unsigned char *buf, ULONGEST length,
4875                      ULONGEST *nbytes)
4876 {
4877   struct traceframe *tframe;
4878   unsigned char *database, *dataptr;
4879   unsigned int datasize;
4880   CORE_ADDR maddr;
4881   unsigned short mlen;
4882
4883   trace_debug ("traceframe_read_mem");
4884
4885   tframe = find_traceframe (tfnum);
4886
4887   if (!tframe)
4888     {
4889       trace_debug ("traceframe %d not found", tfnum);
4890       return 1;
4891     }
4892
4893   datasize = tframe->data_size;
4894   database = dataptr = &tframe->data[0];
4895
4896   /* Iterate through a traceframe's blocks, looking for memory.  */
4897   while ((dataptr = traceframe_find_block_type (dataptr,
4898                                                 datasize - (dataptr - database),
4899                                                 tfnum, 'M')) != NULL)
4900     {
4901       memcpy (&maddr, dataptr, sizeof (maddr));
4902       dataptr += sizeof (maddr);
4903       memcpy (&mlen, dataptr, sizeof (mlen));
4904       dataptr += sizeof (mlen);
4905       trace_debug ("traceframe %d has %d bytes at %s",
4906                    tfnum, mlen, paddress (maddr));
4907
4908       /* Check that requested data is in bounds.  */
4909       if (maddr <= addr && (addr + length) <= (maddr + mlen))
4910         {
4911           /* Block includes the requested range, copy it out.  */
4912           memcpy (buf, dataptr + (addr - maddr), length);
4913           *nbytes = length;
4914           return 0;
4915         }
4916
4917       /* Skip over this block.  */
4918       dataptr += mlen;
4919     }
4920
4921   trace_debug ("traceframe %d has no memory data for the desired region",
4922                tfnum);
4923
4924   *nbytes = 0;
4925   return 0;
4926 }
4927
4928 static int
4929 traceframe_read_tsv (int tsvnum, LONGEST *val)
4930 {
4931   int tfnum;
4932   struct traceframe *tframe;
4933   unsigned char *database, *dataptr;
4934   unsigned int datasize;
4935   int vnum;
4936
4937   trace_debug ("traceframe_read_tsv");
4938
4939   tfnum = current_traceframe;
4940
4941   if (tfnum < 0)
4942     {
4943       trace_debug ("no current traceframe");
4944       return 1;
4945     }
4946
4947   tframe = find_traceframe (tfnum);
4948
4949   if (tframe == NULL)
4950     {
4951       trace_debug ("traceframe %d not found", tfnum);
4952       return 1;
4953     }
4954
4955   datasize = tframe->data_size;
4956   database = dataptr = &tframe->data[0];
4957
4958   /* Iterate through a traceframe's blocks, looking for the tsv.  */
4959   while ((dataptr = traceframe_find_block_type (dataptr,
4960                                                 datasize - (dataptr - database),
4961                                                 tfnum, 'V')) != NULL)
4962     {
4963       memcpy (&vnum, dataptr, sizeof (vnum));
4964       dataptr += sizeof (vnum);
4965
4966       trace_debug ("traceframe %d has variable %d", tfnum, vnum);
4967
4968       /* Check that this is the variable we want.  */
4969       if (tsvnum == vnum)
4970         {
4971           memcpy (val, dataptr, sizeof (*val));
4972           return 0;
4973         }
4974
4975       /* Skip over this block.  */
4976       dataptr += sizeof (LONGEST);
4977     }
4978
4979   trace_debug ("traceframe %d has no data for variable %d",
4980                tfnum, tsvnum);
4981   return 1;
4982 }
4983
4984 /* Read a requested block of static tracepoint data from a trace
4985    frame.  */
4986
4987 int
4988 traceframe_read_sdata (int tfnum, ULONGEST offset,
4989                        unsigned char *buf, ULONGEST length,
4990                        ULONGEST *nbytes)
4991 {
4992   struct traceframe *tframe;
4993   unsigned char *database, *dataptr;
4994   unsigned int datasize;
4995   unsigned short mlen;
4996
4997   trace_debug ("traceframe_read_sdata");
4998
4999   tframe = find_traceframe (tfnum);
5000
5001   if (!tframe)
5002     {
5003       trace_debug ("traceframe %d not found", tfnum);
5004       return 1;
5005     }
5006
5007   datasize = tframe->data_size;
5008   database = &tframe->data[0];
5009
5010   /* Iterate through a traceframe's blocks, looking for static
5011      tracepoint data.  */
5012   dataptr = traceframe_find_block_type (database, datasize,
5013                                         tfnum, 'S');
5014   if (dataptr != NULL)
5015     {
5016       memcpy (&mlen, dataptr, sizeof (mlen));
5017       dataptr += sizeof (mlen);
5018       if (offset < mlen)
5019         {
5020           if (offset + length > mlen)
5021             length = mlen - offset;
5022
5023           memcpy (buf, dataptr, length);
5024           *nbytes = length;
5025         }
5026       else
5027         *nbytes = 0;
5028       return 0;
5029     }
5030
5031   trace_debug ("traceframe %d has no static trace data", tfnum);
5032
5033   *nbytes = 0;
5034   return 0;
5035 }
5036
5037 /* Return the first fast tracepoint whose jump pad contains PC.  */
5038
5039 static struct tracepoint *
5040 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5041 {
5042   struct tracepoint *tpoint;
5043
5044   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5045     if (tpoint->type == fast_tracepoint)
5046       if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5047         return tpoint;
5048
5049   return NULL;
5050 }
5051
5052 /* Return GDBserver's tracepoint that matches the IP Agent's
5053    tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5054    address space.  */
5055
5056 static struct tracepoint *
5057 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5058 {
5059   struct tracepoint *tpoint;
5060
5061   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5062     if (tpoint->type == fast_tracepoint)
5063       if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5064         return tpoint;
5065
5066   return NULL;
5067 }
5068
5069 #endif
5070
5071 /* The type of the object that is used to synchronize fast tracepoint
5072    collection.  */
5073
5074 typedef struct collecting_t
5075 {
5076   /* The fast tracepoint number currently collecting.  */
5077   uintptr_t tpoint;
5078
5079   /* A number that GDBserver can use to identify the thread that is
5080      presently holding the collect lock.  This need not (and usually
5081      is not) the thread id, as getting the current thread ID usually
5082      requires a system call, which we want to avoid like the plague.
5083      Usually this is thread's TCB, found in the TLS (pseudo-)
5084      register, which is readable with a single insn on several
5085      architectures.  */
5086   uintptr_t thread_area;
5087 } collecting_t;
5088
5089 #ifndef IN_PROCESS_AGENT
5090
5091 void
5092 force_unlock_trace_buffer (void)
5093 {
5094   write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5095 }
5096
5097 /* Check if the thread identified by THREAD_AREA which is stopped at
5098    STOP_PC, is presently locking the fast tracepoint collection, and
5099    if so, gather some status of said collection.  Returns 0 if the
5100    thread isn't collecting or in the jump pad at all.  1, if in the
5101    jump pad (or within gdb_collect) and hasn't executed the adjusted
5102    original insn yet (can set a breakpoint there and run to it).  2,
5103    if presently executing the adjusted original insn --- in which
5104    case, if we want to move the thread out of the jump pad, we need to
5105    single-step it until this function returns 0.  */
5106
5107 int
5108 fast_tracepoint_collecting (CORE_ADDR thread_area,
5109                             CORE_ADDR stop_pc,
5110                             struct fast_tpoint_collect_status *status)
5111 {
5112   CORE_ADDR ipa_collecting;
5113   CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5114   struct tracepoint *tpoint;
5115   int needs_breakpoint;
5116
5117   /* The thread THREAD_AREA is either:
5118
5119       0. not collecting at all, not within the jump pad, or within
5120          gdb_collect or one of its callees.
5121
5122       1. in the jump pad and haven't reached gdb_collect
5123
5124       2. within gdb_collect (out of the jump pad) (collect is set)
5125
5126       3. we're in the jump pad, after gdb_collect having returned,
5127          possibly executing the adjusted insns.
5128
5129       For cases 1 and 3, `collecting' may or not be set.  The jump pad
5130       doesn't have any complicated jump logic, so we can tell if the
5131       thread is executing the adjust original insn or not by just
5132       matching STOP_PC with known jump pad addresses.  If we it isn't
5133       yet executing the original insn, set a breakpoint there, and let
5134       the thread run to it, so to quickly step over a possible (many
5135       insns) gdb_collect call.  Otherwise, or when the breakpoint is
5136       hit, only a few (small number of) insns are left to be executed
5137       in the jump pad.  Single-step the thread until it leaves the
5138       jump pad.  */
5139
5140  again:
5141   tpoint = NULL;
5142   needs_breakpoint = 0;
5143   trace_debug ("fast_tracepoint_collecting");
5144
5145   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5146                                   &ipa_gdb_jump_pad_buffer))
5147     fatal ("error extracting `gdb_jump_pad_buffer'");
5148   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5149                                   &ipa_gdb_jump_pad_buffer_end))
5150     fatal ("error extracting `gdb_jump_pad_buffer_end'");
5151
5152   if (ipa_gdb_jump_pad_buffer <= stop_pc && stop_pc < ipa_gdb_jump_pad_buffer_end)
5153     {
5154       /* We can tell which tracepoint(s) the thread is collecting by
5155          matching the jump pad address back to the tracepoint.  */
5156       tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5157       if (tpoint == NULL)
5158         {
5159           warning ("in jump pad, but no matching tpoint?");
5160           return 0;
5161         }
5162       else
5163         {
5164           trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5165                        "adj_insn(%s, %s)",
5166                        tpoint->number, paddress (tpoint->address),
5167                        paddress (tpoint->jump_pad),
5168                        paddress (tpoint->jump_pad_end),
5169                        paddress (tpoint->adjusted_insn_addr),
5170                        paddress (tpoint->adjusted_insn_addr_end));
5171         }
5172
5173       /* Definitely in the jump pad.  May or may not need
5174          fast-exit-jump-pad breakpoint.  */
5175       if (tpoint->jump_pad <= stop_pc
5176           && stop_pc < tpoint->adjusted_insn_addr)
5177         needs_breakpoint =  1;
5178     }
5179   else
5180     {
5181       collecting_t ipa_collecting_obj;
5182
5183       /* If `collecting' is set/locked, then the THREAD_AREA thread
5184          may or not be the one holding the lock.  We have to read the
5185          lock to find out.  */
5186
5187       if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5188                                       &ipa_collecting))
5189         {
5190           trace_debug ("fast_tracepoint_collecting:"
5191                        " failed reading 'collecting' in the inferior");
5192           return 0;
5193         }
5194
5195       if (!ipa_collecting)
5196         {
5197           trace_debug ("fast_tracepoint_collecting: not collecting"
5198                        " (and nobody is).");
5199           return 0;
5200         }
5201
5202       /* Some thread is collecting.  Check which.  */
5203       if (read_inferior_memory (ipa_collecting,
5204                                 (unsigned char *) &ipa_collecting_obj,
5205                                 sizeof (ipa_collecting_obj)) != 0)
5206         goto again;
5207
5208       if (ipa_collecting_obj.thread_area != thread_area)
5209         {
5210           trace_debug ("fast_tracepoint_collecting: not collecting "
5211                        "(another thread is)");
5212           return 0;
5213         }
5214
5215       tpoint
5216         = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5217       if (tpoint == NULL)
5218         {
5219           warning ("fast_tracepoint_collecting: collecting, "
5220                    "but tpoint %s not found?",
5221                    paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5222           return 0;
5223         }
5224
5225       /* The thread is within `gdb_collect', skip over the rest of
5226          fast tracepoint collection quickly using a breakpoint.  */
5227       needs_breakpoint = 1;
5228     }
5229
5230   /* The caller wants a bit of status detail.  */
5231   if (status != NULL)
5232     {
5233       status->tpoint_num = tpoint->number;
5234       status->tpoint_addr = tpoint->address;
5235       status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5236       status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5237     }
5238
5239   if (needs_breakpoint)
5240     {
5241       /* Hasn't executed the original instruction yet.  Set breakpoint
5242          there, and wait till it's hit, then single-step until exiting
5243          the jump pad.  */
5244
5245       trace_debug ("\
5246 fast_tracepoint_collecting, returning continue-until-break at %s",
5247                    paddress (tpoint->adjusted_insn_addr));
5248
5249       return 1; /* continue */
5250     }
5251   else
5252     {
5253       /* Just single-step until exiting the jump pad.  */
5254
5255       trace_debug ("fast_tracepoint_collecting, returning "
5256                    "need-single-step (%s-%s)",
5257                    paddress (tpoint->adjusted_insn_addr),
5258                    paddress (tpoint->adjusted_insn_addr_end));
5259
5260       return 2; /* single-step */
5261     }
5262 }
5263
5264 #endif
5265
5266 #ifdef IN_PROCESS_AGENT
5267
5268 /* The global fast tracepoint collect lock.  Points to a collecting_t
5269    object built on the stack by the jump pad, if presently locked;
5270    NULL if it isn't locked.  Note that this lock *must* be set while
5271    executing any *function other than the jump pad.  See
5272    fast_tracepoint_collecting.  */
5273 static collecting_t * ATTR_USED collecting;
5274
5275 /* This routine, called from the jump pad (in asm) is designed to be
5276    called from the jump pads of fast tracepoints, thus it is on the
5277    critical path.  */
5278
5279 IP_AGENT_EXPORT void ATTR_USED
5280 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5281 {
5282   struct fast_tracepoint_ctx ctx;
5283
5284   /* Don't do anything until the trace run is completely set up.  */
5285   if (!tracing)
5286     return;
5287
5288   ctx.base.type = fast_tracepoint;
5289   ctx.regs = regs;
5290   ctx.regcache_initted = 0;
5291   ctx.tpoint = tpoint;
5292
5293   /* Wrap the regblock in a register cache (in the stack, we don't
5294      want to malloc here).  */
5295   ctx.regspace = alloca (register_cache_size ());
5296   if (ctx.regspace == NULL)
5297     {
5298       trace_debug ("Trace buffer block allocation failed, skipping");
5299       return;
5300     }
5301
5302   /* Test the condition if present, and collect if true.  */
5303   if (tpoint->cond == NULL
5304       || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5305                                        tpoint))
5306     {
5307       collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5308                                   tpoint->address, tpoint);
5309
5310       /* Note that this will cause original insns to be written back
5311          to where we jumped from, but that's OK because we're jumping
5312          back to the next whole instruction.  This will go badly if
5313          instruction restoration is not atomic though.  */
5314       if (stopping_tracepoint
5315           || trace_buffer_is_full
5316           || expr_eval_result != expr_eval_no_error)
5317         stop_tracing ();
5318     }
5319   else
5320     {
5321       /* If there was a condition and it evaluated to false, the only
5322          way we would stop tracing is if there was an error during
5323          condition expression evaluation.  */
5324       if (expr_eval_result != expr_eval_no_error)
5325         stop_tracing ();
5326     }
5327 }
5328
5329 #endif
5330
5331 #ifndef IN_PROCESS_AGENT
5332
5333 /* Bytecode compilation.  */
5334
5335 CORE_ADDR current_insn_ptr;
5336
5337 int emit_error;
5338
5339 struct bytecode_address
5340 {
5341   int pc;
5342   CORE_ADDR address;
5343   int goto_pc;
5344   /* Offset and size of field to be modified in the goto block.  */
5345   int from_offset, from_size;
5346   struct bytecode_address *next;
5347 } *bytecode_address_table;
5348
5349 CORE_ADDR
5350 get_raw_reg_func_addr (void)
5351 {
5352   return ipa_sym_addrs.addr_get_raw_reg;
5353 }
5354
5355 static void
5356 emit_prologue (void)
5357 {
5358   target_emit_ops ()->emit_prologue ();
5359 }
5360
5361 static void
5362 emit_epilogue (void)
5363 {
5364   target_emit_ops ()->emit_epilogue ();
5365 }
5366
5367 static void
5368 emit_add (void)
5369 {
5370   target_emit_ops ()->emit_add ();
5371 }
5372
5373 static void
5374 emit_sub (void)
5375 {
5376   target_emit_ops ()->emit_sub ();
5377 }
5378
5379 static void
5380 emit_mul (void)
5381 {
5382   target_emit_ops ()->emit_mul ();
5383 }
5384
5385 static void
5386 emit_lsh (void)
5387 {
5388   target_emit_ops ()->emit_lsh ();
5389 }
5390
5391 static void
5392 emit_rsh_signed (void)
5393 {
5394   target_emit_ops ()->emit_rsh_signed ();
5395 }
5396
5397 static void
5398 emit_rsh_unsigned (void)
5399 {
5400   target_emit_ops ()->emit_rsh_unsigned ();
5401 }
5402
5403 static void
5404 emit_ext (int arg)
5405 {
5406   target_emit_ops ()->emit_ext (arg);
5407 }
5408
5409 static void
5410 emit_log_not (void)
5411 {
5412   target_emit_ops ()->emit_log_not ();
5413 }
5414
5415 static void
5416 emit_bit_and (void)
5417 {
5418   target_emit_ops ()->emit_bit_and ();
5419 }
5420
5421 static void
5422 emit_bit_or (void)
5423 {
5424   target_emit_ops ()->emit_bit_or ();
5425 }
5426
5427 static void
5428 emit_bit_xor (void)
5429 {
5430   target_emit_ops ()->emit_bit_xor ();
5431 }
5432
5433 static void
5434 emit_bit_not (void)
5435 {
5436   target_emit_ops ()->emit_bit_not ();
5437 }
5438
5439 static void
5440 emit_equal (void)
5441 {
5442   target_emit_ops ()->emit_equal ();
5443 }
5444
5445 static void
5446 emit_less_signed (void)
5447 {
5448   target_emit_ops ()->emit_less_signed ();
5449 }
5450
5451 static void
5452 emit_less_unsigned (void)
5453 {
5454   target_emit_ops ()->emit_less_unsigned ();
5455 }
5456
5457 static void
5458 emit_ref (int size)
5459 {
5460   target_emit_ops ()->emit_ref (size);
5461 }
5462
5463 static void
5464 emit_if_goto (int *offset_p, int *size_p)
5465 {
5466   target_emit_ops ()->emit_if_goto (offset_p, size_p);
5467 }
5468
5469 static void
5470 emit_goto (int *offset_p, int *size_p)
5471 {
5472   target_emit_ops ()->emit_goto (offset_p, size_p);
5473 }
5474
5475 static void
5476 write_goto_address (CORE_ADDR from, CORE_ADDR to, int size)
5477 {
5478   target_emit_ops ()->write_goto_address (from, to, size);
5479 }
5480
5481 static void
5482 emit_const (LONGEST num)
5483 {
5484   target_emit_ops ()->emit_const (num);
5485 }
5486
5487 static void
5488 emit_reg (int reg)
5489 {
5490   target_emit_ops ()->emit_reg (reg);
5491 }
5492
5493 static void
5494 emit_pop (void)
5495 {
5496   target_emit_ops ()->emit_pop ();
5497 }
5498
5499 static void
5500 emit_stack_flush (void)
5501 {
5502   target_emit_ops ()->emit_stack_flush ();
5503 }
5504
5505 static void
5506 emit_zero_ext (int arg)
5507 {
5508   target_emit_ops ()->emit_zero_ext (arg);
5509 }
5510
5511 static void
5512 emit_swap (void)
5513 {
5514   target_emit_ops ()->emit_swap ();
5515 }
5516
5517 static void
5518 emit_stack_adjust (int n)
5519 {
5520   target_emit_ops ()->emit_stack_adjust (n);
5521 }
5522
5523 /* FN's prototype is `LONGEST(*fn)(int)'.  */
5524
5525 static void
5526 emit_int_call_1 (CORE_ADDR fn, int arg1)
5527 {
5528   target_emit_ops ()->emit_int_call_1 (fn, arg1);
5529 }
5530
5531 /* FN's prototype is `void(*fn)(int,LONGEST)'.  */
5532
5533 static void
5534 emit_void_call_2 (CORE_ADDR fn, int arg1)
5535 {
5536   target_emit_ops ()->emit_void_call_2 (fn, arg1);
5537 }
5538
5539 static enum eval_result_type compile_bytecodes (struct agent_expr *aexpr);
5540
5541 static void
5542 compile_tracepoint_condition (struct tracepoint *tpoint, CORE_ADDR *jump_entry)
5543 {
5544   CORE_ADDR entry_point = *jump_entry;
5545   enum eval_result_type err;
5546
5547   trace_debug ("Starting condition compilation for tracepoint %d\n",
5548                tpoint->number);
5549
5550   /* Initialize the global pointer to the code being built.  */
5551   current_insn_ptr = *jump_entry;
5552
5553   emit_prologue ();
5554
5555   err = compile_bytecodes (tpoint->cond);
5556
5557   if (err == expr_eval_no_error)
5558     {
5559       emit_epilogue ();
5560
5561       /* Record the beginning of the compiled code.  */
5562       tpoint->compiled_cond = entry_point;
5563
5564       trace_debug ("Condition compilation for tracepoint %d complete\n",
5565                    tpoint->number);
5566     }
5567   else
5568     {
5569       /* Leave the unfinished code in situ, but don't point to it.  */
5570
5571       tpoint->compiled_cond = 0;
5572
5573       trace_debug ("Condition compilation for tracepoint %d failed, "
5574                    "error code %d",
5575                    tpoint->number, err);
5576     }
5577
5578   /* Update the code pointer passed in.  Note that we do this even if
5579      the compile fails, so that we can look at the partial results
5580      instead of letting them be overwritten.  */
5581   *jump_entry = current_insn_ptr;
5582
5583   /* Leave a gap, to aid dump decipherment.  */
5584   *jump_entry += 16;
5585 }
5586
5587 /* Given an agent expression, turn it into native code.  */
5588
5589 static enum eval_result_type
5590 compile_bytecodes (struct agent_expr *aexpr)
5591 {
5592   int pc = 0;
5593   int done = 0;
5594   unsigned char op;
5595   int arg;
5596   /* This is only used to build 64-bit value for constants.  */
5597   ULONGEST top;
5598   struct bytecode_address *aentry, *aentry2;
5599
5600 #define UNHANDLED                                       \
5601   do                                                    \
5602     {                                                   \
5603       trace_debug ("Cannot compile op 0x%x\n", op);     \
5604       return expr_eval_unhandled_opcode;                \
5605     } while (0)
5606
5607   if (aexpr->length == 0)
5608     {
5609       trace_debug ("empty agent expression\n");
5610       return expr_eval_empty_expression;
5611     }
5612
5613   bytecode_address_table = NULL;
5614
5615   while (!done)
5616     {
5617       op = aexpr->bytes[pc];
5618
5619       trace_debug ("About to compile op 0x%x, pc=%d\n", op, pc);
5620
5621       /* Record the compiled-code address of the bytecode, for use by
5622          jump instructions.  */
5623       aentry = xmalloc (sizeof (struct bytecode_address));
5624       aentry->pc = pc;
5625       aentry->address = current_insn_ptr;
5626       aentry->goto_pc = -1;
5627       aentry->from_offset = aentry->from_size = 0;
5628       aentry->next = bytecode_address_table;
5629       bytecode_address_table = aentry;
5630
5631       ++pc;
5632
5633       emit_error = 0;
5634
5635       switch (op)
5636         {
5637         case gdb_agent_op_add:
5638           emit_add ();
5639           break;
5640
5641         case gdb_agent_op_sub:
5642           emit_sub ();
5643           break;
5644
5645         case gdb_agent_op_mul:
5646           emit_mul ();
5647           break;
5648
5649         case gdb_agent_op_div_signed:
5650           UNHANDLED;
5651           break;
5652
5653         case gdb_agent_op_div_unsigned:
5654           UNHANDLED;
5655           break;
5656
5657         case gdb_agent_op_rem_signed:
5658           UNHANDLED;
5659           break;
5660
5661         case gdb_agent_op_rem_unsigned:
5662           UNHANDLED;
5663           break;
5664
5665         case gdb_agent_op_lsh:
5666           emit_lsh ();
5667           break;
5668
5669         case gdb_agent_op_rsh_signed:
5670           emit_rsh_signed ();
5671           break;
5672
5673         case gdb_agent_op_rsh_unsigned:
5674           emit_rsh_unsigned ();
5675           break;
5676
5677         case gdb_agent_op_trace:
5678           UNHANDLED;
5679           break;
5680
5681         case gdb_agent_op_trace_quick:
5682           UNHANDLED;
5683           break;
5684
5685         case gdb_agent_op_log_not:
5686           emit_log_not ();
5687           break;
5688
5689         case gdb_agent_op_bit_and:
5690           emit_bit_and ();
5691           break;
5692
5693         case gdb_agent_op_bit_or:
5694           emit_bit_or ();
5695           break;
5696
5697         case gdb_agent_op_bit_xor:
5698           emit_bit_xor ();
5699           break;
5700
5701         case gdb_agent_op_bit_not:
5702           emit_bit_not ();
5703           break;
5704
5705         case gdb_agent_op_equal:
5706           emit_equal ();
5707           break;
5708
5709         case gdb_agent_op_less_signed:
5710           emit_less_signed ();
5711           break;
5712
5713         case gdb_agent_op_less_unsigned:
5714           emit_less_unsigned ();
5715           break;
5716
5717         case gdb_agent_op_ext:
5718           arg = aexpr->bytes[pc++];
5719           if (arg < (sizeof (LONGEST) * 8))
5720             emit_ext (arg);
5721           break;
5722
5723         case gdb_agent_op_ref8:
5724           emit_ref (1);
5725           break;
5726
5727         case gdb_agent_op_ref16:
5728           emit_ref (2);
5729           break;
5730
5731         case gdb_agent_op_ref32:
5732           emit_ref (4);
5733           break;
5734
5735         case gdb_agent_op_ref64:
5736           emit_ref (8);
5737           break;
5738
5739         case gdb_agent_op_if_goto:
5740           arg = aexpr->bytes[pc++];
5741           arg = (arg << 8) + aexpr->bytes[pc++];
5742           aentry->goto_pc = arg;
5743           emit_if_goto (&(aentry->from_offset), &(aentry->from_size));
5744           break;
5745
5746         case gdb_agent_op_goto:
5747           arg = aexpr->bytes[pc++];
5748           arg = (arg << 8) + aexpr->bytes[pc++];
5749           aentry->goto_pc = arg;
5750           emit_goto (&(aentry->from_offset), &(aentry->from_size));
5751           break;
5752
5753         case gdb_agent_op_const8:
5754           emit_stack_flush ();
5755           top = aexpr->bytes[pc++];
5756           emit_const (top);
5757           break;
5758
5759         case gdb_agent_op_const16:
5760           emit_stack_flush ();
5761           top = aexpr->bytes[pc++];
5762           top = (top << 8) + aexpr->bytes[pc++];
5763           emit_const (top);
5764           break;
5765
5766         case gdb_agent_op_const32:
5767           emit_stack_flush ();
5768           top = aexpr->bytes[pc++];
5769           top = (top << 8) + aexpr->bytes[pc++];
5770           top = (top << 8) + aexpr->bytes[pc++];
5771           top = (top << 8) + aexpr->bytes[pc++];
5772           emit_const (top);
5773           break;
5774
5775         case gdb_agent_op_const64:
5776           emit_stack_flush ();
5777           top = aexpr->bytes[pc++];
5778           top = (top << 8) + aexpr->bytes[pc++];
5779           top = (top << 8) + aexpr->bytes[pc++];
5780           top = (top << 8) + aexpr->bytes[pc++];
5781           top = (top << 8) + aexpr->bytes[pc++];
5782           top = (top << 8) + aexpr->bytes[pc++];
5783           top = (top << 8) + aexpr->bytes[pc++];
5784           top = (top << 8) + aexpr->bytes[pc++];
5785           emit_const (top);
5786           break;
5787
5788         case gdb_agent_op_reg:
5789           emit_stack_flush ();
5790           arg = aexpr->bytes[pc++];
5791           arg = (arg << 8) + aexpr->bytes[pc++];
5792           emit_reg (arg);
5793           break;
5794
5795         case gdb_agent_op_end:
5796           trace_debug ("At end of expression\n");
5797
5798           /* Assume there is one stack element left, and that it is
5799              cached in "top" where emit_epilogue can get to it.  */
5800           emit_stack_adjust (1);
5801
5802           done = 1;
5803           break;
5804
5805         case gdb_agent_op_dup:
5806           /* In our design, dup is equivalent to stack flushing.  */
5807           emit_stack_flush ();
5808           break;
5809
5810         case gdb_agent_op_pop:
5811           emit_pop ();
5812           break;
5813
5814         case gdb_agent_op_zero_ext:
5815           arg = aexpr->bytes[pc++];
5816           if (arg < (sizeof (LONGEST) * 8))
5817             emit_zero_ext (arg);
5818           break;
5819
5820         case gdb_agent_op_swap:
5821           emit_swap ();
5822           break;
5823
5824         case gdb_agent_op_getv:
5825           emit_stack_flush ();
5826           arg = aexpr->bytes[pc++];
5827           arg = (arg << 8) + aexpr->bytes[pc++];
5828           emit_int_call_1 (ipa_sym_addrs.addr_get_trace_state_variable_value,
5829                            arg);
5830           break;
5831
5832         case gdb_agent_op_setv:
5833           arg = aexpr->bytes[pc++];
5834           arg = (arg << 8) + aexpr->bytes[pc++];
5835           emit_void_call_2 (ipa_sym_addrs.addr_set_trace_state_variable_value,
5836                             arg);
5837           break;
5838
5839         case gdb_agent_op_tracev:
5840           UNHANDLED;
5841           break;
5842
5843           /* GDB never (currently) generates any of these ops.  */
5844         case gdb_agent_op_float:
5845         case gdb_agent_op_ref_float:
5846         case gdb_agent_op_ref_double:
5847         case gdb_agent_op_ref_long_double:
5848         case gdb_agent_op_l_to_d:
5849         case gdb_agent_op_d_to_l:
5850         case gdb_agent_op_trace16:
5851           UNHANDLED;
5852           break;
5853
5854         default:
5855           trace_debug ("Agent expression op 0x%x not recognized\n", op);
5856           /* Don't struggle on, things will just get worse.  */
5857           return expr_eval_unrecognized_opcode;
5858         }
5859
5860       /* This catches errors that occur in target-specific code
5861          emission.  */
5862       if (emit_error)
5863         {
5864           trace_debug ("Error %d while emitting code for %s\n",
5865                        emit_error, gdb_agent_op_names[op]);
5866           return expr_eval_unhandled_opcode;
5867         }
5868
5869       trace_debug ("Op %s compiled\n", gdb_agent_op_names[op]);
5870     }
5871
5872   /* Now fill in real addresses as goto destinations.  */
5873   for (aentry = bytecode_address_table; aentry; aentry = aentry->next)
5874     {
5875       int written = 0;
5876
5877       if (aentry->goto_pc < 0)
5878         continue;
5879
5880       /* Find the location that we are going to, and call back into
5881          target-specific code to write the actual address or
5882          displacement.  */
5883       for (aentry2 = bytecode_address_table; aentry2; aentry2 = aentry2->next)
5884         {
5885           if (aentry2->pc == aentry->goto_pc)
5886             {
5887               trace_debug ("Want to jump from %s to %s\n",
5888                            paddress (aentry->address),
5889                            paddress (aentry2->address));
5890               write_goto_address (aentry->address + aentry->from_offset,
5891                                   aentry2->address, aentry->from_size);
5892               written = 1;
5893               break;
5894             }
5895         }
5896
5897       /* Error out if we didn't find a destination.  */
5898       if (!written)
5899         {
5900           trace_debug ("Destination of goto %d not found\n",
5901                        aentry->goto_pc);
5902           return expr_eval_invalid_goto;
5903         }
5904     }
5905
5906   return expr_eval_no_error;
5907 }
5908
5909 /* We'll need to adjust these when we consider bi-arch setups, and big
5910    endian machines.  */
5911
5912 static int
5913 write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr)
5914 {
5915   return write_inferior_memory (where,
5916                                 (unsigned char *) &ptr, sizeof (void *));
5917 }
5918
5919 /* The base pointer of the IPA's heap.  This is the only memory the
5920    IPA is allowed to use.  The IPA should _not_ call the inferior's
5921    `malloc' during operation.  That'd be slow, and, most importantly,
5922    it may not be safe.  We may be collecting a tracepoint in a signal
5923    handler, for example.  */
5924 static CORE_ADDR target_tp_heap;
5925
5926 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5927    to 8 bytes.  */
5928
5929 static CORE_ADDR
5930 target_malloc (ULONGEST size)
5931 {
5932   CORE_ADDR ptr;
5933
5934   if (target_tp_heap == 0)
5935     {
5936       /* We have the pointer *address*, need what it points to.  */
5937       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5938                                       &target_tp_heap))
5939         fatal ("could get target heap head pointer");
5940     }
5941
5942   ptr = target_tp_heap;
5943   target_tp_heap += size;
5944
5945   /* Pad to 8-byte alignment.  */
5946   target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5947
5948   return ptr;
5949 }
5950
5951 static CORE_ADDR
5952 download_agent_expr (struct agent_expr *expr)
5953 {
5954   CORE_ADDR expr_addr;
5955   CORE_ADDR expr_bytes;
5956
5957   expr_addr = target_malloc (sizeof (*expr));
5958   write_inferior_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5959
5960   expr_bytes = target_malloc (expr->length);
5961   write_inferior_data_ptr (expr_addr + offsetof (struct agent_expr, bytes),
5962                            expr_bytes);
5963   write_inferior_memory (expr_bytes, expr->bytes, expr->length);
5964
5965   return expr_addr;
5966 }
5967
5968 /* Align V up to N bits.  */
5969 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5970
5971 static void
5972 download_tracepoints (void)
5973 {
5974   CORE_ADDR tpptr = 0, prev_tpptr = 0;
5975   struct tracepoint *tpoint;
5976
5977   /* Start out empty.  */
5978   write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, 0);
5979
5980   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5981     {
5982       struct tracepoint target_tracepoint;
5983
5984       if (tpoint->type != fast_tracepoint
5985           && tpoint->type != static_tracepoint)
5986         continue;
5987
5988       /* Maybe download a compiled condition.  */
5989       if (tpoint->cond != NULL && target_emit_ops () != NULL)
5990         {
5991           CORE_ADDR jentry, jump_entry;
5992
5993           jentry = jump_entry = get_jump_space_head ();
5994
5995           if (tpoint->cond != NULL)
5996             {
5997               /* Pad to 8-byte alignment. (needed?)  */
5998               /* Actually this should be left for the target to
5999                  decide.  */
6000               jentry = UALIGN (jentry, 8);
6001
6002               compile_tracepoint_condition (tpoint, &jentry);
6003             }
6004
6005           /* Pad to 8-byte alignment.  */
6006           jentry = UALIGN (jentry, 8);
6007           claim_jump_space (jentry - jump_entry);
6008         }
6009
6010       target_tracepoint = *tpoint;
6011
6012       prev_tpptr = tpptr;
6013       tpptr = target_malloc (sizeof (*tpoint));
6014       tpoint->obj_addr_on_target = tpptr;
6015
6016       if (tpoint == tracepoints)
6017         {
6018           /* First object in list, set the head pointer in the
6019              inferior.  */
6020           write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, tpptr);
6021         }
6022       else
6023         {
6024           write_inferior_data_ptr (prev_tpptr + offsetof (struct tracepoint,
6025                                                           next),
6026                                    tpptr);
6027         }
6028
6029       /* Write the whole object.  We'll fix up its pointers in a bit.
6030          Assume no next for now.  This is fixed up above on the next
6031          iteration, if there's any.  */
6032       target_tracepoint.next = NULL;
6033       /* Need to clear this here too, since we're downloading the
6034          tracepoints before clearing our own copy.  */
6035       target_tracepoint.hit_count = 0;
6036
6037       write_inferior_memory (tpptr, (unsigned char *) &target_tracepoint,
6038                              sizeof (target_tracepoint));
6039
6040       if (tpoint->cond)
6041         write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
6042                                                    cond),
6043                                  download_agent_expr (tpoint->cond));
6044
6045       if (tpoint->numactions)
6046         {
6047           int i;
6048           CORE_ADDR actions_array;
6049
6050           /* The pointers array.  */
6051           actions_array
6052             = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
6053           write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
6054                                                      actions),
6055                                    actions_array);
6056
6057           /* Now for each pointer, download the action.  */
6058           for (i = 0; i < tpoint->numactions; i++)
6059             {
6060               CORE_ADDR ipa_action = 0;
6061               struct tracepoint_action *action = tpoint->actions[i];
6062
6063               switch (action->type)
6064                 {
6065                 case 'M':
6066                   ipa_action
6067                     = target_malloc (sizeof (struct collect_memory_action));
6068                   write_inferior_memory (ipa_action,
6069                                          (unsigned char *) action,
6070                                          sizeof (struct collect_memory_action));
6071                   break;
6072                 case 'R':
6073                   ipa_action
6074                     = target_malloc (sizeof (struct collect_registers_action));
6075                   write_inferior_memory (ipa_action,
6076                                          (unsigned char *) action,
6077                                          sizeof (struct collect_registers_action));
6078                   break;
6079                 case 'X':
6080                   {
6081                     CORE_ADDR expr;
6082                     struct eval_expr_action *eaction
6083                       = (struct eval_expr_action *) action;
6084
6085                     ipa_action = target_malloc (sizeof (*eaction));
6086                     write_inferior_memory (ipa_action,
6087                                            (unsigned char *) eaction,
6088                                            sizeof (*eaction));
6089
6090                     expr = download_agent_expr (eaction->expr);
6091                     write_inferior_data_ptr
6092                       (ipa_action + offsetof (struct eval_expr_action, expr),
6093                        expr);
6094                     break;
6095                   }
6096                 case 'L':
6097                   ipa_action = target_malloc
6098                     (sizeof (struct collect_static_trace_data_action));
6099                   write_inferior_memory
6100                     (ipa_action,
6101                      (unsigned char *) action,
6102                      sizeof (struct collect_static_trace_data_action));
6103                   break;
6104                 default:
6105                   trace_debug ("unknown trace action '%c', ignoring",
6106                                action->type);
6107                   break;
6108                 }
6109
6110               if (ipa_action != 0)
6111                 write_inferior_data_ptr
6112                   (actions_array + i * sizeof (sizeof (*tpoint->actions)),
6113                    ipa_action);
6114             }
6115         }
6116     }
6117 }
6118
6119 static void
6120 download_trace_state_variables (void)
6121 {
6122   CORE_ADDR ptr = 0, prev_ptr = 0;
6123   struct trace_state_variable *tsv;
6124
6125   /* Start out empty.  */
6126   write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables, 0);
6127
6128   for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
6129     {
6130       struct trace_state_variable target_tsv;
6131
6132       /* TSV's with a getter have been initialized equally in both the
6133          inferior and GDBserver.  Skip them.  */
6134       if (tsv->getter != NULL)
6135         continue;
6136
6137       target_tsv = *tsv;
6138
6139       prev_ptr = ptr;
6140       ptr = target_malloc (sizeof (*tsv));
6141
6142       if (tsv == trace_state_variables)
6143         {
6144           /* First object in list, set the head pointer in the
6145              inferior.  */
6146
6147           write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables,
6148                                    ptr);
6149         }
6150       else
6151         {
6152           write_inferior_data_ptr (prev_ptr
6153                                    + offsetof (struct trace_state_variable,
6154                                                next),
6155                                    ptr);
6156         }
6157
6158       /* Write the whole object.  We'll fix up its pointers in a bit.
6159          Assume no next, fixup when needed.  */
6160       target_tsv.next = NULL;
6161
6162       write_inferior_memory (ptr, (unsigned char *) &target_tsv,
6163                              sizeof (target_tsv));
6164
6165       if (tsv->name != NULL)
6166         {
6167           size_t size = strlen (tsv->name) + 1;
6168           CORE_ADDR name_addr = target_malloc (size);
6169           write_inferior_memory (name_addr,
6170                                  (unsigned char *) tsv->name, size);
6171           write_inferior_data_ptr (ptr
6172                                    + offsetof (struct trace_state_variable,
6173                                                name),
6174                                    name_addr);
6175         }
6176
6177       if (tsv->getter != NULL)
6178         {
6179           fatal ("what to do with these?");
6180         }
6181     }
6182
6183   if (prev_ptr != 0)
6184     {
6185       /* Fixup the next pointer in the last item in the list.  */
6186       write_inferior_data_ptr (prev_ptr + offsetof (struct trace_state_variable,
6187                                                     next), 0);
6188     }
6189 }
6190
6191 /* Upload complete trace frames out of the IP Agent's trace buffer
6192    into GDBserver's trace buffer.  This always uploads either all or
6193    no trace frames.  This is the counter part of
6194    `trace_alloc_trace_buffer'.  See its description of the atomic
6195    synching mechanism.  */
6196
6197 static void
6198 upload_fast_traceframes (void)
6199 {
6200   unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
6201   unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
6202   CORE_ADDR tf;
6203   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
6204   unsigned int curr_tbctrl_idx;
6205   unsigned int ipa_trace_buffer_ctrl_curr;
6206   unsigned int ipa_trace_buffer_ctrl_curr_old;
6207   CORE_ADDR ipa_trace_buffer_ctrl_addr;
6208   struct breakpoint *about_to_request_buffer_space_bkpt;
6209   CORE_ADDR ipa_trace_buffer_lo;
6210   CORE_ADDR ipa_trace_buffer_hi;
6211
6212   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6213                               &ipa_traceframe_read_count_racy))
6214     {
6215       /* This will happen in most targets if the current thread is
6216          running.  */
6217       return;
6218     }
6219
6220   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6221                               &ipa_traceframe_write_count_racy))
6222     return;
6223
6224   trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
6225                ipa_traceframe_write_count_racy - ipa_traceframe_read_count_racy,
6226                ipa_traceframe_write_count_racy, ipa_traceframe_read_count_racy);
6227
6228   if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
6229     return;
6230
6231   about_to_request_buffer_space_bkpt
6232     = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
6233                          NULL);
6234
6235   if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6236                               &ipa_trace_buffer_ctrl_curr))
6237     return;
6238
6239   ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
6240
6241   curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
6242
6243   {
6244     unsigned int prev, counter;
6245
6246     /* Update the token, with new counters, and the GDBserver stamp
6247        bit.  Alway reuse the current TBC index.  */
6248     prev = ipa_trace_buffer_ctrl_curr & 0x0007ff00;
6249     counter = (prev + 0x100) & 0x0007ff00;
6250
6251     ipa_trace_buffer_ctrl_curr = (0x80000000
6252                                   | (prev << 12)
6253                                   | counter
6254                                   | curr_tbctrl_idx);
6255   }
6256
6257   if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6258                                ipa_trace_buffer_ctrl_curr))
6259     return;
6260
6261   trace_debug ("Lib: Committed %08x -> %08x",
6262                ipa_trace_buffer_ctrl_curr_old,
6263                ipa_trace_buffer_ctrl_curr);
6264
6265   /* Re-read these, now that we've installed the
6266      `about_to_request_buffer_space' breakpoint/lock.  A thread could
6267      have finished a traceframe between the last read of these
6268      counters and setting the breakpoint above.  If we start
6269      uploading, we never want to leave this function with
6270      traceframe_read_count != 0, otherwise, GDBserver could end up
6271      incrementing the counter tokens more than once (due to event loop
6272      nesting), which would break the IP agent's "effective" detection
6273      (see trace_alloc_trace_buffer).  */
6274   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6275                               &ipa_traceframe_read_count))
6276     return;
6277   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6278                               &ipa_traceframe_write_count))
6279     return;
6280
6281   if (debug_threads)
6282     {
6283       trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
6284                    ipa_traceframe_write_count - ipa_traceframe_read_count,
6285                    ipa_traceframe_write_count, ipa_traceframe_read_count);
6286
6287       if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
6288           || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
6289         trace_debug ("note that ipa_traceframe_count's parts changed");
6290     }
6291
6292   /* Get the address of the current TBC object (the IP agent has an
6293      array of 3 such objects).  The index is stored in the TBC
6294      token.  */
6295   ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
6296   ipa_trace_buffer_ctrl_addr
6297     += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
6298
6299   if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
6300                             (unsigned char *) &ipa_trace_buffer_ctrl,
6301                             sizeof (struct ipa_trace_buffer_control)))
6302     return;
6303
6304   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
6305                                   &ipa_trace_buffer_lo))
6306     return;
6307   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
6308                                   &ipa_trace_buffer_hi))
6309     return;
6310
6311   /* Offsets are easier to grok for debugging than raw addresses,
6312      especially for the small trace buffer sizes that are useful for
6313      testing.  */
6314   trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6315                "endfree=%d wrap=%d hi=%d",
6316                curr_tbctrl_idx,
6317                (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6318                (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6319                (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6320                (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6321                (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6322
6323   /* Note that the IPA's buffer is always circular.  */
6324
6325 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6326
6327 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ)                \
6328   ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6329
6330 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ)                                  \
6331   (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ)                                    \
6332    - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6333       ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo)              \
6334       : 0))
6335
6336   tf = IPA_FIRST_TRACEFRAME ();
6337
6338   while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6339     {
6340       struct tracepoint *tpoint;
6341       struct traceframe *tframe;
6342       unsigned char *block;
6343       struct traceframe ipa_tframe;
6344
6345       if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6346                                 offsetof (struct traceframe, data)))
6347         error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6348
6349       if (ipa_tframe.tpnum == 0)
6350         fatal ("Uploading: No (more) fast traceframes, but "
6351                "ipa_traceframe_count == %u??\n",
6352                ipa_traceframe_write_count - ipa_traceframe_read_count);
6353
6354       /* Note that this will be incorrect for multi-location
6355          tracepoints...  */
6356       tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6357
6358       tframe = add_traceframe (tpoint);
6359       if (tframe == NULL)
6360         {
6361           trace_buffer_is_full = 1;
6362           trace_debug ("Uploading: trace buffer is full");
6363         }
6364       else
6365         {
6366           /* Copy the whole set of blocks in one go for now.  FIXME:
6367              split this in smaller blocks.  */
6368           block = add_traceframe_block (tframe, ipa_tframe.data_size);
6369           if (block != NULL)
6370             {
6371               if (read_inferior_memory (tf + offsetof (struct traceframe, data),
6372                                         block, ipa_tframe.data_size))
6373                 error ("Uploading: Couldn't read traceframe data at %s\n",
6374                        paddress (tf + offsetof (struct traceframe, data)));
6375             }
6376
6377           trace_debug ("Uploading: traceframe didn't fit");
6378           finish_traceframe (tframe);
6379         }
6380
6381       tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6382
6383       /* If we freed the traceframe that wrapped around, go back
6384          to the non-wrap case.  */
6385       if (tf < ipa_trace_buffer_ctrl.start)
6386         {
6387           trace_debug ("Lib: Discarding past the wraparound");
6388           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6389         }
6390       ipa_trace_buffer_ctrl.start = tf;
6391       ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6392       ++ipa_traceframe_read_count;
6393
6394       if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6395           && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6396         {
6397           trace_debug ("Lib: buffer is fully empty.  "
6398                        "Trace buffer [%d] start=%d free=%d endfree=%d",
6399                        curr_tbctrl_idx,
6400                        (int) (ipa_trace_buffer_ctrl.start
6401                               - ipa_trace_buffer_lo),
6402                        (int) (ipa_trace_buffer_ctrl.free
6403                               - ipa_trace_buffer_lo),
6404                        (int) (ipa_trace_buffer_ctrl.end_free
6405                               - ipa_trace_buffer_lo));
6406
6407           ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6408           ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6409           ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6410           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6411         }
6412
6413       trace_debug ("Uploaded a traceframe\n"
6414                    "Lib: Trace buffer [%d] start=%d free=%d "
6415                    "endfree=%d wrap=%d hi=%d",
6416                    curr_tbctrl_idx,
6417                    (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6418                    (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6419                    (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6420                    (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6421                    (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6422     }
6423
6424   if (write_inferior_memory (ipa_trace_buffer_ctrl_addr,
6425                              (unsigned char *) &ipa_trace_buffer_ctrl,
6426                              sizeof (struct ipa_trace_buffer_control)))
6427     return;
6428
6429   write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6430                           ipa_traceframe_read_count);
6431
6432   trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6433
6434   pause_all (1);
6435   cancel_breakpoints ();
6436
6437   delete_breakpoint (about_to_request_buffer_space_bkpt);
6438   about_to_request_buffer_space_bkpt = NULL;
6439
6440   unpause_all (1);
6441
6442   if (trace_buffer_is_full)
6443     stop_tracing ();
6444 }
6445 #endif
6446
6447 #ifdef IN_PROCESS_AGENT
6448
6449 IP_AGENT_EXPORT int ust_loaded;
6450 IP_AGENT_EXPORT char cmd_buf[CMD_BUF_SIZE];
6451
6452 #ifdef HAVE_UST
6453
6454 /* Static tracepoints.  */
6455
6456 /* UST puts a "struct tracepoint" in the global namespace, which
6457    conflicts with our tracepoint.  Arguably, being a library, it
6458    shouldn't take ownership of such a generic name.  We work around it
6459    here.  */
6460 #define tracepoint ust_tracepoint
6461 #include <ust/ust.h>
6462 #undef tracepoint
6463
6464 extern int serialize_to_text (char *outbuf, int bufsize,
6465                               const char *fmt, va_list ap);
6466
6467 #define GDB_PROBE_NAME "gdb"
6468
6469 /* We dynamically search for the UST symbols instead of linking them
6470    in.  This lets the user decide if the application uses static
6471    tracepoints, instead of always pulling libust.so in.  This vector
6472    holds pointers to all functions we care about.  */
6473
6474 static struct
6475 {
6476   int (*serialize_to_text) (char *outbuf, int bufsize,
6477                             const char *fmt, va_list ap);
6478
6479   int (*ltt_probe_register) (struct ltt_available_probe *pdata);
6480   int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
6481
6482   int (*ltt_marker_connect) (const char *channel, const char *mname,
6483                              const char *pname);
6484   int (*ltt_marker_disconnect) (const char *channel, const char *mname,
6485                                 const char *pname);
6486
6487   void (*marker_iter_start) (struct marker_iter *iter);
6488   void (*marker_iter_next) (struct marker_iter *iter);
6489   void (*marker_iter_stop) (struct marker_iter *iter);
6490   void (*marker_iter_reset) (struct marker_iter *iter);
6491 } ust_ops;
6492
6493 #include <dlfcn.h>
6494
6495 /* Cast through typeof to catch incompatible API changes.  Since UST
6496    only builds with gcc, we can freely use gcc extensions here
6497    too.  */
6498 #define GET_UST_SYM(SYM)                                        \
6499   do                                                            \
6500     {                                                           \
6501       if (ust_ops.SYM == NULL)                                  \
6502         ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM);       \
6503       if (ust_ops.SYM == NULL)                                  \
6504         return 0;                                               \
6505     } while (0)
6506
6507 #define USTF(SYM) ust_ops.SYM
6508
6509 /* Get pointers to all libust.so functions we care about.  */
6510
6511 static int
6512 dlsym_ust (void)
6513 {
6514   GET_UST_SYM (serialize_to_text);
6515
6516   GET_UST_SYM (ltt_probe_register);
6517   GET_UST_SYM (ltt_probe_unregister);
6518   GET_UST_SYM (ltt_marker_connect);
6519   GET_UST_SYM (ltt_marker_disconnect);
6520
6521   GET_UST_SYM (marker_iter_start);
6522   GET_UST_SYM (marker_iter_next);
6523   GET_UST_SYM (marker_iter_stop);
6524   GET_UST_SYM (marker_iter_reset);
6525
6526   ust_loaded = 1;
6527   return 1;
6528 }
6529
6530 /* Given an UST marker, return the matching gdb static tracepoint.
6531    The match is done by address.  */
6532
6533 static struct tracepoint *
6534 ust_marker_to_static_tracepoint (const struct marker *mdata)
6535 {
6536   struct tracepoint *tpoint;
6537
6538   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
6539     {
6540       if (!tpoint->enabled || tpoint->type != static_tracepoint)
6541         continue;
6542
6543       if (tpoint->address == (uintptr_t) mdata->location)
6544         return tpoint;
6545     }
6546
6547   return NULL;
6548 }
6549
6550 /* The probe function we install on lttng/ust markers.  Whenever a
6551    probed ust marker is hit, this function is called.  This is similar
6552    to gdb_collect, only for static tracepoints, instead of fast
6553    tracepoints.  */
6554
6555 static void
6556 gdb_probe (const struct marker *mdata, void *probe_private,
6557            struct registers *regs, void *call_private,
6558            const char *fmt, va_list *args)
6559 {
6560   struct tracepoint *tpoint;
6561   struct static_tracepoint_ctx ctx;
6562
6563   /* Don't do anything until the trace run is completely set up.  */
6564   if (!tracing)
6565     {
6566       trace_debug ("gdb_probe: not tracing\n");
6567       return;
6568     }
6569
6570   ctx.base.type = static_tracepoint;
6571   ctx.regcache_initted = 0;
6572   ctx.regs = regs;
6573   ctx.fmt = fmt;
6574   ctx.args = args;
6575
6576   /* Wrap the regblock in a register cache (in the stack, we don't
6577      want to malloc here).  */
6578   ctx.regspace = alloca (register_cache_size ());
6579   if (ctx.regspace == NULL)
6580     {
6581       trace_debug ("Trace buffer block allocation failed, skipping");
6582       return;
6583     }
6584
6585   tpoint = ust_marker_to_static_tracepoint (mdata);
6586   if (tpoint == NULL)
6587     {
6588       trace_debug ("gdb_probe: marker not known: "
6589                    "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6590                    mdata->location, mdata->channel,
6591                    mdata->name, mdata->format);
6592       return;
6593     }
6594
6595   ctx.tpoint = tpoint;
6596
6597   trace_debug ("gdb_probe: collecting marker: "
6598                "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6599                mdata->location, mdata->channel,
6600                mdata->name, mdata->format);
6601
6602   /* Test the condition if present, and collect if true.  */
6603   if (tpoint->cond == NULL
6604       || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6605                                        tpoint))
6606     {
6607       collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6608                                   tpoint->address, tpoint);
6609
6610       if (stopping_tracepoint
6611           || trace_buffer_is_full
6612           || expr_eval_result != expr_eval_no_error)
6613         stop_tracing ();
6614     }
6615   else
6616     {
6617       /* If there was a condition and it evaluated to false, the only
6618          way we would stop tracing is if there was an error during
6619          condition expression evaluation.  */
6620       if (expr_eval_result != expr_eval_no_error)
6621         stop_tracing ();
6622     }
6623 }
6624
6625 /* Called if the gdb static tracepoint requested collecting "$_sdata",
6626    static tracepoint string data.  This is a string passed to the
6627    tracing library by the user, at the time of the tracepoint marker
6628    call.  E.g., in the UST marker call:
6629
6630      trace_mark (ust, bar33, "str %s", "FOOBAZ");
6631
6632    the collected data is "str FOOBAZ".
6633 */
6634
6635 static void
6636 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
6637                                 CORE_ADDR stop_pc,
6638                                 struct tracepoint *tpoint,
6639                                 struct traceframe *tframe)
6640 {
6641   struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
6642   unsigned char *bufspace;
6643   int size;
6644   va_list copy;
6645   unsigned short blocklen;
6646
6647   if (umd == NULL)
6648     {
6649       trace_debug ("Wanted to collect static trace data, "
6650                    "but there's no static trace data");
6651       return;
6652     }
6653
6654   va_copy (copy, *umd->args);
6655   size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
6656   va_end (copy);
6657
6658   trace_debug ("Want to collect ust data");
6659
6660   /* 'S' + size + string */
6661   bufspace = add_traceframe_block (tframe,
6662                                    1 + sizeof (blocklen) + size + 1);
6663   if (bufspace == NULL)
6664     {
6665       trace_debug ("Trace buffer block allocation failed, skipping");
6666       return;
6667     }
6668
6669   /* Identify a static trace data block.  */
6670   *bufspace = 'S';
6671
6672   blocklen = size + 1;
6673   memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
6674
6675   va_copy (copy, *umd->args);
6676   USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
6677                            size + 1, umd->fmt, copy);
6678   va_end (copy);
6679
6680   trace_debug ("Storing static tracepoint data in regblock: %s",
6681                bufspace + 1 + sizeof (blocklen));
6682 }
6683
6684 /* The probe to register with lttng/ust.  */
6685 static struct ltt_available_probe gdb_ust_probe =
6686   {
6687     GDB_PROBE_NAME,
6688     NULL,
6689     gdb_probe,
6690   };
6691
6692 #endif /* HAVE_UST */
6693 #endif /* IN_PROCESS_AGENT */
6694
6695 #ifdef HAVE_UST
6696
6697 #include <sys/socket.h>
6698 #include <sys/un.h>
6699
6700 #ifndef UNIX_PATH_MAX
6701 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6702 #endif
6703
6704 /* Where we put the socked used for synchronization.  */
6705 #define SOCK_DIR P_tmpdir
6706
6707 #endif /* HAVE_UST */
6708
6709 #ifndef IN_PROCESS_AGENT
6710
6711 #ifdef HAVE_UST
6712
6713 static int
6714 gdb_ust_connect_sync_socket (int pid)
6715 {
6716   struct sockaddr_un addr;
6717   int res, fd;
6718   char path[UNIX_PATH_MAX];
6719
6720   res = xsnprintf (path, UNIX_PATH_MAX, "%s/gdb_ust%d", SOCK_DIR, pid);
6721   if (res >= UNIX_PATH_MAX)
6722     {
6723       trace_debug ("string overflow allocating socket name");
6724       return -1;
6725     }
6726
6727   res = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6728   if (res == -1)
6729     {
6730       warning ("error opening sync socket: %s\n", strerror (errno));
6731       return -1;
6732     }
6733
6734   addr.sun_family = AF_UNIX;
6735
6736   res = xsnprintf (addr.sun_path, UNIX_PATH_MAX, "%s", path);
6737   if (res >= UNIX_PATH_MAX)
6738     {
6739       warning ("string overflow allocating socket name\n");
6740       close (fd);
6741       return -1;
6742     }
6743
6744   res = connect (fd, (struct sockaddr *) &addr, sizeof (addr));
6745   if (res == -1)
6746     {
6747       warning ("error connecting sync socket (%s): %s. "
6748                "Make sure the directory exists and that it is writable.",
6749                path, strerror (errno));
6750       close (fd);
6751       return -1;
6752     }
6753
6754   return fd;
6755 }
6756
6757 /* Resume thread PTID.  */
6758
6759 static void
6760 resume_thread (ptid_t ptid)
6761 {
6762   struct thread_resume resume_info;
6763
6764   resume_info.thread = ptid;
6765   resume_info.kind = resume_continue;
6766   resume_info.sig = TARGET_SIGNAL_0;
6767   (*the_target->resume) (&resume_info, 1);
6768 }
6769
6770 /* Stop thread PTID.  */
6771
6772 static void
6773 stop_thread (ptid_t ptid)
6774 {
6775   struct thread_resume resume_info;
6776
6777   resume_info.thread = ptid;
6778   resume_info.kind = resume_stop;
6779   resume_info.sig = TARGET_SIGNAL_0;
6780   (*the_target->resume) (&resume_info, 1);
6781 }
6782
6783 /* Ask the in-process agent to run a command.  Since we don't want to
6784    have to handle the IPA hitting breakpoints while running the
6785    command, we pause all threads, remove all breakpoints, and then set
6786    the helper thread re-running.  We communicate with the helper
6787    thread by means of direct memory xfering, and a socket for
6788    synchronization.  */
6789
6790 static int
6791 run_inferior_command (char *cmd)
6792 {
6793   int err = -1;
6794   int fd = -1;
6795   int pid = ptid_get_pid (current_inferior->entry.id);
6796   int tid;
6797   ptid_t ptid = null_ptid;
6798
6799   trace_debug ("run_inferior_command: running: %s", cmd);
6800
6801   pause_all (0);
6802   uninsert_all_breakpoints ();
6803
6804   if (read_inferior_integer (ipa_sym_addrs.addr_helper_thread_id, &tid))
6805     {
6806       warning ("Error reading helper thread's id in lib");
6807       goto out;
6808     }
6809
6810   if (tid == 0)
6811     {
6812       warning ("helper thread not initialized yet");
6813       goto out;
6814     }
6815
6816   if (write_inferior_memory (ipa_sym_addrs.addr_cmd_buf,
6817                              (unsigned char *) cmd, strlen (cmd) + 1))
6818     {
6819       warning ("Error writing command");
6820       goto out;
6821     }
6822
6823   ptid = ptid_build (pid, tid, 0);
6824
6825   resume_thread (ptid);
6826
6827   fd = gdb_ust_connect_sync_socket (pid);
6828   if (fd >= 0)
6829     {
6830       char buf[1] = "";
6831       int ret;
6832
6833       trace_debug ("signalling helper thread");
6834
6835       do
6836         {
6837           ret = write (fd, buf, 1);
6838         } while (ret == -1 && errno == EINTR);
6839
6840       trace_debug ("waiting for helper thread's response");
6841
6842       do
6843         {
6844           ret = read (fd, buf, 1);
6845         } while (ret == -1 && errno == EINTR);
6846
6847       close (fd);
6848
6849       trace_debug ("helper thread's response received");
6850     }
6851
6852  out:
6853
6854   /* Need to read response with the inferior stopped.  */
6855   if (!ptid_equal (ptid, null_ptid))
6856     {
6857       int was_non_stop = non_stop;
6858       struct target_waitstatus status;
6859
6860       stop_thread (ptid);
6861       non_stop = 1;
6862       mywait (ptid, &status, 0, 0);
6863       non_stop = was_non_stop;
6864     }
6865
6866   if (fd >= 0)
6867     {
6868       if (read_inferior_memory (ipa_sym_addrs.addr_cmd_buf,
6869                                 (unsigned char *) cmd, CMD_BUF_SIZE))
6870         {
6871           warning ("Error reading command response");
6872         }
6873       else
6874         {
6875           err = 0;
6876           trace_debug ("run_inferior_command: response: %s", cmd);
6877         }
6878     }
6879
6880   reinsert_all_breakpoints ();
6881   unpause_all (0);
6882
6883   return err;
6884 }
6885
6886 #else /* HAVE_UST */
6887
6888 static int
6889 run_inferior_command (char *cmd)
6890 {
6891   return -1;
6892 }
6893
6894 #endif /* HAVE_UST */
6895
6896 #else /* !IN_PROCESS_AGENT */
6897
6898 /* Thread ID of the helper thread.  GDBserver reads this to know which
6899    is the help thread.  This is an LWP id on Linux.  */
6900 int helper_thread_id;
6901
6902 #ifdef HAVE_UST
6903
6904 static int
6905 init_named_socket (const char *name)
6906 {
6907   int result, fd;
6908   struct sockaddr_un addr;
6909
6910   result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6911   if (result == -1)
6912     {
6913       warning ("socket creation failed: %s", strerror (errno));
6914       return -1;
6915     }
6916
6917   addr.sun_family = AF_UNIX;
6918
6919   strncpy (addr.sun_path, name, UNIX_PATH_MAX);
6920   addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
6921
6922   result = access (name, F_OK);
6923   if (result == 0)
6924     {
6925       /* File exists.  */
6926       result = unlink (name);
6927       if (result == -1)
6928         {
6929           warning ("unlink failed: %s", strerror (errno));
6930           close (fd);
6931           return -1;
6932         }
6933       warning ("socket %s already exists; overwriting", name);
6934     }
6935
6936   result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6937   if (result == -1)
6938     {
6939       warning ("bind failed: %s", strerror (errno));
6940       close (fd);
6941       return -1;
6942     }
6943
6944   result = listen (fd, 1);
6945   if (result == -1)
6946     {
6947       warning ("listen: %s", strerror (errno));
6948       close (fd);
6949       return -1;
6950     }
6951
6952   return fd;
6953 }
6954
6955 static int
6956 gdb_ust_socket_init (void)
6957 {
6958   int result, fd;
6959   char name[UNIX_PATH_MAX];
6960
6961   result = xsnprintf (name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6962                       SOCK_DIR, getpid ());
6963   if (result >= UNIX_PATH_MAX)
6964     {
6965       trace_debug ("string overflow allocating socket name");
6966       return -1;
6967     }
6968
6969   fd = init_named_socket (name);
6970   if (fd < 0)
6971     warning ("Error initializing named socket (%s) for communication with the "
6972              "ust helper thread. Check that directory exists and that it "
6973              "is writable.", name);
6974
6975   return fd;
6976 }
6977
6978 /* Return an hexstr version of the STR C string, fit for sending to
6979    GDB.  */
6980
6981 static char *
6982 cstr_to_hexstr (const char *str)
6983 {
6984   int len = strlen (str);
6985   char *hexstr = xmalloc (len * 2 + 1);
6986   convert_int_to_ascii ((gdb_byte *) str, hexstr, len);
6987   return hexstr;
6988 }
6989
6990 /* The next marker to be returned on a qTsSTM command.  */
6991 static const struct marker *next_st;
6992
6993 /* Returns the first known marker.  */
6994
6995 struct marker *
6996 first_marker (void)
6997 {
6998   struct marker_iter iter;
6999
7000   USTF(marker_iter_reset) (&iter);
7001   USTF(marker_iter_start) (&iter);
7002
7003   return iter.marker;
7004 }
7005
7006 /* Returns the marker following M.  */
7007
7008 const struct marker *
7009 next_marker (const struct marker *m)
7010 {
7011   struct marker_iter iter;
7012
7013   USTF(marker_iter_reset) (&iter);
7014   USTF(marker_iter_start) (&iter);
7015
7016   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7017     {
7018       if (iter.marker == m)
7019         {
7020           USTF(marker_iter_next) (&iter);
7021           return iter.marker;
7022         }
7023     }
7024
7025   return NULL;
7026 }
7027
7028 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
7029    packets.  */
7030
7031 static void
7032 response_ust_marker (char *packet, const struct marker *st)
7033 {
7034   char *strid, *format, *tmp;
7035
7036   next_st = next_marker (st);
7037
7038   tmp = xmalloc (strlen (st->channel) + 1 +
7039                  strlen (st->name) + 1);
7040   sprintf (tmp, "%s/%s", st->channel, st->name);
7041
7042   strid = cstr_to_hexstr (tmp);
7043   free (tmp);
7044
7045   format = cstr_to_hexstr (st->format);
7046
7047   sprintf (packet, "m%s:%s:%s",
7048            paddress ((uintptr_t) st->location),
7049            strid,
7050            format);
7051
7052   free (strid);
7053   free (format);
7054 }
7055
7056 /* Return the first static tracepoint, and initialize the state
7057    machine that will iterate through all the static tracepoints.  */
7058
7059 static void
7060 cmd_qtfstm (char *packet)
7061 {
7062   trace_debug ("Returning first trace state variable definition");
7063
7064   if (first_marker ())
7065     response_ust_marker (packet, first_marker ());
7066   else
7067     strcpy (packet, "l");
7068 }
7069
7070 /* Return additional trace state variable definitions. */
7071
7072 static void
7073 cmd_qtsstm (char *packet)
7074 {
7075   trace_debug ("Returning static tracepoint");
7076
7077   if (next_st)
7078     response_ust_marker (packet, next_st);
7079   else
7080     strcpy (packet, "l");
7081 }
7082
7083 /* Disconnect the GDB probe from a marker at a given address.  */
7084
7085 static void
7086 unprobe_marker_at (char *packet)
7087 {
7088   char *p = packet;
7089   ULONGEST address;
7090   struct marker_iter iter;
7091
7092   p += sizeof ("unprobe_marker_at:") - 1;
7093
7094   p = unpack_varlen_hex (p, &address);
7095
7096   USTF(marker_iter_reset) (&iter);
7097   USTF(marker_iter_start) (&iter);
7098   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7099     if ((uintptr_t ) iter.marker->location == address)
7100       {
7101         int result;
7102
7103         result = USTF(ltt_marker_disconnect) (iter.marker->channel,
7104                                               iter.marker->name,
7105                                               GDB_PROBE_NAME);
7106         if (result < 0)
7107           warning ("could not disable marker %s/%s",
7108                    iter.marker->channel, iter.marker->name);
7109         break;
7110       }
7111 }
7112
7113 /* Connect the GDB probe to a marker at a given address.  */
7114
7115 static int
7116 probe_marker_at (char *packet)
7117 {
7118   char *p = packet;
7119   ULONGEST address;
7120   struct marker_iter iter;
7121   struct marker *m;
7122
7123   p += sizeof ("probe_marker_at:") - 1;
7124
7125   p = unpack_varlen_hex (p, &address);
7126
7127   USTF(marker_iter_reset) (&iter);
7128
7129   for (USTF(marker_iter_start) (&iter), m = iter.marker;
7130        m != NULL;
7131        USTF(marker_iter_next) (&iter), m = iter.marker)
7132     if ((uintptr_t ) m->location == address)
7133       {
7134         int result;
7135
7136         trace_debug ("found marker for address.  "
7137                      "ltt_marker_connect (marker = %s/%s)",
7138                      m->channel, m->name);
7139
7140         result = USTF(ltt_marker_connect) (m->channel, m->name, GDB_PROBE_NAME);
7141         if (result && result != -EEXIST)
7142           trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
7143                        m->channel, m->name, -result);
7144
7145         if (result < 0)
7146           {
7147             sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
7148                      m->channel, m->name);
7149             return -1;
7150           }
7151
7152         strcpy (packet, "OK");
7153         return 0;
7154       }
7155
7156   sprintf (packet, "E.no marker found at 0x%s", paddress (address));
7157   return -1;
7158 }
7159
7160 static int
7161 cmd_qtstmat (char *packet)
7162 {
7163   char *p = packet;
7164   ULONGEST address;
7165   struct marker_iter iter;
7166   struct marker *m;
7167
7168   p += sizeof ("qTSTMat:") - 1;
7169
7170   p = unpack_varlen_hex (p, &address);
7171
7172   USTF(marker_iter_reset) (&iter);
7173
7174   for (USTF(marker_iter_start) (&iter), m = iter.marker;
7175        m != NULL;
7176        USTF(marker_iter_next) (&iter), m = iter.marker)
7177     if ((uintptr_t ) m->location == address)
7178       {
7179         response_ust_marker (packet, m);
7180         return 0;
7181       }
7182
7183   strcpy (packet, "l");
7184   return -1;
7185 }
7186
7187 static void *
7188 gdb_ust_thread (void *arg)
7189 {
7190   int listen_fd;
7191
7192   while (1)
7193     {
7194       listen_fd = gdb_ust_socket_init ();
7195
7196 #ifdef SYS_gettid
7197       if (helper_thread_id == 0)
7198         helper_thread_id = syscall (SYS_gettid);
7199 #endif
7200
7201       if (listen_fd == -1)
7202         {
7203           warning ("could not create sync socket\n");
7204           break;
7205         }
7206
7207       while (1)
7208         {
7209           socklen_t tmp;
7210           struct sockaddr_un sockaddr;
7211           int fd;
7212           char buf[1];
7213           int ret;
7214
7215           tmp = sizeof (sockaddr);
7216
7217           do
7218             {
7219               fd = accept (listen_fd, &sockaddr, &tmp);
7220             }
7221           /* It seems an ERESTARTSYS can escape out of accept.  */
7222           while (fd == -512 || (fd == -1 && errno == EINTR));
7223
7224           if (fd < 0)
7225             {
7226               warning ("Accept returned %d, error: %s\n",
7227                        fd, strerror (errno));
7228               break;
7229             }
7230
7231           do
7232             {
7233               ret = read (fd, buf, 1);
7234             } while (ret == -1 && errno == EINTR);
7235
7236           if (ret == -1)
7237             {
7238               warning ("reading socket (fd=%d) failed with %s",
7239                        fd, strerror (errno));
7240               close (fd);
7241               break;
7242             }
7243
7244           if (cmd_buf[0])
7245             {
7246               if (strcmp ("qTfSTM", cmd_buf) == 0)
7247                 {
7248                   cmd_qtfstm (cmd_buf);
7249                 }
7250               else if (strcmp ("qTsSTM", cmd_buf) == 0)
7251                 {
7252                   cmd_qtsstm (cmd_buf);
7253                 }
7254               else if (strncmp ("unprobe_marker_at:",
7255                                 cmd_buf,
7256                                 sizeof ("unprobe_marker_at:") - 1) == 0)
7257                 {
7258                   unprobe_marker_at (cmd_buf);
7259                 }
7260               else if (strncmp ("probe_marker_at:",
7261                                 cmd_buf,
7262                                 sizeof ("probe_marker_at:") - 1) == 0)
7263                 {
7264                   probe_marker_at (cmd_buf);
7265                 }
7266               else if (strncmp ("qTSTMat:",
7267                                 cmd_buf,
7268                                 sizeof ("qTSTMat:") - 1) == 0)
7269                 {
7270                   cmd_qtstmat (cmd_buf);
7271                 }
7272               else if (strcmp (cmd_buf, "help") == 0)
7273                 {
7274                   strcpy (cmd_buf, "for help, press F1\n");
7275                 }
7276               else
7277                 strcpy (cmd_buf, "");
7278             }
7279
7280           write (fd, buf, 1);
7281           close (fd);
7282         }
7283     }
7284
7285   return NULL;
7286 }
7287
7288 #include <signal.h>
7289
7290 static void
7291 gdb_ust_init (void)
7292 {
7293   int res;
7294   pthread_t thread;
7295   sigset_t new_mask;
7296   sigset_t orig_mask;
7297
7298   if (!dlsym_ust ())
7299     return;
7300
7301   /* We want the helper thread to be as transparent as possible, so
7302      have it inherit an all-signals-blocked mask.  */
7303
7304   sigfillset (&new_mask);
7305   res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
7306   if (res)
7307     fatal ("pthread_sigmask (1) failed: %s", strerror (res));
7308
7309   res = pthread_create (&thread,
7310                         NULL,
7311                         gdb_ust_thread,
7312                         NULL);
7313
7314   res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
7315   if (res)
7316     fatal ("pthread_sigmask (2) failed: %s", strerror (res));
7317
7318   while (helper_thread_id == 0)
7319     usleep (1);
7320
7321   USTF(ltt_probe_register) (&gdb_ust_probe);
7322 }
7323
7324 #endif /* HAVE_UST */
7325
7326 #include <sys/mman.h>
7327 #include <fcntl.h>
7328
7329 IP_AGENT_EXPORT char *gdb_tp_heap_buffer;
7330 IP_AGENT_EXPORT char *gdb_jump_pad_buffer;
7331 IP_AGENT_EXPORT char *gdb_jump_pad_buffer_end;
7332
7333 static void __attribute__ ((constructor))
7334 initialize_tracepoint_ftlib (void)
7335 {
7336   initialize_tracepoint ();
7337
7338 #ifdef HAVE_UST
7339   gdb_ust_init ();
7340 #endif
7341 }
7342
7343 #endif /* IN_PROCESS_AGENT */
7344
7345 static LONGEST
7346 tsv_get_timestamp (void)
7347 {
7348    struct timeval tv;
7349
7350    if (gettimeofday (&tv, 0) != 0)
7351      return -1;
7352    else
7353      return (LONGEST) tv.tv_sec * 1000000 + tv.tv_usec;
7354 }
7355
7356 void
7357 initialize_tracepoint (void)
7358 {
7359   /* There currently no way to change the buffer size.  */
7360   const int sizeOfBuffer = 5 * 1024 * 1024;
7361   unsigned char *buf = xmalloc (sizeOfBuffer);
7362   init_trace_buffer (buf, sizeOfBuffer);
7363
7364   /* Wire trace state variable 1 to be the timestamp.  This will be
7365      uploaded to GDB upon connection and become one of its trace state
7366      variables.  (In case you're wondering, if GDB already has a trace
7367      variable numbered 1, it will be renumbered.)  */
7368   create_trace_state_variable (1, 0);
7369   set_trace_state_variable_name (1, "trace_timestamp");
7370   set_trace_state_variable_getter (1, tsv_get_timestamp);
7371
7372 #ifdef IN_PROCESS_AGENT
7373   {
7374     int pagesize;
7375     pagesize = sysconf (_SC_PAGE_SIZE);
7376     if (pagesize == -1)
7377       fatal ("sysconf");
7378
7379     gdb_tp_heap_buffer = xmalloc (5 * 1024 * 1024);
7380
7381     /* Allocate scratch buffer aligned on a page boundary.  */
7382     gdb_jump_pad_buffer = memalign (pagesize, pagesize * 20);
7383     gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + pagesize * 20;
7384
7385     /* Make it writable and executable.  */
7386     if (mprotect (gdb_jump_pad_buffer, pagesize * 20,
7387                   PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
7388       fatal ("\
7389 initialize_tracepoint: mprotect(%p, %d, PROT_READ|PROT_EXEC) failed with %s",
7390              gdb_jump_pad_buffer, pagesize * 20, strerror (errno));
7391   }
7392
7393   initialize_low_tracepoint ();
7394 #endif
7395 }