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