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