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