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