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