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