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