Fix snafu in previous delta for elf32-csky.c
[binutils-gdb.git] / gdbserver / tracepoint.cc
blob37a9a8c5b7c49df0dd2ef58c30d1a0a6dbdf0cdd
1 /* Tracepoint code for remote server for GDB.
2 Copyright (C) 2009-2023 Free Software Foundation, Inc.
4 This file is part of GDB.
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.
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.
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/>. */
19 #include "server.h"
20 #include "tracepoint.h"
21 #include "gdbthread.h"
22 #include "gdbsupport/rsp-low.h"
24 #include <ctype.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <chrono>
28 #include <inttypes.h>
29 #include "ax.h"
30 #include "tdesc.h"
32 #define IPA_SYM_STRUCT_NAME ipa_sym_addresses
33 #include "gdbsupport/agent.h"
35 #define DEFAULT_TRACE_BUFFER_SIZE 5242880 /* 5*1024*1024 */
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).
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.
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.
64 #ifdef IN_PROCESS_AGENT
66 static void trace_vdebug (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
68 static void
69 trace_vdebug (const char *fmt, ...)
71 char buf[1024];
72 va_list ap;
74 va_start (ap, fmt);
75 vsprintf (buf, fmt, ap);
76 fprintf (stderr, PROG "/tracepoint: %s\n", buf);
77 va_end (ap);
80 #define trace_debug(fmt, args...) \
81 do { \
82 if (debug_threads) \
83 trace_vdebug ((fmt), ##args); \
84 } while (0)
86 #else
88 #define trace_debug(fmt, args...) \
89 do { \
90 threads_debug_printf ((fmt), ##args); \
91 } while (0)
93 #endif
95 /* Prefix exported symbols, for good citizenship. All the symbols
96 that need exporting are defined in this module. Note that all
97 these symbols must be tagged with IP_AGENT_EXPORT_*. */
98 #ifdef IN_PROCESS_AGENT
99 # define gdb_tp_heap_buffer IPA_SYM_EXPORTED_NAME (gdb_tp_heap_buffer)
100 # define gdb_jump_pad_buffer IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer)
101 # define gdb_jump_pad_buffer_end IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer_end)
102 # define gdb_trampoline_buffer IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer)
103 # define gdb_trampoline_buffer_end IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_end)
104 # define gdb_trampoline_buffer_error IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_error)
105 # define collecting IPA_SYM_EXPORTED_NAME (collecting)
106 # define gdb_collect_ptr IPA_SYM_EXPORTED_NAME (gdb_collect_ptr)
107 # define stop_tracing IPA_SYM_EXPORTED_NAME (stop_tracing)
108 # define flush_trace_buffer IPA_SYM_EXPORTED_NAME (flush_trace_buffer)
109 # define about_to_request_buffer_space IPA_SYM_EXPORTED_NAME (about_to_request_buffer_space)
110 # define trace_buffer_is_full IPA_SYM_EXPORTED_NAME (trace_buffer_is_full)
111 # define stopping_tracepoint IPA_SYM_EXPORTED_NAME (stopping_tracepoint)
112 # define expr_eval_result IPA_SYM_EXPORTED_NAME (expr_eval_result)
113 # define error_tracepoint IPA_SYM_EXPORTED_NAME (error_tracepoint)
114 # define tracepoints IPA_SYM_EXPORTED_NAME (tracepoints)
115 # define tracing IPA_SYM_EXPORTED_NAME (tracing)
116 # define trace_buffer_ctrl IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl)
117 # define trace_buffer_ctrl_curr IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl_curr)
118 # define trace_buffer_lo IPA_SYM_EXPORTED_NAME (trace_buffer_lo)
119 # define trace_buffer_hi IPA_SYM_EXPORTED_NAME (trace_buffer_hi)
120 # define traceframe_read_count IPA_SYM_EXPORTED_NAME (traceframe_read_count)
121 # define traceframe_write_count IPA_SYM_EXPORTED_NAME (traceframe_write_count)
122 # define traceframes_created IPA_SYM_EXPORTED_NAME (traceframes_created)
123 # define trace_state_variables IPA_SYM_EXPORTED_NAME (trace_state_variables)
124 # define get_raw_reg_ptr IPA_SYM_EXPORTED_NAME (get_raw_reg_ptr)
125 # define get_trace_state_variable_value_ptr \
126 IPA_SYM_EXPORTED_NAME (get_trace_state_variable_value_ptr)
127 # define set_trace_state_variable_value_ptr \
128 IPA_SYM_EXPORTED_NAME (set_trace_state_variable_value_ptr)
129 # define ust_loaded IPA_SYM_EXPORTED_NAME (ust_loaded)
130 # define helper_thread_id IPA_SYM_EXPORTED_NAME (helper_thread_id)
131 # define cmd_buf IPA_SYM_EXPORTED_NAME (cmd_buf)
132 # define ipa_tdesc_idx IPA_SYM_EXPORTED_NAME (ipa_tdesc_idx)
133 #endif
135 #ifndef IN_PROCESS_AGENT
137 /* Addresses of in-process agent's symbols GDBserver cares about. */
139 struct ipa_sym_addresses
141 CORE_ADDR addr_gdb_tp_heap_buffer;
142 CORE_ADDR addr_gdb_jump_pad_buffer;
143 CORE_ADDR addr_gdb_jump_pad_buffer_end;
144 CORE_ADDR addr_gdb_trampoline_buffer;
145 CORE_ADDR addr_gdb_trampoline_buffer_end;
146 CORE_ADDR addr_gdb_trampoline_buffer_error;
147 CORE_ADDR addr_collecting;
148 CORE_ADDR addr_gdb_collect_ptr;
149 CORE_ADDR addr_stop_tracing;
150 CORE_ADDR addr_flush_trace_buffer;
151 CORE_ADDR addr_about_to_request_buffer_space;
152 CORE_ADDR addr_trace_buffer_is_full;
153 CORE_ADDR addr_stopping_tracepoint;
154 CORE_ADDR addr_expr_eval_result;
155 CORE_ADDR addr_error_tracepoint;
156 CORE_ADDR addr_tracepoints;
157 CORE_ADDR addr_tracing;
158 CORE_ADDR addr_trace_buffer_ctrl;
159 CORE_ADDR addr_trace_buffer_ctrl_curr;
160 CORE_ADDR addr_trace_buffer_lo;
161 CORE_ADDR addr_trace_buffer_hi;
162 CORE_ADDR addr_traceframe_read_count;
163 CORE_ADDR addr_traceframe_write_count;
164 CORE_ADDR addr_traceframes_created;
165 CORE_ADDR addr_trace_state_variables;
166 CORE_ADDR addr_get_raw_reg_ptr;
167 CORE_ADDR addr_get_trace_state_variable_value_ptr;
168 CORE_ADDR addr_set_trace_state_variable_value_ptr;
169 CORE_ADDR addr_ust_loaded;
170 CORE_ADDR addr_ipa_tdesc_idx;
173 static struct
175 const char *name;
176 int offset;
177 } symbol_list[] = {
178 IPA_SYM(gdb_tp_heap_buffer),
179 IPA_SYM(gdb_jump_pad_buffer),
180 IPA_SYM(gdb_jump_pad_buffer_end),
181 IPA_SYM(gdb_trampoline_buffer),
182 IPA_SYM(gdb_trampoline_buffer_end),
183 IPA_SYM(gdb_trampoline_buffer_error),
184 IPA_SYM(collecting),
185 IPA_SYM(gdb_collect_ptr),
186 IPA_SYM(stop_tracing),
187 IPA_SYM(flush_trace_buffer),
188 IPA_SYM(about_to_request_buffer_space),
189 IPA_SYM(trace_buffer_is_full),
190 IPA_SYM(stopping_tracepoint),
191 IPA_SYM(expr_eval_result),
192 IPA_SYM(error_tracepoint),
193 IPA_SYM(tracepoints),
194 IPA_SYM(tracing),
195 IPA_SYM(trace_buffer_ctrl),
196 IPA_SYM(trace_buffer_ctrl_curr),
197 IPA_SYM(trace_buffer_lo),
198 IPA_SYM(trace_buffer_hi),
199 IPA_SYM(traceframe_read_count),
200 IPA_SYM(traceframe_write_count),
201 IPA_SYM(traceframes_created),
202 IPA_SYM(trace_state_variables),
203 IPA_SYM(get_raw_reg_ptr),
204 IPA_SYM(get_trace_state_variable_value_ptr),
205 IPA_SYM(set_trace_state_variable_value_ptr),
206 IPA_SYM(ust_loaded),
207 IPA_SYM(ipa_tdesc_idx),
210 static struct ipa_sym_addresses ipa_sym_addrs;
212 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
214 /* Returns true if both the in-process agent library and the static
215 tracepoints libraries are loaded in the inferior, and agent has
216 capability on static tracepoints. */
218 static int
219 in_process_agent_supports_ust (void)
221 int loaded = 0;
223 if (!agent_loaded_p ())
225 warning ("In-process agent not loaded");
226 return 0;
229 if (agent_capability_check (AGENT_CAPA_STATIC_TRACE))
231 /* Agent understands static tracepoint, then check whether UST is in
232 fact loaded in the inferior. */
233 if (read_inferior_integer (ipa_sym_addrs.addr_ust_loaded, &loaded))
235 warning ("Error reading ust_loaded in lib");
236 return 0;
239 return loaded;
241 else
242 return 0;
245 static void
246 write_e_ipa_not_loaded (char *buffer)
248 sprintf (buffer,
249 "E.In-process agent library not loaded in process. "
250 "Fast and static tracepoints unavailable.");
253 /* Write an error to BUFFER indicating that UST isn't loaded in the
254 inferior. */
256 static void
257 write_e_ust_not_loaded (char *buffer)
259 #ifdef HAVE_UST
260 sprintf (buffer,
261 "E.UST library not loaded in process. "
262 "Static tracepoints unavailable.");
263 #else
264 sprintf (buffer, "E.GDBserver was built without static tracepoints support");
265 #endif
268 /* If the in-process agent library isn't loaded in the inferior, write
269 an error to BUFFER, and return 1. Otherwise, return 0. */
271 static int
272 maybe_write_ipa_not_loaded (char *buffer)
274 if (!agent_loaded_p ())
276 write_e_ipa_not_loaded (buffer);
277 return 1;
279 return 0;
282 /* If the in-process agent library and the ust (static tracepoints)
283 library aren't loaded in the inferior, write an error to BUFFER,
284 and return 1. Otherwise, return 0. */
286 static int
287 maybe_write_ipa_ust_not_loaded (char *buffer)
289 if (!agent_loaded_p ())
291 write_e_ipa_not_loaded (buffer);
292 return 1;
294 else if (!in_process_agent_supports_ust ())
296 write_e_ust_not_loaded (buffer);
297 return 1;
299 return 0;
302 /* Cache all future symbols that the tracepoints module might request.
303 We can not request symbols at arbitrary states in the remote
304 protocol, only when the client tells us that new symbols are
305 available. So when we load the in-process library, make sure to
306 check the entire list. */
308 void
309 tracepoint_look_up_symbols (void)
311 int i;
313 if (agent_loaded_p ())
314 return;
316 for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
318 CORE_ADDR *addrp =
319 (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
321 if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
323 threads_debug_printf ("symbol `%s' not found", symbol_list[i].name);
324 return;
328 agent_look_up_symbols (NULL);
331 #endif
333 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
334 of the "stop_tracing" function. When this breakpoint is hit,
335 tracing stopped in the IPA for some reason. E.g., due to
336 tracepoint reaching the pass count, hitting conditional expression
337 evaluation error, etc.
339 The IPA's trace buffer is never in circular tracing mode: instead,
340 GDBserver's is, and whenever the in-process buffer fills, it calls
341 "flush_trace_buffer", which triggers an internal breakpoint.
342 GDBserver reacts to this breakpoint by pulling the meanwhile
343 collected data. Old frames discarding is always handled on the
344 GDBserver side. */
346 #ifdef IN_PROCESS_AGENT
347 /* See target.h. */
350 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
352 memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
353 return 0;
356 /* Call this in the functions where GDBserver places a breakpoint, so
357 that the compiler doesn't try to be clever and skip calling the
358 function at all. This is necessary, even if we tell the compiler
359 to not inline said functions. */
361 #if defined(__GNUC__)
362 # define UNKNOWN_SIDE_EFFECTS() asm ("")
363 #else
364 # define UNKNOWN_SIDE_EFFECTS() do {} while (0)
365 #endif
367 /* This is needed for -Wmissing-declarations. */
368 IP_AGENT_EXPORT_FUNC void stop_tracing (void);
370 IP_AGENT_EXPORT_FUNC void
371 stop_tracing (void)
373 /* GDBserver places breakpoint here. */
374 UNKNOWN_SIDE_EFFECTS();
377 /* This is needed for -Wmissing-declarations. */
378 IP_AGENT_EXPORT_FUNC void flush_trace_buffer (void);
380 IP_AGENT_EXPORT_FUNC void
381 flush_trace_buffer (void)
383 /* GDBserver places breakpoint here. */
384 UNKNOWN_SIDE_EFFECTS();
387 #endif
389 #ifndef IN_PROCESS_AGENT
390 static int
391 tracepoint_handler (CORE_ADDR address)
393 trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
394 paddress (address));
395 return 0;
398 /* Breakpoint at "stop_tracing" in the inferior lib. */
399 static struct breakpoint *stop_tracing_bkpt;
400 static int stop_tracing_handler (CORE_ADDR);
402 /* Breakpoint at "flush_trace_buffer" in the inferior lib. */
403 static struct breakpoint *flush_trace_buffer_bkpt;
404 static int flush_trace_buffer_handler (CORE_ADDR);
406 static void download_trace_state_variables (void);
407 static void upload_fast_traceframes (void);
409 static int run_inferior_command (char *cmd, int len);
411 static int
412 read_inferior_integer (CORE_ADDR symaddr, int *val)
414 return read_inferior_memory (symaddr, (unsigned char *) val,
415 sizeof (*val));
418 struct tracepoint;
419 static int tracepoint_send_agent (struct tracepoint *tpoint);
421 static int
422 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
424 return read_inferior_memory (symaddr, (unsigned char *) val,
425 sizeof (*val));
428 static int
429 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
431 void *pval = (void *) (uintptr_t) val;
432 int ret;
434 ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
435 *val = (uintptr_t) pval;
436 return ret;
439 static int
440 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
442 void *pval = (void *) (uintptr_t) val;
443 return target_write_memory (symaddr,
444 (unsigned char *) &pval, sizeof (pval));
447 static int
448 write_inferior_integer (CORE_ADDR symaddr, int val)
450 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
453 static int
454 write_inferior_int8 (CORE_ADDR symaddr, int8_t val)
456 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
459 static int
460 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
462 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
465 static CORE_ADDR target_malloc (ULONGEST size);
467 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD) \
468 do { \
469 memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
470 BUF += sizeof ((OBJ)->FIELD); \
471 } while (0)
473 #endif
475 /* Base action. Concrete actions inherit this. */
477 struct tracepoint_action
479 char type;
482 /* An 'M' (collect memory) action. */
483 struct collect_memory_action
485 struct tracepoint_action base;
487 ULONGEST addr;
488 ULONGEST len;
489 int32_t basereg;
492 /* An 'R' (collect registers) action. */
494 struct collect_registers_action
496 struct tracepoint_action base;
499 /* An 'X' (evaluate expression) action. */
501 struct eval_expr_action
503 struct tracepoint_action base;
505 struct agent_expr *expr;
508 /* An 'L' (collect static trace data) action. */
509 struct collect_static_trace_data_action
511 struct tracepoint_action base;
514 #ifndef IN_PROCESS_AGENT
515 static CORE_ADDR
516 m_tracepoint_action_download (const struct tracepoint_action *action)
518 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_memory_action));
520 target_write_memory (ipa_action, (unsigned char *) action,
521 sizeof (struct collect_memory_action));
523 return ipa_action;
525 static char *
526 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
528 struct collect_memory_action *maction
529 = (struct collect_memory_action *) action;
531 COPY_FIELD_TO_BUF (buffer, maction, addr);
532 COPY_FIELD_TO_BUF (buffer, maction, len);
533 COPY_FIELD_TO_BUF (buffer, maction, basereg);
535 return buffer;
538 static CORE_ADDR
539 r_tracepoint_action_download (const struct tracepoint_action *action)
541 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_registers_action));
543 target_write_memory (ipa_action, (unsigned char *) action,
544 sizeof (struct collect_registers_action));
546 return ipa_action;
549 static char *
550 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
552 return buffer;
555 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
557 static CORE_ADDR
558 x_tracepoint_action_download (const struct tracepoint_action *action)
560 CORE_ADDR ipa_action = target_malloc (sizeof (struct eval_expr_action));
561 CORE_ADDR expr;
563 target_write_memory (ipa_action, (unsigned char *) action,
564 sizeof (struct eval_expr_action));
565 expr = download_agent_expr (((struct eval_expr_action *) action)->expr);
566 write_inferior_data_pointer (ipa_action
567 + offsetof (struct eval_expr_action, expr),
568 expr);
570 return ipa_action;
573 /* Copy agent expression AEXPR to buffer pointed by P. If AEXPR is NULL,
574 copy 0 to P. Return updated header of buffer. */
576 static char *
577 agent_expr_send (char *p, const struct agent_expr *aexpr)
579 /* Copy the length of condition first, and then copy its
580 content. */
581 if (aexpr == NULL)
583 memset (p, 0, 4);
584 p += 4;
586 else
588 memcpy (p, &aexpr->length, 4);
589 p +=4;
591 memcpy (p, aexpr->bytes, aexpr->length);
592 p += aexpr->length;
594 return p;
597 static char *
598 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
600 struct eval_expr_action *eaction = (struct eval_expr_action *) action;
602 return agent_expr_send (buffer, eaction->expr);
605 static CORE_ADDR
606 l_tracepoint_action_download (const struct tracepoint_action *action)
608 CORE_ADDR ipa_action
609 = target_malloc (sizeof (struct collect_static_trace_data_action));
611 target_write_memory (ipa_action, (unsigned char *) action,
612 sizeof (struct collect_static_trace_data_action));
614 return ipa_action;
617 static char *
618 l_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
620 return buffer;
623 static char *
624 tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
626 switch (action->type)
628 case 'M':
629 return m_tracepoint_action_send (buffer, action);
630 case 'R':
631 return r_tracepoint_action_send (buffer, action);
632 case 'X':
633 return x_tracepoint_action_send (buffer, action);
634 case 'L':
635 return l_tracepoint_action_send (buffer, action);
637 error ("Unknown trace action '%c'.", action->type);
640 static CORE_ADDR
641 tracepoint_action_download (const struct tracepoint_action *action)
643 switch (action->type)
645 case 'M':
646 return m_tracepoint_action_download (action);
647 case 'R':
648 return r_tracepoint_action_download (action);
649 case 'X':
650 return x_tracepoint_action_download (action);
651 case 'L':
652 return l_tracepoint_action_download (action);
654 error ("Unknown trace action '%c'.", action->type);
656 #endif
658 /* This structure describes a piece of the source-level definition of
659 the tracepoint. The contents are not interpreted by the target,
660 but preserved verbatim for uploading upon reconnection. */
662 struct source_string
664 /* The type of string, such as "cond" for a conditional. */
665 char *type;
667 /* The source-level string itself. For the sake of target
668 debugging, we store it in plaintext, even though it is always
669 transmitted in hex. */
670 char *str;
672 /* Link to the next one in the list. We link them in the order
673 received, in case some make up an ordered list of commands or
674 some such. */
675 struct source_string *next;
678 enum tracepoint_type
680 /* Trap based tracepoint. */
681 trap_tracepoint,
683 /* A fast tracepoint implemented with a jump instead of a trap. */
684 fast_tracepoint,
686 /* A static tracepoint, implemented by a program call into a tracing
687 library. */
688 static_tracepoint
691 struct tracepoint_hit_ctx;
693 typedef enum eval_result_type (*condfn) (unsigned char *,
694 ULONGEST *);
696 /* The definition of a tracepoint. */
698 /* Tracepoints may have multiple locations, each at a different
699 address. This can occur with optimizations, template
700 instantiation, etc. Since the locations may be in different
701 scopes, the conditions and actions may be different for each
702 location. Our target version of tracepoints is more like GDB's
703 notion of "breakpoint locations", but we have almost nothing that
704 is not per-location, so we bother having two kinds of objects. The
705 key consequence is that numbers are not unique, and that it takes
706 both number and address to identify a tracepoint uniquely. */
708 struct tracepoint
710 /* The number of the tracepoint, as specified by GDB. Several
711 tracepoint objects here may share a number. */
712 uint32_t number;
714 /* Address at which the tracepoint is supposed to trigger. Several
715 tracepoints may share an address. */
716 CORE_ADDR address;
718 /* Tracepoint type. */
719 enum tracepoint_type type;
721 /* True if the tracepoint is currently enabled. */
722 int8_t enabled;
724 /* The number of single steps that will be performed after each
725 tracepoint hit. */
726 uint64_t step_count;
728 /* The number of times the tracepoint may be hit before it will
729 terminate the entire tracing run. */
730 uint64_t pass_count;
732 /* Pointer to the agent expression that is the tracepoint's
733 conditional, or NULL if the tracepoint is unconditional. */
734 struct agent_expr *cond;
736 /* The list of actions to take when the tracepoint triggers. */
737 uint32_t numactions;
738 struct tracepoint_action **actions;
740 /* Count of the times we've hit this tracepoint during the run.
741 Note that while-stepping steps are not counted as "hits". */
742 uint64_t hit_count;
744 /* Cached sum of the sizes of traceframes created by this point. */
745 uint64_t traceframe_usage;
747 CORE_ADDR compiled_cond;
749 /* Link to the next tracepoint in the list. */
750 struct tracepoint *next;
752 #ifndef IN_PROCESS_AGENT
753 /* The list of actions to take when the tracepoint triggers, in
754 string/packet form. */
755 char **actions_str;
757 /* The collection of strings that describe the tracepoint as it was
758 entered into GDB. These are not used by the target, but are
759 reported back to GDB upon reconnection. */
760 struct source_string *source_strings;
762 /* The number of bytes displaced by fast tracepoints. It may subsume
763 multiple instructions, for multi-byte fast tracepoints. This
764 field is only valid for fast tracepoints. */
765 uint32_t orig_size;
767 /* Only for fast tracepoints. */
768 CORE_ADDR obj_addr_on_target;
770 /* Address range where the original instruction under a fast
771 tracepoint was relocated to. (_end is actually one byte past
772 the end). */
773 CORE_ADDR adjusted_insn_addr;
774 CORE_ADDR adjusted_insn_addr_end;
776 /* The address range of the piece of the jump pad buffer that was
777 assigned to this fast tracepoint. (_end is actually one byte
778 past the end).*/
779 CORE_ADDR jump_pad;
780 CORE_ADDR jump_pad_end;
782 /* The address range of the piece of the trampoline buffer that was
783 assigned to this fast tracepoint. (_end is actually one byte
784 past the end). */
785 CORE_ADDR trampoline;
786 CORE_ADDR trampoline_end;
788 /* The list of actions to take while in a stepping loop. These
789 fields are only valid for patch-based tracepoints. */
790 int num_step_actions;
791 struct tracepoint_action **step_actions;
792 /* Same, but in string/packet form. */
793 char **step_actions_str;
795 /* Handle returned by the breakpoint or tracepoint module when we
796 inserted the trap or jump, or hooked into a static tracepoint.
797 NULL if we haven't inserted it yet. */
798 void *handle;
799 #endif
803 #ifndef IN_PROCESS_AGENT
805 /* Given `while-stepping', a thread may be collecting data for more
806 than one tracepoint simultaneously. On the other hand, the same
807 tracepoint with a while-stepping action may be hit by more than one
808 thread simultaneously (but not quite, each thread could be handling
809 a different step). Each thread holds a list of these objects,
810 representing the current step of each while-stepping action being
811 collected. */
813 struct wstep_state
815 struct wstep_state *next;
817 /* The tracepoint number. */
818 int tp_number;
819 /* The tracepoint's address. */
820 CORE_ADDR tp_address;
822 /* The number of the current step in this 'while-stepping'
823 action. */
824 long current_step;
827 #endif
829 EXTERN_C_PUSH
831 /* The linked list of all tracepoints. Marked explicitly as used as
832 the in-process library doesn't use it for the fast tracepoints
833 support. */
834 IP_AGENT_EXPORT_VAR struct tracepoint *tracepoints;
836 /* The first tracepoint to exceed its pass count. */
838 IP_AGENT_EXPORT_VAR struct tracepoint *stopping_tracepoint;
840 /* True if the trace buffer is full or otherwise no longer usable. */
842 IP_AGENT_EXPORT_VAR int trace_buffer_is_full;
844 /* The first error that occurred during expression evaluation. */
846 /* Stored as an int to avoid the IPA ABI being dependent on whatever
847 the compiler decides to use for the enum's underlying type. Holds
848 enum eval_result_type values. */
849 IP_AGENT_EXPORT_VAR int expr_eval_result = expr_eval_no_error;
851 EXTERN_C_POP
853 #ifndef IN_PROCESS_AGENT
855 /* Pointer to the last tracepoint in the list, new tracepoints are
856 linked in at the end. */
858 static struct tracepoint *last_tracepoint;
860 static const char * const eval_result_names[] =
862 "terror:in the attic", /* this should never be reported */
863 "terror:empty expression",
864 "terror:empty stack",
865 "terror:stack overflow",
866 "terror:stack underflow",
867 "terror:unhandled opcode",
868 "terror:unrecognized opcode",
869 "terror:divide by zero"
872 #endif
874 /* The tracepoint in which the error occurred. */
876 EXTERN_C_PUSH
877 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
878 EXTERN_C_POP
880 struct trace_state_variable
882 /* This is the name of the variable as used in GDB. The target
883 doesn't use the name, but needs to have it for saving and
884 reconnection purposes. */
885 char *name;
887 /* This number identifies the variable uniquely. Numbers may be
888 assigned either by the target (in the case of builtin variables),
889 or by GDB, and are presumed unique during the course of a trace
890 experiment. */
891 int number;
893 /* The variable's initial value, a 64-bit signed integer always. */
894 LONGEST initial_value;
896 /* The variable's value, a 64-bit signed integer always. */
897 LONGEST value;
899 /* Pointer to a getter function, used to supply computed values. */
900 LONGEST (*getter) (void);
902 /* Link to the next variable. */
903 struct trace_state_variable *next;
906 /* Linked list of all trace state variables. */
908 #ifdef IN_PROCESS_AGENT
909 static struct trace_state_variable *alloced_trace_state_variables;
910 #endif
912 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
914 /* The results of tracing go into a fixed-size space known as the
915 "trace buffer". Because usage follows a limited number of
916 patterns, we manage it ourselves rather than with malloc. Basic
917 rules are that we create only one trace frame at a time, each is
918 variable in size, they are never moved once created, and we only
919 discard if we are doing a circular buffer, and then only the oldest
920 ones. Each trace frame includes its own size, so we don't need to
921 link them together, and the trace frame number is relative to the
922 first one, so we don't need to record numbers. A trace frame also
923 records the number of the tracepoint that created it. The data
924 itself is a series of blocks, each introduced by a single character
925 and with a defined format. Each type of block has enough
926 type/length info to allow scanners to jump quickly from one block
927 to the next without reading each byte in the block. */
929 /* Trace buffer management would be simple - advance a free pointer
930 from beginning to end, then stop - were it not for the circular
931 buffer option, which is a useful way to prevent a trace run from
932 stopping prematurely because the buffer filled up. In the circular
933 case, the location of the first trace frame (trace_buffer_start)
934 moves as old trace frames are discarded. Also, since we grow trace
935 frames incrementally as actions are performed, we wrap around to
936 the beginning of the trace buffer. This is per-block, so each
937 block within a trace frame remains contiguous. Things get messy
938 when the wrapped-around trace frame is the one being discarded; the
939 free space ends up in two parts at opposite ends of the buffer. */
941 #ifndef ATTR_PACKED
942 # if defined(__GNUC__)
943 # define ATTR_PACKED __attribute__ ((packed))
944 # else
945 # define ATTR_PACKED /* nothing */
946 # endif
947 #endif
949 /* The data collected at a tracepoint hit. This object should be as
950 small as possible, since there may be a great many of them. We do
951 not need to keep a frame number, because they are all sequential
952 and there are no deletions; so the Nth frame in the buffer is
953 always frame number N. */
955 struct traceframe
957 /* Number of the tracepoint that collected this traceframe. A value
958 of 0 indicates the current end of the trace buffer. We make this
959 a 16-bit field because it's never going to happen that GDB's
960 numbering of tracepoints reaches 32,000. */
961 int tpnum : 16;
963 /* The size of the data in this trace frame. We limit this to 32
964 bits, even on a 64-bit target, because it's just implausible that
965 one is validly going to collect 4 gigabytes of data at a single
966 tracepoint hit. */
967 unsigned int data_size : 32;
969 /* The base of the trace data, which is contiguous from this point. */
970 unsigned char data[0];
972 } ATTR_PACKED;
974 /* The size of the EOB marker, in bytes. A traceframe with zeroed
975 fields (and no data) marks the end of trace data. */
976 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
978 /* This flag is true if the trace buffer is circular, meaning that
979 when it fills, the oldest trace frames are discarded in order to
980 make room. */
982 #ifndef IN_PROCESS_AGENT
983 static int circular_trace_buffer;
984 #endif
986 /* Size of the trace buffer. */
988 static LONGEST trace_buffer_size;
990 EXTERN_C_PUSH
992 /* Pointer to the block of memory that traceframes all go into. */
994 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
996 /* Pointer to the end of the trace buffer, more precisely to the byte
997 after the end of the buffer. */
999 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
1001 EXTERN_C_POP
1003 /* Control structure holding the read/write/etc. pointers into the
1004 trace buffer. We need more than one of these to implement a
1005 transaction-like mechanism to guarantees that both GDBserver and the
1006 in-process agent can try to change the trace buffer
1007 simultaneously. */
1009 struct trace_buffer_control
1011 /* Pointer to the first trace frame in the buffer. In the
1012 non-circular case, this is equal to trace_buffer_lo, otherwise it
1013 moves around in the buffer. */
1014 unsigned char *start;
1016 /* Pointer to the free part of the trace buffer. Note that we clear
1017 several bytes at and after this pointer, so that traceframe
1018 scans/searches terminate properly. */
1019 unsigned char *free;
1021 /* Pointer to the byte after the end of the free part. Note that
1022 this may be smaller than trace_buffer_free in the circular case,
1023 and means that the free part is in two pieces. Initially it is
1024 equal to trace_buffer_hi, then is generally equivalent to
1025 trace_buffer_start. */
1026 unsigned char *end_free;
1028 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
1029 this is the point at which the trace data breaks, and resumes at
1030 trace_buffer_lo. */
1031 unsigned char *wrap;
1034 /* Same as above, to be used by GDBserver when updating the in-process
1035 agent. */
1036 struct ipa_trace_buffer_control
1038 uintptr_t start;
1039 uintptr_t free;
1040 uintptr_t end_free;
1041 uintptr_t wrap;
1045 /* We have possibly both GDBserver and an inferior thread accessing
1046 the same IPA trace buffer memory. The IPA is the producer (tries
1047 to put new frames in the buffer), while GDBserver occasionally
1048 consumes them, that is, flushes the IPA's buffer into its own
1049 buffer. Both sides need to update the trace buffer control
1050 pointers (current head, tail, etc.). We can't use a global lock to
1051 synchronize the accesses, as otherwise we could deadlock GDBserver
1052 (if the thread holding the lock stops for a signal, say). So
1053 instead of that, we use a transaction scheme where GDBserver writes
1054 always prevail over the IPAs writes, and, we have the IPA detect
1055 the commit failure/overwrite, and retry the whole attempt. This is
1056 mainly implemented by having a global token object that represents
1057 who wrote last to the buffer control structure. We need to freeze
1058 any inferior writing to the buffer while GDBserver touches memory,
1059 so that the inferior can correctly detect that GDBserver had been
1060 there, otherwise, it could mistakingly think its commit was
1061 successful; that's implemented by simply having GDBserver set a
1062 breakpoint the inferior hits if it is the critical region.
1064 There are three cycling trace buffer control structure copies
1065 (buffer head, tail, etc.), with the token object including an index
1066 indicating which is current live copy. The IPA tentatively builds
1067 an updated copy in a non-current control structure, while GDBserver
1068 always clobbers the current version directly. The IPA then tries
1069 to atomically "commit" its version; if GDBserver clobbered the
1070 structure meanwhile, that will fail, and the IPA restarts the
1071 allocation process.
1073 Listing the step in further detail, we have:
1075 In-process agent (producer):
1077 - passes by `about_to_request_buffer_space' breakpoint/lock
1079 - reads current token, extracts current trace buffer control index,
1080 and starts tentatively updating the rightmost one (0->1, 1->2,
1081 2->0). Note that only one inferior thread is executing this code
1082 at any given time, due to an outer lock in the jump pads.
1084 - updates counters, and tries to commit the token.
1086 - passes by second `about_to_request_buffer_space' breakpoint/lock,
1087 leaving the sync region.
1089 - checks if the update was effective.
1091 - if trace buffer was found full, hits flush_trace_buffer
1092 breakpoint, and restarts later afterwards.
1094 GDBserver (consumer):
1096 - sets `about_to_request_buffer_space' breakpoint/lock.
1098 - updates the token unconditionally, using the current buffer
1099 control index, since it knows that the IP agent always writes to
1100 the rightmost, and due to the breakpoint, at most one IP thread
1101 can try to update the trace buffer concurrently to GDBserver, so
1102 there will be no danger of trace buffer control index wrap making
1103 the IPA write to the same index as GDBserver.
1105 - flushes the IP agent's trace buffer completely, and updates the
1106 current trace buffer control structure. GDBserver *always* wins.
1108 - removes the `about_to_request_buffer_space' breakpoint.
1110 The token is stored in the `trace_buffer_ctrl_curr' variable.
1111 Internally, it's bits are defined as:
1113 |-------------+-----+-------------+--------+-------------+--------------|
1114 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1115 |-------------+-----+-------------+--------+-------------+--------------|
1116 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1117 |-------------+-----+-------------+--------+-------------+--------------|
1119 GSB - GDBserver Stamp Bit
1120 PC - Previous Counter
1121 CC - Current Counter
1122 TBCI - Trace Buffer Control Index
1125 An IPA update of `trace_buffer_ctrl_curr' does:
1127 - read CC from the current token, save as PC.
1128 - updates pointers
1129 - atomically tries to write PC+1,CC
1131 A GDBserver update of `trace_buffer_ctrl_curr' does:
1133 - reads PC and CC from the current token.
1134 - updates pointers
1135 - writes GSB,PC,CC
1138 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1139 for the counters described below. The cleared bits are used to
1140 hold the index of the items of the `trace_buffer_ctrl' array that
1141 is "current". */
1142 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1144 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1145 counter, and the `current' counter. */
1147 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1148 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1150 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1151 always stamps this bit as set. */
1152 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1154 #ifdef IN_PROCESS_AGENT
1155 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1156 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1158 # define TRACE_BUFFER_CTRL_CURR \
1159 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1161 #else
1163 /* The GDBserver side agent only needs one instance of this object, as
1164 it doesn't need to sync with itself. Define it as array anyway so
1165 that the rest of the code base doesn't need to care for the
1166 difference. */
1167 static trace_buffer_control trace_buffer_ctrl[1];
1168 # define TRACE_BUFFER_CTRL_CURR 0
1169 #endif
1171 /* These are convenience macros used to access the current trace
1172 buffer control in effect. */
1173 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1174 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1175 #define trace_buffer_end_free \
1176 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1177 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1180 /* Macro that returns a pointer to the first traceframe in the buffer. */
1182 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1184 /* Macro that returns a pointer to the next traceframe in the buffer.
1185 If the computed location is beyond the wraparound point, subtract
1186 the offset of the wraparound. */
1188 #define NEXT_TRACEFRAME_1(TF) \
1189 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1191 #define NEXT_TRACEFRAME(TF) \
1192 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1193 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1194 ? (trace_buffer_wrap - trace_buffer_lo) \
1195 : 0)))
1197 /* The difference between these counters represents the total number
1198 of complete traceframes present in the trace buffer. The IP agent
1199 writes to the write count, GDBserver writes to read count. */
1201 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1202 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1204 /* Convenience macro. */
1206 #define traceframe_count \
1207 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1209 /* The count of all traceframes created in the current run, including
1210 ones that were discarded to make room. */
1212 IP_AGENT_EXPORT_VAR int traceframes_created;
1214 #ifndef IN_PROCESS_AGENT
1216 /* Read-only regions are address ranges whose contents don't change,
1217 and so can be read from target memory even while looking at a trace
1218 frame. Without these, disassembly for instance will likely fail,
1219 because the program code is not usually collected into a trace
1220 frame. This data structure does not need to be very complicated or
1221 particularly efficient, it's only going to be used occasionally,
1222 and only by some commands. */
1224 struct readonly_region
1226 /* The bounds of the region. */
1227 CORE_ADDR start, end;
1229 /* Link to the next one. */
1230 struct readonly_region *next;
1233 /* Linked list of readonly regions. This list stays in effect from
1234 one tstart to the next. */
1236 static struct readonly_region *readonly_regions;
1238 #endif
1240 /* The global that controls tracing overall. */
1242 IP_AGENT_EXPORT_VAR int tracing;
1244 #ifndef IN_PROCESS_AGENT
1246 /* Controls whether tracing should continue after GDB disconnects. */
1248 int disconnected_tracing;
1250 /* The reason for the last tracing run to have stopped. We initialize
1251 to a distinct string so that GDB can distinguish between "stopped
1252 after running" and "stopped because never run" cases. */
1254 static const char *tracing_stop_reason = "tnotrun";
1256 static int tracing_stop_tpnum;
1258 /* 64-bit timestamps for the trace run's start and finish, expressed
1259 in microseconds from the Unix epoch. */
1261 static LONGEST tracing_start_time;
1262 static LONGEST tracing_stop_time;
1264 /* The (optional) user-supplied name of the user that started the run.
1265 This is an arbitrary string, and may be NULL. */
1267 static char *tracing_user_name;
1269 /* Optional user-supplied text describing the run. This is
1270 an arbitrary string, and may be NULL. */
1272 static char *tracing_notes;
1274 /* Optional user-supplied text explaining a tstop command. This is an
1275 arbitrary string, and may be NULL. */
1277 static char *tracing_stop_note;
1279 #endif
1281 /* Functions local to this file. */
1283 /* Base "class" for tracepoint type specific data to be passed down to
1284 collect_data_at_tracepoint. */
1285 struct tracepoint_hit_ctx
1287 enum tracepoint_type type;
1290 #ifdef IN_PROCESS_AGENT
1292 /* Fast/jump tracepoint specific data to be passed down to
1293 collect_data_at_tracepoint. */
1294 struct fast_tracepoint_ctx
1296 struct tracepoint_hit_ctx base;
1298 struct regcache regcache;
1299 int regcache_initted;
1300 unsigned char *regspace;
1302 unsigned char *regs;
1303 struct tracepoint *tpoint;
1306 /* Static tracepoint specific data to be passed down to
1307 collect_data_at_tracepoint. */
1308 struct static_tracepoint_ctx
1310 struct tracepoint_hit_ctx base;
1312 /* The regcache corresponding to the registers state at the time of
1313 the tracepoint hit. Initialized lazily, from REGS. */
1314 struct regcache regcache;
1315 int regcache_initted;
1317 /* The buffer space REGCACHE above uses. We use a separate buffer
1318 instead of letting the regcache malloc for both signal safety and
1319 performance reasons; this is allocated on the stack instead. */
1320 unsigned char *regspace;
1322 /* The register buffer as passed on by lttng/ust. */
1323 struct registers *regs;
1325 /* The "printf" formatter and the args the user passed to the marker
1326 call. We use this to be able to collect "static trace data"
1327 ($_sdata). */
1328 const char *fmt;
1329 va_list *args;
1331 /* The GDB tracepoint matching the probed marker that was "hit". */
1332 struct tracepoint *tpoint;
1335 #else
1337 /* Static tracepoint specific data to be passed down to
1338 collect_data_at_tracepoint. */
1339 struct trap_tracepoint_ctx
1341 struct tracepoint_hit_ctx base;
1343 struct regcache *regcache;
1346 #endif
1348 #ifndef IN_PROCESS_AGENT
1349 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1350 static int traceframe_read_tsv (int num, LONGEST *val);
1351 #endif
1353 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1354 struct tracepoint *tpoint);
1356 #ifndef IN_PROCESS_AGENT
1357 static void clear_readonly_regions (void);
1358 static void clear_installed_tracepoints (void);
1359 #endif
1361 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1362 CORE_ADDR stop_pc,
1363 struct tracepoint *tpoint);
1364 #ifndef IN_PROCESS_AGENT
1365 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1366 CORE_ADDR stop_pc,
1367 struct tracepoint *tpoint, int current_step);
1368 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1369 CORE_ADDR *jump_entry);
1370 #endif
1371 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1372 CORE_ADDR stop_pc,
1373 struct tracepoint *tpoint,
1374 struct traceframe *tframe,
1375 struct tracepoint_action *taction);
1377 #ifndef IN_PROCESS_AGENT
1378 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1380 static void install_tracepoint (struct tracepoint *, char *own_buf);
1381 static void download_tracepoint (struct tracepoint *);
1382 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1383 static void clone_fast_tracepoint (struct tracepoint *to,
1384 const struct tracepoint *from);
1385 #endif
1387 static LONGEST get_timestamp (void);
1389 #if defined(__GNUC__)
1390 # define memory_barrier() asm volatile ("" : : : "memory")
1391 #else
1392 # define memory_barrier() do {} while (0)
1393 #endif
1395 /* We only build the IPA if this builtin is supported, and there are
1396 no uses of this in GDBserver itself, so we're safe in defining this
1397 unconditionally. */
1398 #define cmpxchg(mem, oldval, newval) \
1399 __sync_val_compare_and_swap (mem, oldval, newval)
1401 /* Record that an error occurred during expression evaluation. */
1403 static void
1404 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1405 enum eval_result_type rtype)
1407 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1408 tpoint->number, paddress (tpoint->address), which, rtype);
1410 #ifdef IN_PROCESS_AGENT
1411 /* Only record the first error we get. */
1412 if (cmpxchg (&expr_eval_result,
1413 expr_eval_no_error,
1414 rtype) != expr_eval_no_error)
1415 return;
1416 #else
1417 if (expr_eval_result != expr_eval_no_error)
1418 return;
1419 #endif
1421 error_tracepoint = tpoint;
1424 /* Trace buffer management. */
1426 static void
1427 clear_trace_buffer (void)
1429 trace_buffer_start = trace_buffer_lo;
1430 trace_buffer_free = trace_buffer_lo;
1431 trace_buffer_end_free = trace_buffer_hi;
1432 trace_buffer_wrap = trace_buffer_hi;
1433 /* A traceframe with zeroed fields marks the end of trace data. */
1434 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1435 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1436 traceframe_read_count = traceframe_write_count = 0;
1437 traceframes_created = 0;
1440 #ifndef IN_PROCESS_AGENT
1442 static void
1443 clear_inferior_trace_buffer (void)
1445 CORE_ADDR ipa_trace_buffer_lo;
1446 CORE_ADDR ipa_trace_buffer_hi;
1447 struct traceframe ipa_traceframe = { 0 };
1448 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1450 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1451 &ipa_trace_buffer_lo);
1452 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1453 &ipa_trace_buffer_hi);
1455 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1456 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1457 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1458 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1460 /* A traceframe with zeroed fields marks the end of trace data. */
1461 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1462 (unsigned char *) &ipa_trace_buffer_ctrl,
1463 sizeof (ipa_trace_buffer_ctrl));
1465 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1467 /* A traceframe with zeroed fields marks the end of trace data. */
1468 target_write_memory (ipa_trace_buffer_lo,
1469 (unsigned char *) &ipa_traceframe,
1470 sizeof (ipa_traceframe));
1472 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1473 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1474 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1477 #endif
1479 static void
1480 init_trace_buffer (LONGEST bufsize)
1482 size_t alloc_size;
1484 trace_buffer_size = bufsize;
1486 /* Make sure to internally allocate at least space for the EOB
1487 marker. */
1488 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1489 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1490 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1492 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1494 clear_trace_buffer ();
1497 #ifdef IN_PROCESS_AGENT
1499 /* This is needed for -Wmissing-declarations. */
1500 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1502 IP_AGENT_EXPORT_FUNC void
1503 about_to_request_buffer_space (void)
1505 /* GDBserver places breakpoint here while it goes about to flush
1506 data at random times. */
1507 UNKNOWN_SIDE_EFFECTS();
1510 #endif
1512 /* Carve out a piece of the trace buffer, returning NULL in case of
1513 failure. */
1515 static void *
1516 trace_buffer_alloc (size_t amt)
1518 unsigned char *rslt;
1519 struct trace_buffer_control *tbctrl;
1520 unsigned int curr;
1521 #ifdef IN_PROCESS_AGENT
1522 unsigned int prev, prev_filtered;
1523 unsigned int commit_count;
1524 unsigned int commit;
1525 unsigned int readout;
1526 #else
1527 struct traceframe *oldest;
1528 unsigned char *new_start;
1529 #endif
1531 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1532 (long) amt, (long) sizeof (struct traceframe));
1534 /* Account for the EOB marker. */
1535 amt += TRACEFRAME_EOB_MARKER_SIZE;
1537 #ifdef IN_PROCESS_AGENT
1538 again:
1539 memory_barrier ();
1541 /* Read the current token and extract the index to try to write to,
1542 storing it in CURR. */
1543 prev = trace_buffer_ctrl_curr;
1544 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1545 curr = prev_filtered + 1;
1546 if (curr > 2)
1547 curr = 0;
1549 about_to_request_buffer_space ();
1551 /* Start out with a copy of the current state. GDBserver may be
1552 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1553 be able to commit anyway if that happens. */
1554 trace_buffer_ctrl[curr]
1555 = trace_buffer_ctrl[prev_filtered];
1556 trace_debug ("trying curr=%u", curr);
1557 #else
1558 /* The GDBserver's agent doesn't need all that syncing, and always
1559 updates TCB 0 (there's only one, mind you). */
1560 curr = 0;
1561 #endif
1562 tbctrl = &trace_buffer_ctrl[curr];
1564 /* Offsets are easier to grok for debugging than raw addresses,
1565 especially for the small trace buffer sizes that are useful for
1566 testing. */
1567 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1568 curr,
1569 (int) (tbctrl->start - trace_buffer_lo),
1570 (int) (tbctrl->free - trace_buffer_lo),
1571 (int) (tbctrl->end_free - trace_buffer_lo),
1572 (int) (tbctrl->wrap - trace_buffer_lo),
1573 (int) (trace_buffer_hi - trace_buffer_lo));
1575 /* The algorithm here is to keep trying to get a contiguous block of
1576 the requested size, possibly discarding older traceframes to free
1577 up space. Since free space might come in one or two pieces,
1578 depending on whether discarded traceframes wrapped around at the
1579 high end of the buffer, we test both pieces after each
1580 discard. */
1581 while (1)
1583 /* First, if we have two free parts, try the upper one first. */
1584 if (tbctrl->end_free < tbctrl->free)
1586 if (tbctrl->free + amt <= trace_buffer_hi)
1587 /* We have enough in the upper part. */
1588 break;
1589 else
1591 /* Our high part of free space wasn't enough. Give up
1592 on it for now, set wraparound. We will recover the
1593 space later, if/when the wrapped-around traceframe is
1594 discarded. */
1595 trace_debug ("Upper part too small, setting wraparound");
1596 tbctrl->wrap = tbctrl->free;
1597 tbctrl->free = trace_buffer_lo;
1601 /* The normal case. */
1602 if (tbctrl->free + amt <= tbctrl->end_free)
1603 break;
1605 #ifdef IN_PROCESS_AGENT
1606 /* The IP Agent's buffer is always circular. It isn't used
1607 currently, but `circular_trace_buffer' could represent
1608 GDBserver's mode. If we didn't find space, ask GDBserver to
1609 flush. */
1611 flush_trace_buffer ();
1612 memory_barrier ();
1613 if (tracing)
1615 trace_debug ("gdbserver flushed buffer, retrying");
1616 goto again;
1619 /* GDBserver cancelled the tracing. Bail out as well. */
1620 return NULL;
1621 #else
1622 /* If we're here, then neither part is big enough, and
1623 non-circular trace buffers are now full. */
1624 if (!circular_trace_buffer)
1626 trace_debug ("Not enough space in the trace buffer");
1627 return NULL;
1630 trace_debug ("Need more space in the trace buffer");
1632 /* If we have a circular buffer, we can try discarding the
1633 oldest traceframe and see if that helps. */
1634 oldest = FIRST_TRACEFRAME ();
1635 if (oldest->tpnum == 0)
1637 /* Not good; we have no traceframes to free. Perhaps we're
1638 asking for a block that is larger than the buffer? In
1639 any case, give up. */
1640 trace_debug ("No traceframes to discard");
1641 return NULL;
1644 /* We don't run this code in the in-process agent currently.
1645 E.g., we could leave the in-process agent in autonomous
1646 circular mode if we only have fast tracepoints. If we do
1647 that, then this bit becomes racy with GDBserver, which also
1648 writes to this counter. */
1649 --traceframe_write_count;
1651 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1652 /* If we freed the traceframe that wrapped around, go back
1653 to the non-wrap case. */
1654 if (new_start < tbctrl->start)
1656 trace_debug ("Discarding past the wraparound");
1657 tbctrl->wrap = trace_buffer_hi;
1659 tbctrl->start = new_start;
1660 tbctrl->end_free = tbctrl->start;
1662 trace_debug ("Discarded a traceframe\n"
1663 "Trace buffer [%d], start=%d free=%d "
1664 "endfree=%d wrap=%d hi=%d",
1665 curr,
1666 (int) (tbctrl->start - trace_buffer_lo),
1667 (int) (tbctrl->free - trace_buffer_lo),
1668 (int) (tbctrl->end_free - trace_buffer_lo),
1669 (int) (tbctrl->wrap - trace_buffer_lo),
1670 (int) (trace_buffer_hi - trace_buffer_lo));
1672 /* Now go back around the loop. The discard might have resulted
1673 in either one or two pieces of free space, so we want to try
1674 both before freeing any more traceframes. */
1675 #endif
1678 /* If we get here, we know we can provide the asked-for space. */
1680 rslt = tbctrl->free;
1682 /* Adjust the request back down, now that we know we have space for
1683 the marker, but don't commit to AMT yet, we may still need to
1684 restart the operation if GDBserver touches the trace buffer
1685 (obviously only important in the in-process agent's version). */
1686 tbctrl->free += (amt - sizeof (struct traceframe));
1688 /* Or not. If GDBserver changed the trace buffer behind our back,
1689 we get to restart a new allocation attempt. */
1691 #ifdef IN_PROCESS_AGENT
1692 /* Build the tentative token. */
1693 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1694 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1695 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1696 | commit_count
1697 | curr);
1699 /* Try to commit it. */
1700 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1701 if (readout != prev)
1703 trace_debug ("GDBserver has touched the trace buffer, restarting."
1704 " (prev=%08x, commit=%08x, readout=%08x)",
1705 prev, commit, readout);
1706 goto again;
1709 /* Hold your horses here. Even if that change was committed,
1710 GDBserver could come in, and clobber it. We need to hold to be
1711 able to tell if GDBserver clobbers before or after we committed
1712 the change. Whenever GDBserver goes about touching the IPA
1713 buffer, it sets a breakpoint in this routine, so we have a sync
1714 point here. */
1715 about_to_request_buffer_space ();
1717 /* Check if the change has been effective, even if GDBserver stopped
1718 us at the breakpoint. */
1721 unsigned int refetch;
1723 memory_barrier ();
1725 refetch = trace_buffer_ctrl_curr;
1727 if (refetch == commit
1728 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1730 /* effective */
1731 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1732 "readout=%08x, refetch=%08x)",
1733 prev, commit, readout, refetch);
1735 else
1737 trace_debug ("GDBserver has touched the trace buffer, not effective."
1738 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1739 prev, commit, readout, refetch);
1740 goto again;
1743 #endif
1745 /* We have a new piece of the trace buffer. Hurray! */
1747 /* Add an EOB marker just past this allocation. */
1748 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1749 ((struct traceframe *) tbctrl->free)->data_size = 0;
1751 /* Adjust the request back down, now that we know we have space for
1752 the marker. */
1753 amt -= sizeof (struct traceframe);
1755 if (debug_threads)
1757 trace_debug ("Allocated %d bytes", (int) amt);
1758 trace_debug ("Trace buffer [%d] start=%d free=%d "
1759 "endfree=%d wrap=%d hi=%d",
1760 curr,
1761 (int) (tbctrl->start - trace_buffer_lo),
1762 (int) (tbctrl->free - trace_buffer_lo),
1763 (int) (tbctrl->end_free - trace_buffer_lo),
1764 (int) (tbctrl->wrap - trace_buffer_lo),
1765 (int) (trace_buffer_hi - trace_buffer_lo));
1768 return rslt;
1771 #ifndef IN_PROCESS_AGENT
1773 /* Return the total free space. This is not necessarily the largest
1774 block we can allocate, because of the two-part case. */
1776 static int
1777 free_space (void)
1779 if (trace_buffer_free <= trace_buffer_end_free)
1780 return trace_buffer_end_free - trace_buffer_free;
1781 else
1782 return ((trace_buffer_end_free - trace_buffer_lo)
1783 + (trace_buffer_hi - trace_buffer_free));
1786 /* An 'S' in continuation packets indicates remainder are for
1787 while-stepping. */
1789 static int seen_step_action_flag;
1791 /* Create a tracepoint (location) with given number and address. Add this
1792 new tracepoint to list and sort this list. */
1794 static struct tracepoint *
1795 add_tracepoint (int num, CORE_ADDR addr)
1797 struct tracepoint *tpoint, **tp_next;
1799 tpoint = XNEW (struct tracepoint);
1800 tpoint->number = num;
1801 tpoint->address = addr;
1802 tpoint->numactions = 0;
1803 tpoint->actions = NULL;
1804 tpoint->actions_str = NULL;
1805 tpoint->cond = NULL;
1806 tpoint->num_step_actions = 0;
1807 tpoint->step_actions = NULL;
1808 tpoint->step_actions_str = NULL;
1809 /* Start all off as regular (slow) tracepoints. */
1810 tpoint->type = trap_tracepoint;
1811 tpoint->orig_size = -1;
1812 tpoint->source_strings = NULL;
1813 tpoint->compiled_cond = 0;
1814 tpoint->handle = NULL;
1815 tpoint->next = NULL;
1817 /* Find a place to insert this tracepoint into list in order to keep
1818 the tracepoint list still in the ascending order. There may be
1819 multiple tracepoints at the same address as TPOINT's, and this
1820 guarantees TPOINT is inserted after all the tracepoints which are
1821 set at the same address. For example, fast tracepoints A, B, C are
1822 set at the same address, and D is to be insert at the same place as
1823 well,
1825 -->| A |--> | B |-->| C |->...
1827 One jump pad was created for tracepoint A, B, and C, and the target
1828 address of A is referenced/used in jump pad. So jump pad will let
1829 inferior jump to A. If D is inserted in front of A, like this,
1831 -->| D |-->| A |--> | B |-->| C |->...
1833 without updating jump pad, D is not reachable during collect, which
1834 is wrong. As we can see, the order of B, C and D doesn't matter, but
1835 A should always be the `first' one. */
1836 for (tp_next = &tracepoints;
1837 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1838 tp_next = &(*tp_next)->next)
1840 tpoint->next = *tp_next;
1841 *tp_next = tpoint;
1842 last_tracepoint = tpoint;
1844 seen_step_action_flag = 0;
1846 return tpoint;
1849 #ifndef IN_PROCESS_AGENT
1851 /* Return the tracepoint with the given number and address, or NULL. */
1853 static struct tracepoint *
1854 find_tracepoint (int id, CORE_ADDR addr)
1856 struct tracepoint *tpoint;
1858 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1859 if (tpoint->number == id && tpoint->address == addr)
1860 return tpoint;
1862 return NULL;
1865 /* Remove TPOINT from global list. */
1867 static void
1868 remove_tracepoint (struct tracepoint *tpoint)
1870 struct tracepoint *tp, *tp_prev;
1872 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1873 tp_prev = tp, tp = tp->next)
1876 if (tp)
1878 if (tp_prev)
1879 tp_prev->next = tp->next;
1880 else
1881 tracepoints = tp->next;
1883 xfree (tp);
1887 /* There may be several tracepoints with the same number (because they
1888 are "locations", in GDB parlance); return the next one after the
1889 given tracepoint, or search from the beginning of the list if the
1890 first argument is NULL. */
1892 static struct tracepoint *
1893 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1895 struct tracepoint *tpoint;
1897 if (prev_tp)
1898 tpoint = prev_tp->next;
1899 else
1900 tpoint = tracepoints;
1901 for (; tpoint; tpoint = tpoint->next)
1902 if (tpoint->number == num)
1903 return tpoint;
1905 return NULL;
1908 #endif
1910 /* Append another action to perform when the tracepoint triggers. */
1912 static void
1913 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1915 const char *act;
1917 if (*packet == 'S')
1919 seen_step_action_flag = 1;
1920 ++packet;
1923 act = packet;
1925 while (*act)
1927 const char *act_start = act;
1928 struct tracepoint_action *action = NULL;
1930 switch (*act)
1932 case 'M':
1934 struct collect_memory_action *maction =
1935 XNEW (struct collect_memory_action);
1936 ULONGEST basereg;
1937 int is_neg;
1939 maction->base.type = *act;
1940 action = &maction->base;
1942 ++act;
1943 is_neg = (*act == '-');
1944 if (*act == '-')
1945 ++act;
1946 act = unpack_varlen_hex (act, &basereg);
1947 ++act;
1948 act = unpack_varlen_hex (act, &maction->addr);
1949 ++act;
1950 act = unpack_varlen_hex (act, &maction->len);
1951 maction->basereg = (is_neg
1952 ? - (int) basereg
1953 : (int) basereg);
1954 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1955 pulongest (maction->len),
1956 paddress (maction->addr), maction->basereg);
1957 break;
1959 case 'R':
1961 struct collect_registers_action *raction =
1962 XNEW (struct collect_registers_action);
1964 raction->base.type = *act;
1965 action = &raction->base;
1967 trace_debug ("Want to collect registers");
1968 ++act;
1969 /* skip past hex digits of mask for now */
1970 while (isxdigit(*act))
1971 ++act;
1972 break;
1974 case 'L':
1976 struct collect_static_trace_data_action *raction =
1977 XNEW (struct collect_static_trace_data_action);
1979 raction->base.type = *act;
1980 action = &raction->base;
1982 trace_debug ("Want to collect static trace data");
1983 ++act;
1984 break;
1986 case 'S':
1987 trace_debug ("Unexpected step action, ignoring");
1988 ++act;
1989 break;
1990 case 'X':
1992 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1994 xaction->base.type = *act;
1995 action = &xaction->base;
1997 trace_debug ("Want to evaluate expression");
1998 xaction->expr = gdb_parse_agent_expr (&act);
1999 break;
2001 default:
2002 trace_debug ("unknown trace action '%c', ignoring...", *act);
2003 break;
2004 case '-':
2005 break;
2008 if (action == NULL)
2009 break;
2011 if (seen_step_action_flag)
2013 tpoint->num_step_actions++;
2015 tpoint->step_actions
2016 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
2017 tpoint->num_step_actions);
2018 tpoint->step_actions_str
2019 = XRESIZEVEC (char *, tpoint->step_actions_str,
2020 tpoint->num_step_actions);
2021 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
2022 tpoint->step_actions_str[tpoint->num_step_actions - 1]
2023 = savestring (act_start, act - act_start);
2025 else
2027 tpoint->numactions++;
2028 tpoint->actions
2029 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
2030 tpoint->numactions);
2031 tpoint->actions_str
2032 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
2033 tpoint->actions[tpoint->numactions - 1] = action;
2034 tpoint->actions_str[tpoint->numactions - 1]
2035 = savestring (act_start, act - act_start);
2040 #endif
2042 /* Find or create a trace state variable with the given number. */
2044 static struct trace_state_variable *
2045 get_trace_state_variable (int num)
2047 struct trace_state_variable *tsv;
2049 #ifdef IN_PROCESS_AGENT
2050 /* Search for an existing variable. */
2051 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
2052 if (tsv->number == num)
2053 return tsv;
2054 #endif
2056 /* Search for an existing variable. */
2057 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
2058 if (tsv->number == num)
2059 return tsv;
2061 return NULL;
2064 /* Find or create a trace state variable with the given number. */
2066 static struct trace_state_variable *
2067 create_trace_state_variable (int num, int gdb)
2069 struct trace_state_variable *tsv;
2071 tsv = get_trace_state_variable (num);
2072 if (tsv != NULL)
2073 return tsv;
2075 /* Create a new variable. */
2076 tsv = XNEW (struct trace_state_variable);
2077 tsv->number = num;
2078 tsv->initial_value = 0;
2079 tsv->value = 0;
2080 tsv->getter = NULL;
2081 tsv->name = NULL;
2082 #ifdef IN_PROCESS_AGENT
2083 if (!gdb)
2085 tsv->next = alloced_trace_state_variables;
2086 alloced_trace_state_variables = tsv;
2088 else
2089 #endif
2091 tsv->next = trace_state_variables;
2092 trace_state_variables = tsv;
2094 return tsv;
2097 /* This is needed for -Wmissing-declarations. */
2098 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
2100 IP_AGENT_EXPORT_FUNC LONGEST
2101 get_trace_state_variable_value (int num)
2103 struct trace_state_variable *tsv;
2105 tsv = get_trace_state_variable (num);
2107 if (!tsv)
2109 trace_debug ("No trace state variable %d, skipping value get", num);
2110 return 0;
2113 /* Call a getter function if we have one. While it's tempting to
2114 set up something to only call the getter once per tracepoint hit,
2115 it could run afoul of thread races. Better to let the getter
2116 handle it directly, if necessary to worry about it. */
2117 if (tsv->getter)
2118 tsv->value = (tsv->getter) ();
2120 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2121 num, plongest (tsv->value));
2123 return tsv->value;
2126 /* This is needed for -Wmissing-declarations. */
2127 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
2128 LONGEST val);
2130 IP_AGENT_EXPORT_FUNC void
2131 set_trace_state_variable_value (int num, LONGEST val)
2133 struct trace_state_variable *tsv;
2135 tsv = get_trace_state_variable (num);
2137 if (!tsv)
2139 trace_debug ("No trace state variable %d, skipping value set", num);
2140 return;
2143 tsv->value = val;
2146 LONGEST
2147 agent_get_trace_state_variable_value (int num)
2149 return get_trace_state_variable_value (num);
2152 void
2153 agent_set_trace_state_variable_value (int num, LONGEST val)
2155 set_trace_state_variable_value (num, val);
2158 static void
2159 set_trace_state_variable_name (int num, const char *name)
2161 struct trace_state_variable *tsv;
2163 tsv = get_trace_state_variable (num);
2165 if (!tsv)
2167 trace_debug ("No trace state variable %d, skipping name set", num);
2168 return;
2171 tsv->name = (char *) name;
2174 static void
2175 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2177 struct trace_state_variable *tsv;
2179 tsv = get_trace_state_variable (num);
2181 if (!tsv)
2183 trace_debug ("No trace state variable %d, skipping getter set", num);
2184 return;
2187 tsv->getter = getter;
2190 /* Add a raw traceframe for the given tracepoint. */
2192 static struct traceframe *
2193 add_traceframe (struct tracepoint *tpoint)
2195 struct traceframe *tframe;
2197 tframe
2198 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2200 if (tframe == NULL)
2201 return NULL;
2203 tframe->tpnum = tpoint->number;
2204 tframe->data_size = 0;
2206 return tframe;
2209 /* Add a block to the traceframe currently being worked on. */
2211 static unsigned char *
2212 add_traceframe_block (struct traceframe *tframe,
2213 struct tracepoint *tpoint, int amt)
2215 unsigned char *block;
2217 if (!tframe)
2218 return NULL;
2220 block = (unsigned char *) trace_buffer_alloc (amt);
2222 if (!block)
2223 return NULL;
2225 gdb_assert (tframe->tpnum == tpoint->number);
2227 tframe->data_size += amt;
2228 tpoint->traceframe_usage += amt;
2230 return block;
2233 /* Flag that the current traceframe is finished. */
2235 static void
2236 finish_traceframe (struct traceframe *tframe)
2238 ++traceframe_write_count;
2239 ++traceframes_created;
2242 #ifndef IN_PROCESS_AGENT
2244 /* Given a traceframe number NUM, find the NUMth traceframe in the
2245 buffer. */
2247 static struct traceframe *
2248 find_traceframe (int num)
2250 struct traceframe *tframe;
2251 int tfnum = 0;
2253 for (tframe = FIRST_TRACEFRAME ();
2254 tframe->tpnum != 0;
2255 tframe = NEXT_TRACEFRAME (tframe))
2257 if (tfnum == num)
2258 return tframe;
2259 ++tfnum;
2262 return NULL;
2265 static CORE_ADDR
2266 get_traceframe_address (struct traceframe *tframe)
2268 CORE_ADDR addr;
2269 struct tracepoint *tpoint;
2271 addr = traceframe_get_pc (tframe);
2273 if (addr)
2274 return addr;
2276 /* Fallback strategy, will be incorrect for while-stepping frames
2277 and multi-location tracepoints. */
2278 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2279 return tpoint->address;
2282 /* Search for the next traceframe whose address is inside or outside
2283 the given range. */
2285 static struct traceframe *
2286 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2287 int *tfnump)
2289 client_state &cs = get_client_state ();
2290 struct traceframe *tframe;
2291 CORE_ADDR tfaddr;
2293 *tfnump = cs.current_traceframe + 1;
2294 tframe = find_traceframe (*tfnump);
2295 /* The search is not supposed to wrap around. */
2296 if (!tframe)
2298 *tfnump = -1;
2299 return NULL;
2302 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2304 tfaddr = get_traceframe_address (tframe);
2305 if (inside_p
2306 ? (lo <= tfaddr && tfaddr <= hi)
2307 : (lo > tfaddr || tfaddr > hi))
2308 return tframe;
2309 ++*tfnump;
2312 *tfnump = -1;
2313 return NULL;
2316 /* Search for the next traceframe recorded by the given tracepoint.
2317 Note that for multi-location tracepoints, this will find whatever
2318 location appears first. */
2320 static struct traceframe *
2321 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2323 client_state &cs = get_client_state ();
2324 struct traceframe *tframe;
2326 *tfnump = cs.current_traceframe + 1;
2327 tframe = find_traceframe (*tfnump);
2328 /* The search is not supposed to wrap around. */
2329 if (!tframe)
2331 *tfnump = -1;
2332 return NULL;
2335 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2337 if (tframe->tpnum == num)
2338 return tframe;
2339 ++*tfnump;
2342 *tfnump = -1;
2343 return NULL;
2346 #endif
2348 #ifndef IN_PROCESS_AGENT
2350 /* Clear all past trace state. */
2352 static void
2353 cmd_qtinit (char *packet)
2355 client_state &cs = get_client_state ();
2356 struct trace_state_variable *tsv, *prev, *next;
2358 /* Can't do this command without a pid attached. */
2359 if (current_thread == NULL)
2361 write_enn (packet);
2362 return;
2365 /* Make sure we don't try to read from a trace frame. */
2366 cs.current_traceframe = -1;
2368 stop_tracing ();
2370 trace_debug ("Initializing the trace");
2372 clear_installed_tracepoints ();
2373 clear_readonly_regions ();
2375 tracepoints = NULL;
2376 last_tracepoint = NULL;
2378 /* Clear out any leftover trace state variables. Ones with target
2379 defined getters should be kept however. */
2380 prev = NULL;
2381 tsv = trace_state_variables;
2382 while (tsv)
2384 trace_debug ("Looking at var %d", tsv->number);
2385 if (tsv->getter == NULL)
2387 next = tsv->next;
2388 if (prev)
2389 prev->next = next;
2390 else
2391 trace_state_variables = next;
2392 trace_debug ("Deleting var %d", tsv->number);
2393 free (tsv);
2394 tsv = next;
2396 else
2398 prev = tsv;
2399 tsv = tsv->next;
2403 clear_trace_buffer ();
2404 clear_inferior_trace_buffer ();
2406 write_ok (packet);
2409 /* Unprobe the UST marker at ADDRESS. */
2411 static void
2412 unprobe_marker_at (CORE_ADDR address)
2414 char cmd[IPA_CMD_BUF_SIZE];
2416 sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
2417 run_inferior_command (cmd, strlen (cmd) + 1);
2420 /* Restore the program to its pre-tracing state. This routine may be called
2421 in error situations, so it needs to be careful about only restoring
2422 from known-valid bits. */
2424 static void
2425 clear_installed_tracepoints (void)
2427 struct tracepoint *tpoint;
2428 struct tracepoint *prev_stpoint;
2430 target_pause_all (true);
2432 prev_stpoint = NULL;
2434 /* Restore any bytes overwritten by tracepoints. */
2435 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2437 /* Catch the case where we might try to remove a tracepoint that
2438 was never actually installed. */
2439 if (tpoint->handle == NULL)
2441 trace_debug ("Tracepoint %d at 0x%s was "
2442 "never installed, nothing to clear",
2443 tpoint->number, paddress (tpoint->address));
2444 continue;
2447 switch (tpoint->type)
2449 case trap_tracepoint:
2451 struct breakpoint *bp
2452 = (struct breakpoint *) tpoint->handle;
2454 delete_breakpoint (bp);
2456 break;
2457 case fast_tracepoint:
2459 struct fast_tracepoint_jump *jump
2460 = (struct fast_tracepoint_jump *) tpoint->handle;
2462 delete_fast_tracepoint_jump (jump);
2464 break;
2465 case static_tracepoint:
2466 if (prev_stpoint != NULL
2467 && prev_stpoint->address == tpoint->address)
2468 /* Nothing to do. We already unprobed a tracepoint set at
2469 this marker address (and there can only be one probe
2470 per marker). */
2472 else
2474 unprobe_marker_at (tpoint->address);
2475 prev_stpoint = tpoint;
2477 break;
2480 tpoint->handle = NULL;
2483 target_unpause_all (true);
2486 /* Parse a packet that defines a tracepoint. */
2488 static void
2489 cmd_qtdp (char *own_buf)
2491 int tppacket;
2492 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2493 int trail_hyphen = 0;
2494 ULONGEST num;
2495 ULONGEST addr;
2496 ULONGEST count;
2497 struct tracepoint *tpoint;
2498 const char *packet = own_buf;
2500 packet += strlen ("QTDP:");
2502 /* A hyphen at the beginning marks a packet specifying actions for a
2503 tracepoint already supplied. */
2504 tppacket = 1;
2505 if (*packet == '-')
2507 tppacket = 0;
2508 ++packet;
2510 packet = unpack_varlen_hex (packet, &num);
2511 ++packet; /* skip a colon */
2512 packet = unpack_varlen_hex (packet, &addr);
2513 ++packet; /* skip a colon */
2515 /* See if we already have this tracepoint. */
2516 tpoint = find_tracepoint (num, addr);
2518 if (tppacket)
2520 /* Duplicate tracepoints are never allowed. */
2521 if (tpoint)
2523 trace_debug ("Tracepoint error: tracepoint %d"
2524 " at 0x%s already exists",
2525 (int) num, paddress (addr));
2526 write_enn (own_buf);
2527 return;
2530 tpoint = add_tracepoint (num, addr);
2532 tpoint->enabled = (*packet == 'E');
2533 ++packet; /* skip 'E' */
2534 ++packet; /* skip a colon */
2535 packet = unpack_varlen_hex (packet, &count);
2536 tpoint->step_count = count;
2537 ++packet; /* skip a colon */
2538 packet = unpack_varlen_hex (packet, &count);
2539 tpoint->pass_count = count;
2540 /* See if we have any of the additional optional fields. */
2541 while (*packet == ':')
2543 ++packet;
2544 if (*packet == 'F')
2546 tpoint->type = fast_tracepoint;
2547 ++packet;
2548 packet = unpack_varlen_hex (packet, &count);
2549 tpoint->orig_size = count;
2551 else if (*packet == 'S')
2553 tpoint->type = static_tracepoint;
2554 ++packet;
2556 else if (*packet == 'X')
2558 tpoint->cond = gdb_parse_agent_expr (&packet);
2560 else if (*packet == '-')
2561 break;
2562 else if (*packet == '\0')
2563 break;
2564 else
2565 trace_debug ("Unknown optional tracepoint field");
2567 if (*packet == '-')
2569 trail_hyphen = 1;
2570 trace_debug ("Also has actions\n");
2573 trace_debug ("Defined %stracepoint %d at 0x%s, "
2574 "enabled %d step %" PRIu64 " pass %" PRIu64,
2575 tpoint->type == fast_tracepoint ? "fast "
2576 : tpoint->type == static_tracepoint ? "static " : "",
2577 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2578 tpoint->step_count, tpoint->pass_count);
2580 else if (tpoint)
2581 add_tracepoint_action (tpoint, packet);
2582 else
2584 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2585 (int) num, paddress (addr));
2586 write_enn (own_buf);
2587 return;
2590 /* Install tracepoint during tracing only once for each tracepoint location.
2591 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2592 determine the last QTDP packet for one tracepoint location by checking
2593 trailing hyphen in QTDP packet. */
2594 if (tracing && !trail_hyphen)
2596 struct tracepoint *tp = NULL;
2598 /* Pause all threads temporarily while we patch tracepoints. */
2599 target_pause_all (false);
2601 /* download_tracepoint will update global `tracepoints'
2602 list, so it is unsafe to leave threads in jump pad. */
2603 target_stabilize_threads ();
2605 /* Freeze threads. */
2606 target_pause_all (true);
2609 if (tpoint->type != trap_tracepoint)
2611 /* Find another fast or static tracepoint at the same address. */
2612 for (tp = tracepoints; tp; tp = tp->next)
2614 if (tp->address == tpoint->address && tp->type == tpoint->type
2615 && tp->number != tpoint->number)
2616 break;
2619 /* TPOINT is installed at the same address as TP. */
2620 if (tp)
2622 if (tpoint->type == fast_tracepoint)
2623 clone_fast_tracepoint (tpoint, tp);
2624 else if (tpoint->type == static_tracepoint)
2625 tpoint->handle = (void *) -1;
2629 if (use_agent && tpoint->type == fast_tracepoint
2630 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2632 /* Download and install fast tracepoint by agent. */
2633 if (tracepoint_send_agent (tpoint) == 0)
2634 write_ok (own_buf);
2635 else
2637 write_enn (own_buf);
2638 remove_tracepoint (tpoint);
2641 else
2643 download_tracepoint (tpoint);
2645 if (tpoint->type == trap_tracepoint || tp == NULL)
2647 install_tracepoint (tpoint, own_buf);
2648 if (strcmp (own_buf, "OK") != 0)
2649 remove_tracepoint (tpoint);
2651 else
2652 write_ok (own_buf);
2655 target_unpause_all (true);
2656 return;
2659 write_ok (own_buf);
2662 static void
2663 cmd_qtdpsrc (char *own_buf)
2665 ULONGEST num, addr, start, slen;
2666 struct tracepoint *tpoint;
2667 const char *packet = own_buf;
2668 const char *saved;
2669 char *srctype, *src;
2670 size_t nbytes;
2671 struct source_string *last, *newlast;
2673 packet += strlen ("QTDPsrc:");
2675 packet = unpack_varlen_hex (packet, &num);
2676 ++packet; /* skip a colon */
2677 packet = unpack_varlen_hex (packet, &addr);
2678 ++packet; /* skip a colon */
2680 /* See if we already have this tracepoint. */
2681 tpoint = find_tracepoint (num, addr);
2683 if (!tpoint)
2685 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2686 (int) num, paddress (addr));
2687 write_enn (own_buf);
2688 return;
2691 saved = packet;
2692 packet = strchr (packet, ':');
2693 srctype = (char *) xmalloc (packet - saved + 1);
2694 memcpy (srctype, saved, packet - saved);
2695 srctype[packet - saved] = '\0';
2696 ++packet;
2697 packet = unpack_varlen_hex (packet, &start);
2698 ++packet; /* skip a colon */
2699 packet = unpack_varlen_hex (packet, &slen);
2700 ++packet; /* skip a colon */
2701 src = (char *) xmalloc (slen + 1);
2702 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2703 src[nbytes] = '\0';
2705 newlast = XNEW (struct source_string);
2706 newlast->type = srctype;
2707 newlast->str = src;
2708 newlast->next = NULL;
2709 /* Always add a source string to the end of the list;
2710 this keeps sequences of actions/commands in the right
2711 order. */
2712 if (tpoint->source_strings)
2714 for (last = tpoint->source_strings; last->next; last = last->next)
2716 last->next = newlast;
2718 else
2719 tpoint->source_strings = newlast;
2721 write_ok (own_buf);
2724 static void
2725 cmd_qtdv (char *own_buf)
2727 ULONGEST num, val, builtin;
2728 char *varname;
2729 size_t nbytes;
2730 struct trace_state_variable *tsv;
2731 const char *packet = own_buf;
2733 packet += strlen ("QTDV:");
2735 packet = unpack_varlen_hex (packet, &num);
2736 ++packet; /* skip a colon */
2737 packet = unpack_varlen_hex (packet, &val);
2738 ++packet; /* skip a colon */
2739 packet = unpack_varlen_hex (packet, &builtin);
2740 ++packet; /* skip a colon */
2742 nbytes = strlen (packet) / 2;
2743 varname = (char *) xmalloc (nbytes + 1);
2744 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2745 varname[nbytes] = '\0';
2747 tsv = create_trace_state_variable (num, 1);
2748 tsv->initial_value = (LONGEST) val;
2749 tsv->name = varname;
2751 set_trace_state_variable_value (num, (LONGEST) val);
2753 write_ok (own_buf);
2756 static void
2757 cmd_qtenable_disable (char *own_buf, int enable)
2759 const char *packet = own_buf;
2760 ULONGEST num, addr;
2761 struct tracepoint *tp;
2763 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2764 packet = unpack_varlen_hex (packet, &num);
2765 ++packet; /* skip a colon */
2766 packet = unpack_varlen_hex (packet, &addr);
2768 tp = find_tracepoint (num, addr);
2770 if (tp)
2772 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2774 trace_debug ("Tracepoint %d at 0x%s is already %s",
2775 (int) num, paddress (addr),
2776 enable ? "enabled" : "disabled");
2777 write_ok (own_buf);
2778 return;
2781 trace_debug ("%s tracepoint %d at 0x%s",
2782 enable ? "Enabling" : "Disabling",
2783 (int) num, paddress (addr));
2785 tp->enabled = enable;
2787 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
2789 int offset = offsetof (struct tracepoint, enabled);
2790 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2792 int ret = write_inferior_int8 (obj_addr, enable);
2793 if (ret)
2795 trace_debug ("Cannot write enabled flag into "
2796 "inferior process memory");
2797 write_enn (own_buf);
2798 return;
2802 write_ok (own_buf);
2804 else
2806 trace_debug ("Tracepoint %d at 0x%s not found",
2807 (int) num, paddress (addr));
2808 write_enn (own_buf);
2812 static void
2813 cmd_qtv (char *own_buf)
2815 client_state &cs = get_client_state ();
2816 ULONGEST num;
2817 LONGEST val = 0;
2818 int err;
2819 char *packet = own_buf;
2821 packet += strlen ("qTV:");
2822 unpack_varlen_hex (packet, &num);
2824 if (cs.current_traceframe >= 0)
2826 err = traceframe_read_tsv ((int) num, &val);
2827 if (err)
2829 strcpy (own_buf, "U");
2830 return;
2833 /* Only make tsv's be undefined before the first trace run. After a
2834 trace run is over, the user might want to see the last value of
2835 the tsv, and it might not be available in a traceframe. */
2836 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2838 strcpy (own_buf, "U");
2839 return;
2841 else
2842 val = get_trace_state_variable_value (num);
2844 sprintf (own_buf, "V%s", phex_nz (val, 0));
2847 /* Clear out the list of readonly regions. */
2849 static void
2850 clear_readonly_regions (void)
2852 struct readonly_region *roreg;
2854 while (readonly_regions)
2856 roreg = readonly_regions;
2857 readonly_regions = readonly_regions->next;
2858 free (roreg);
2862 /* Parse the collection of address ranges whose contents GDB believes
2863 to be unchanging and so can be read directly from target memory
2864 even while looking at a traceframe. */
2866 static void
2867 cmd_qtro (char *own_buf)
2869 ULONGEST start, end;
2870 struct readonly_region *roreg;
2871 const char *packet = own_buf;
2873 trace_debug ("Want to mark readonly regions");
2875 clear_readonly_regions ();
2877 packet += strlen ("QTro");
2879 while (*packet == ':')
2881 ++packet; /* skip a colon */
2882 packet = unpack_varlen_hex (packet, &start);
2883 ++packet; /* skip a comma */
2884 packet = unpack_varlen_hex (packet, &end);
2886 roreg = XNEW (struct readonly_region);
2887 roreg->start = start;
2888 roreg->end = end;
2889 roreg->next = readonly_regions;
2890 readonly_regions = roreg;
2891 trace_debug ("Added readonly region from 0x%s to 0x%s",
2892 paddress (roreg->start), paddress (roreg->end));
2895 write_ok (own_buf);
2898 /* Test to see if the given range is in our list of readonly ranges.
2899 We only test for being entirely within a range, GDB is not going to
2900 send a single memory packet that spans multiple regions. */
2903 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2905 struct readonly_region *roreg;
2907 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2908 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2909 return 1;
2911 return 0;
2914 static CORE_ADDR gdb_jump_pad_head;
2916 /* Return the address of the next free jump space. */
2918 static CORE_ADDR
2919 get_jump_space_head (void)
2921 if (gdb_jump_pad_head == 0)
2923 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2924 &gdb_jump_pad_head))
2926 internal_error ("error extracting jump_pad_buffer");
2930 return gdb_jump_pad_head;
2933 /* Reserve USED bytes from the jump space. */
2935 static void
2936 claim_jump_space (ULONGEST used)
2938 trace_debug ("claim_jump_space reserves %s bytes at %s",
2939 pulongest (used), paddress (gdb_jump_pad_head));
2940 gdb_jump_pad_head += used;
2943 static CORE_ADDR trampoline_buffer_head = 0;
2944 static CORE_ADDR trampoline_buffer_tail;
2946 /* Reserve USED bytes from the trampoline buffer and return the
2947 address of the start of the reserved space in TRAMPOLINE. Returns
2948 non-zero if the space is successfully claimed. */
2951 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2953 if (!trampoline_buffer_head)
2955 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2956 &trampoline_buffer_tail))
2958 internal_error ("error extracting trampoline_buffer");
2961 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2962 &trampoline_buffer_head))
2964 internal_error ("error extracting trampoline_buffer_end");
2968 /* Start claiming space from the top of the trampoline space. If
2969 the space is located at the bottom of the virtual address space,
2970 this reduces the possibility that corruption will occur if a null
2971 pointer is used to write to memory. */
2972 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2974 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2975 pulongest (used));
2976 return 0;
2979 trampoline_buffer_head -= used;
2981 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2982 pulongest (used), paddress (trampoline_buffer_head));
2984 *trampoline = trampoline_buffer_head;
2985 return 1;
2988 /* Returns non-zero if there is space allocated for use in trampolines
2989 for fast tracepoints. */
2992 have_fast_tracepoint_trampoline_buffer (char *buf)
2994 CORE_ADDR trampoline_end, errbuf;
2996 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2997 &trampoline_end))
2999 internal_error ("error extracting trampoline_buffer_end");
3002 if (buf)
3004 buf[0] = '\0';
3005 strcpy (buf, "was claiming");
3006 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
3007 &errbuf))
3009 internal_error ("error extracting errbuf");
3012 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
3015 return trampoline_end != 0;
3018 /* Ask the IPA to probe the marker at ADDRESS. Returns -1 if running
3019 the command fails, or 0 otherwise. If the command ran
3020 successfully, but probing the marker failed, ERROUT will be filled
3021 with the error to reply to GDB, and -1 is also returned. This
3022 allows directly passing IPA errors to GDB. */
3024 static int
3025 probe_marker_at (CORE_ADDR address, char *errout)
3027 char cmd[IPA_CMD_BUF_SIZE];
3028 int err;
3030 sprintf (cmd, "probe_marker_at:%s", paddress (address));
3031 err = run_inferior_command (cmd, strlen (cmd) + 1);
3033 if (err == 0)
3035 if (*cmd == 'E')
3037 strcpy (errout, cmd);
3038 return -1;
3042 return err;
3045 static void
3046 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
3048 to->jump_pad = from->jump_pad;
3049 to->jump_pad_end = from->jump_pad_end;
3050 to->trampoline = from->trampoline;
3051 to->trampoline_end = from->trampoline_end;
3052 to->adjusted_insn_addr = from->adjusted_insn_addr;
3053 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
3054 to->handle = from->handle;
3056 gdb_assert (from->handle);
3057 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
3060 #define MAX_JUMP_SIZE 20
3062 /* Install fast tracepoint. Return 0 if successful, otherwise return
3063 non-zero. */
3065 static int
3066 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
3068 CORE_ADDR jentry, jump_entry;
3069 CORE_ADDR trampoline;
3070 CORE_ADDR collect;
3071 ULONGEST trampoline_size;
3072 int err = 0;
3073 /* The jump to the jump pad of the last fast tracepoint
3074 installed. */
3075 unsigned char fjump[MAX_JUMP_SIZE];
3076 ULONGEST fjump_size;
3078 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
3080 trace_debug ("Requested a fast tracepoint on an instruction "
3081 "that is of less than the minimum length.");
3082 return 0;
3085 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
3086 &collect))
3088 error ("error extracting gdb_collect_ptr");
3089 return 1;
3092 jentry = jump_entry = get_jump_space_head ();
3094 trampoline = 0;
3095 trampoline_size = 0;
3097 /* Install the jump pad. */
3098 err = target_install_fast_tracepoint_jump_pad
3099 (tpoint->obj_addr_on_target, tpoint->address, collect,
3100 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
3101 &trampoline, &trampoline_size, fjump, &fjump_size,
3102 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
3104 if (err)
3105 return 1;
3107 /* Wire it in. */
3108 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
3109 fjump_size);
3111 if (tpoint->handle != NULL)
3113 tpoint->jump_pad = jump_entry;
3114 tpoint->jump_pad_end = jentry;
3115 tpoint->trampoline = trampoline;
3116 tpoint->trampoline_end = trampoline + trampoline_size;
3118 /* Pad to 8-byte alignment. */
3119 jentry = ((jentry + 7) & ~0x7);
3120 claim_jump_space (jentry - jump_entry);
3123 return 0;
3127 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
3129 static void
3130 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
3132 tpoint->handle = NULL;
3133 *own_buf = '\0';
3135 if (tpoint->type == trap_tracepoint)
3137 /* Tracepoints are installed as memory breakpoints. Just go
3138 ahead and install the trap. The breakpoints module
3139 handles duplicated breakpoints, and the memory read
3140 routine handles un-patching traps from memory reads. */
3141 tpoint->handle = set_breakpoint_at (tpoint->address,
3142 tracepoint_handler);
3144 else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
3146 if (!agent_loaded_p ())
3148 trace_debug ("Requested a %s tracepoint, but fast "
3149 "tracepoints aren't supported.",
3150 tpoint->type == static_tracepoint ? "static" : "fast");
3151 write_e_ipa_not_loaded (own_buf);
3152 return;
3154 if (tpoint->type == static_tracepoint
3155 && !in_process_agent_supports_ust ())
3157 trace_debug ("Requested a static tracepoint, but static "
3158 "tracepoints are not supported.");
3159 write_e_ust_not_loaded (own_buf);
3160 return;
3163 if (tpoint->type == fast_tracepoint)
3164 install_fast_tracepoint (tpoint, own_buf);
3165 else
3167 if (probe_marker_at (tpoint->address, own_buf) == 0)
3168 tpoint->handle = (void *) -1;
3172 else
3173 internal_error ("Unknown tracepoint type");
3175 if (tpoint->handle == NULL)
3177 if (*own_buf == '\0')
3178 write_enn (own_buf);
3180 else
3181 write_ok (own_buf);
3184 static void download_tracepoint_1 (struct tracepoint *tpoint);
3186 static void
3187 cmd_qtstart (char *packet)
3189 struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
3190 CORE_ADDR tpptr = 0, prev_tpptr = 0;
3192 trace_debug ("Starting the trace");
3194 /* Pause all threads temporarily while we patch tracepoints. */
3195 target_pause_all (false);
3197 /* Get threads out of jump pads. Safe to do here, since this is a
3198 top level command. And, required to do here, since we're
3199 deleting/rewriting jump pads. */
3201 target_stabilize_threads ();
3203 /* Freeze threads. */
3204 target_pause_all (true);
3206 /* Sync the fast tracepoints list in the inferior ftlib. */
3207 if (agent_loaded_p ())
3208 download_trace_state_variables ();
3210 /* No previous fast tpoint yet. */
3211 prev_ftpoint = NULL;
3213 /* No previous static tpoint yet. */
3214 prev_stpoint = NULL;
3216 *packet = '\0';
3218 if (agent_loaded_p ())
3220 /* Tell IPA about the correct tdesc. */
3221 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
3222 target_get_ipa_tdesc_idx ()))
3223 error ("Error setting ipa_tdesc_idx variable in lib");
3226 /* Start out empty. */
3227 if (agent_loaded_p ())
3228 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
3230 /* Download and install tracepoints. */
3231 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3233 /* Ensure all the hit counts start at zero. */
3234 tpoint->hit_count = 0;
3235 tpoint->traceframe_usage = 0;
3237 if (tpoint->type == trap_tracepoint)
3239 /* Tracepoints are installed as memory breakpoints. Just go
3240 ahead and install the trap. The breakpoints module
3241 handles duplicated breakpoints, and the memory read
3242 routine handles un-patching traps from memory reads. */
3243 tpoint->handle = set_breakpoint_at (tpoint->address,
3244 tracepoint_handler);
3246 else if (tpoint->type == fast_tracepoint
3247 || tpoint->type == static_tracepoint)
3249 if (maybe_write_ipa_not_loaded (packet))
3251 trace_debug ("Requested a %s tracepoint, but fast "
3252 "tracepoints aren't supported.",
3253 tpoint->type == static_tracepoint
3254 ? "static" : "fast");
3255 break;
3258 if (tpoint->type == fast_tracepoint)
3260 int use_agent_p
3261 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3263 if (prev_ftpoint != NULL
3264 && prev_ftpoint->address == tpoint->address)
3266 if (use_agent_p)
3267 tracepoint_send_agent (tpoint);
3268 else
3269 download_tracepoint_1 (tpoint);
3271 clone_fast_tracepoint (tpoint, prev_ftpoint);
3273 else
3275 /* Tracepoint is installed successfully? */
3276 int installed = 0;
3278 /* Download and install fast tracepoint by agent. */
3279 if (use_agent_p)
3280 installed = !tracepoint_send_agent (tpoint);
3281 else
3283 download_tracepoint_1 (tpoint);
3284 installed = !install_fast_tracepoint (tpoint, packet);
3287 if (installed)
3288 prev_ftpoint = tpoint;
3291 else
3293 if (!in_process_agent_supports_ust ())
3295 trace_debug ("Requested a static tracepoint, but static "
3296 "tracepoints are not supported.");
3297 break;
3300 download_tracepoint_1 (tpoint);
3301 /* Can only probe a given marker once. */
3302 if (prev_stpoint != NULL
3303 && prev_stpoint->address == tpoint->address)
3304 tpoint->handle = (void *) -1;
3305 else
3307 if (probe_marker_at (tpoint->address, packet) == 0)
3309 tpoint->handle = (void *) -1;
3311 /* So that we can handle multiple static tracepoints
3312 at the same address easily. */
3313 prev_stpoint = tpoint;
3318 prev_tpptr = tpptr;
3319 tpptr = tpoint->obj_addr_on_target;
3321 if (tpoint == tracepoints)
3322 /* First object in list, set the head pointer in the
3323 inferior. */
3324 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3325 else
3326 write_inferior_data_pointer (prev_tpptr
3327 + offsetof (struct tracepoint, next),
3328 tpptr);
3331 /* Any failure in the inner loop is sufficient cause to give
3332 up. */
3333 if (tpoint->handle == NULL)
3334 break;
3337 /* Any error in tracepoint insertion is unacceptable; better to
3338 address the problem now, than end up with a useless or misleading
3339 trace run. */
3340 if (tpoint != NULL)
3342 clear_installed_tracepoints ();
3343 if (*packet == '\0')
3344 write_enn (packet);
3345 target_unpause_all (true);
3346 return;
3349 stopping_tracepoint = NULL;
3350 trace_buffer_is_full = 0;
3351 expr_eval_result = expr_eval_no_error;
3352 error_tracepoint = NULL;
3353 tracing_start_time = get_timestamp ();
3355 /* Tracing is now active, hits will now start being logged. */
3356 tracing = 1;
3358 if (agent_loaded_p ())
3360 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3362 internal_error ("Error setting tracing variable in lib");
3365 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3368 internal_error ("Error clearing stopping_tracepoint variable"
3369 " in lib");
3372 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3374 internal_error ("Error clearing trace_buffer_is_full variable"
3375 " in lib");
3378 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3379 stop_tracing_handler);
3380 if (stop_tracing_bkpt == NULL)
3381 error ("Error setting stop_tracing breakpoint");
3383 flush_trace_buffer_bkpt
3384 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3385 flush_trace_buffer_handler);
3386 if (flush_trace_buffer_bkpt == NULL)
3387 error ("Error setting flush_trace_buffer breakpoint");
3390 target_unpause_all (true);
3392 write_ok (packet);
3395 /* End a tracing run, filling in a stop reason to report back to GDB,
3396 and removing the tracepoints from the code. */
3398 void
3399 stop_tracing (void)
3401 if (!tracing)
3403 trace_debug ("Tracing is already off, ignoring");
3404 return;
3407 trace_debug ("Stopping the trace");
3409 /* Pause all threads before removing fast jumps from memory,
3410 breakpoints, and touching IPA state variables (inferior memory).
3411 Some thread may hit the internal tracing breakpoints, or be
3412 collecting this moment, but that's ok, we don't release the
3413 tpoint object's memory or the jump pads here (we only do that
3414 when we're sure we can move all threads out of the jump pads).
3415 We can't now, since we may be getting here due to the inferior
3416 agent calling us. */
3417 target_pause_all (true);
3419 /* Stop logging. Tracepoints can still be hit, but they will not be
3420 recorded. */
3421 tracing = 0;
3422 if (agent_loaded_p ())
3424 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3426 internal_error ("Error clearing tracing variable in lib");
3430 tracing_stop_time = get_timestamp ();
3431 tracing_stop_reason = "t???";
3432 tracing_stop_tpnum = 0;
3433 if (stopping_tracepoint)
3435 trace_debug ("Stopping the trace because "
3436 "tracepoint %d was hit %" PRIu64 " times",
3437 stopping_tracepoint->number,
3438 stopping_tracepoint->pass_count);
3439 tracing_stop_reason = "tpasscount";
3440 tracing_stop_tpnum = stopping_tracepoint->number;
3442 else if (trace_buffer_is_full)
3444 trace_debug ("Stopping the trace because the trace buffer is full");
3445 tracing_stop_reason = "tfull";
3447 else if (expr_eval_result != expr_eval_no_error)
3449 trace_debug ("Stopping the trace because of an expression eval error");
3450 tracing_stop_reason = eval_result_names[expr_eval_result];
3451 tracing_stop_tpnum = error_tracepoint->number;
3453 #ifndef IN_PROCESS_AGENT
3454 else if (!gdb_connected ())
3456 trace_debug ("Stopping the trace because GDB disconnected");
3457 tracing_stop_reason = "tdisconnected";
3459 #endif
3460 else
3462 trace_debug ("Stopping the trace because of a tstop command");
3463 tracing_stop_reason = "tstop";
3466 stopping_tracepoint = NULL;
3467 error_tracepoint = NULL;
3469 /* Clear out the tracepoints. */
3470 clear_installed_tracepoints ();
3472 if (agent_loaded_p ())
3474 /* Pull in fast tracepoint trace frames from the inferior lib
3475 buffer into our buffer, even if our buffer is already full,
3476 because we want to present the full number of created frames
3477 in addition to what fit in the trace buffer. */
3478 upload_fast_traceframes ();
3481 if (stop_tracing_bkpt != NULL)
3483 delete_breakpoint (stop_tracing_bkpt);
3484 stop_tracing_bkpt = NULL;
3487 if (flush_trace_buffer_bkpt != NULL)
3489 delete_breakpoint (flush_trace_buffer_bkpt);
3490 flush_trace_buffer_bkpt = NULL;
3493 target_unpause_all (true);
3496 static int
3497 stop_tracing_handler (CORE_ADDR addr)
3499 trace_debug ("lib hit stop_tracing");
3501 /* Don't actually handle it here. When we stop tracing we remove
3502 breakpoints from the inferior, and that is not allowed in a
3503 breakpoint handler (as the caller is walking the breakpoint
3504 list). */
3505 return 0;
3508 static int
3509 flush_trace_buffer_handler (CORE_ADDR addr)
3511 trace_debug ("lib hit flush_trace_buffer");
3512 return 0;
3515 static void
3516 cmd_qtstop (char *packet)
3518 stop_tracing ();
3519 write_ok (packet);
3522 static void
3523 cmd_qtdisconnected (char *own_buf)
3525 ULONGEST setting;
3526 char *packet = own_buf;
3528 packet += strlen ("QTDisconnected:");
3530 unpack_varlen_hex (packet, &setting);
3532 write_ok (own_buf);
3534 disconnected_tracing = setting;
3537 static void
3538 cmd_qtframe (char *own_buf)
3540 client_state &cs = get_client_state ();
3541 ULONGEST frame, pc, lo, hi, num;
3542 int tfnum, tpnum;
3543 struct traceframe *tframe;
3544 const char *packet = own_buf;
3546 packet += strlen ("QTFrame:");
3548 if (startswith (packet, "pc:"))
3550 packet += strlen ("pc:");
3551 unpack_varlen_hex (packet, &pc);
3552 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3553 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3555 else if (startswith (packet, "range:"))
3557 packet += strlen ("range:");
3558 packet = unpack_varlen_hex (packet, &lo);
3559 ++packet;
3560 unpack_varlen_hex (packet, &hi);
3561 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3562 paddress (lo), paddress (hi));
3563 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3565 else if (startswith (packet, "outside:"))
3567 packet += strlen ("outside:");
3568 packet = unpack_varlen_hex (packet, &lo);
3569 ++packet;
3570 unpack_varlen_hex (packet, &hi);
3571 trace_debug ("Want to find next traceframe "
3572 "outside the range 0x%s to 0x%s",
3573 paddress (lo), paddress (hi));
3574 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3576 else if (startswith (packet, "tdp:"))
3578 packet += strlen ("tdp:");
3579 unpack_varlen_hex (packet, &num);
3580 tpnum = (int) num;
3581 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3582 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3584 else
3586 unpack_varlen_hex (packet, &frame);
3587 tfnum = (int) frame;
3588 if (tfnum == -1)
3590 trace_debug ("Want to stop looking at traceframes");
3591 cs.current_traceframe = -1;
3592 write_ok (own_buf);
3593 return;
3595 trace_debug ("Want to look at traceframe %d", tfnum);
3596 tframe = find_traceframe (tfnum);
3599 if (tframe)
3601 cs.current_traceframe = tfnum;
3602 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3604 else
3605 sprintf (own_buf, "F-1");
3608 static void
3609 cmd_qtstatus (char *packet)
3611 char *stop_reason_rsp = NULL;
3612 char *buf1, *buf2, *buf3;
3613 const char *str;
3614 int slen;
3616 /* Translate the plain text of the notes back into hex for
3617 transmission. */
3619 str = (tracing_user_name ? tracing_user_name : "");
3620 slen = strlen (str);
3621 buf1 = (char *) alloca (slen * 2 + 1);
3622 bin2hex ((gdb_byte *) str, buf1, slen);
3624 str = (tracing_notes ? tracing_notes : "");
3625 slen = strlen (str);
3626 buf2 = (char *) alloca (slen * 2 + 1);
3627 bin2hex ((gdb_byte *) str, buf2, slen);
3629 str = (tracing_stop_note ? tracing_stop_note : "");
3630 slen = strlen (str);
3631 buf3 = (char *) alloca (slen * 2 + 1);
3632 bin2hex ((gdb_byte *) str, buf3, slen);
3634 trace_debug ("Returning trace status as %d, stop reason %s",
3635 tracing, tracing_stop_reason);
3637 if (agent_loaded_p ())
3639 target_pause_all (true);
3641 upload_fast_traceframes ();
3643 target_unpause_all (true);
3646 stop_reason_rsp = (char *) tracing_stop_reason;
3648 /* The user visible error string in terror needs to be hex encoded.
3649 We leave it as plain string in `tracing_stop_reason' to ease
3650 debugging. */
3651 if (startswith (stop_reason_rsp, "terror:"))
3653 const char *result_name;
3654 int hexstr_len;
3655 char *p;
3657 result_name = stop_reason_rsp + strlen ("terror:");
3658 hexstr_len = strlen (result_name) * 2;
3659 p = stop_reason_rsp
3660 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3661 strcpy (p, "terror:");
3662 p += strlen (p);
3663 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3666 /* If this was a forced stop, include any stop note that was supplied. */
3667 if (strcmp (stop_reason_rsp, "tstop") == 0)
3669 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3670 strcpy (stop_reason_rsp, "tstop:");
3671 strcat (stop_reason_rsp, buf3);
3674 sprintf (packet,
3675 "T%d;"
3676 "%s:%x;"
3677 "tframes:%x;tcreated:%x;"
3678 "tfree:%x;tsize:%s;"
3679 "circular:%d;"
3680 "disconn:%d;"
3681 "starttime:%s;stoptime:%s;"
3682 "username:%s;notes:%s:",
3683 tracing ? 1 : 0,
3684 stop_reason_rsp, tracing_stop_tpnum,
3685 traceframe_count, traceframes_created,
3686 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3687 circular_trace_buffer,
3688 disconnected_tracing,
3689 phex_nz (tracing_start_time, sizeof (tracing_start_time)),
3690 phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
3691 buf1, buf2);
3694 static void
3695 cmd_qtp (char *own_buf)
3697 ULONGEST num, addr;
3698 struct tracepoint *tpoint;
3699 const char *packet = own_buf;
3701 packet += strlen ("qTP:");
3703 packet = unpack_varlen_hex (packet, &num);
3704 ++packet; /* skip a colon */
3705 packet = unpack_varlen_hex (packet, &addr);
3707 /* See if we already have this tracepoint. */
3708 tpoint = find_tracepoint (num, addr);
3710 if (!tpoint)
3712 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3713 (int) num, paddress (addr));
3714 write_enn (own_buf);
3715 return;
3718 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3719 tpoint->traceframe_usage);
3722 /* State variables to help return all the tracepoint bits. */
3723 static struct tracepoint *cur_tpoint;
3724 static unsigned int cur_action;
3725 static unsigned int cur_step_action;
3726 static struct source_string *cur_source_string;
3727 static struct trace_state_variable *cur_tsv;
3729 /* Compose a response that is an imitation of the syntax by which the
3730 tracepoint was originally downloaded. */
3732 static void
3733 response_tracepoint (char *packet, struct tracepoint *tpoint)
3735 char *buf;
3737 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3738 paddress (tpoint->address),
3739 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3740 tpoint->pass_count);
3741 if (tpoint->type == fast_tracepoint)
3742 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3743 else if (tpoint->type == static_tracepoint)
3744 sprintf (packet + strlen (packet), ":S");
3746 if (tpoint->cond)
3748 buf = gdb_unparse_agent_expr (tpoint->cond);
3749 sprintf (packet + strlen (packet), ":X%x,%s",
3750 tpoint->cond->length, buf);
3751 free (buf);
3755 /* Compose a response that is an imitation of the syntax by which the
3756 tracepoint action was originally downloaded (with the difference
3757 that due to the way we store the actions, this will output a packet
3758 per action, while GDB could have combined more than one action
3759 per-packet. */
3761 static void
3762 response_action (char *packet, struct tracepoint *tpoint,
3763 char *taction, int step)
3765 sprintf (packet, "%c%x:%s:%s",
3766 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3767 taction);
3770 /* Compose a response that is an imitation of the syntax by which the
3771 tracepoint source piece was originally downloaded. */
3773 static void
3774 response_source (char *packet,
3775 struct tracepoint *tpoint, struct source_string *src)
3777 char *buf;
3778 int len;
3780 len = strlen (src->str);
3781 buf = (char *) alloca (len * 2 + 1);
3782 bin2hex ((gdb_byte *) src->str, buf, len);
3784 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3785 tpoint->number, paddress (tpoint->address),
3786 src->type, 0, len, buf);
3789 /* Return the first piece of tracepoint definition, and initialize the
3790 state machine that will iterate through all the tracepoint
3791 bits. */
3793 static void
3794 cmd_qtfp (char *packet)
3796 trace_debug ("Returning first tracepoint definition piece");
3798 cur_tpoint = tracepoints;
3799 cur_action = cur_step_action = 0;
3800 cur_source_string = NULL;
3802 if (cur_tpoint)
3803 response_tracepoint (packet, cur_tpoint);
3804 else
3805 strcpy (packet, "l");
3808 /* Return additional pieces of tracepoint definition. Each action and
3809 stepping action must go into its own packet, because of packet size
3810 limits, and so we use state variables to deliver one piece at a
3811 time. */
3813 static void
3814 cmd_qtsp (char *packet)
3816 trace_debug ("Returning subsequent tracepoint definition piece");
3818 if (!cur_tpoint)
3820 /* This case would normally never occur, but be prepared for
3821 GDB misbehavior. */
3822 strcpy (packet, "l");
3824 else if (cur_action < cur_tpoint->numactions)
3826 response_action (packet, cur_tpoint,
3827 cur_tpoint->actions_str[cur_action], 0);
3828 ++cur_action;
3830 else if (cur_step_action < cur_tpoint->num_step_actions)
3832 response_action (packet, cur_tpoint,
3833 cur_tpoint->step_actions_str[cur_step_action], 1);
3834 ++cur_step_action;
3836 else if ((cur_source_string
3837 ? cur_source_string->next
3838 : cur_tpoint->source_strings))
3840 if (cur_source_string)
3841 cur_source_string = cur_source_string->next;
3842 else
3843 cur_source_string = cur_tpoint->source_strings;
3844 response_source (packet, cur_tpoint, cur_source_string);
3846 else
3848 cur_tpoint = cur_tpoint->next;
3849 cur_action = cur_step_action = 0;
3850 cur_source_string = NULL;
3851 if (cur_tpoint)
3852 response_tracepoint (packet, cur_tpoint);
3853 else
3854 strcpy (packet, "l");
3858 /* Compose a response that is an imitation of the syntax by which the
3859 trace state variable was originally downloaded. */
3861 static void
3862 response_tsv (char *packet, struct trace_state_variable *tsv)
3864 char *buf = (char *) "";
3865 int namelen;
3867 if (tsv->name)
3869 namelen = strlen (tsv->name);
3870 buf = (char *) alloca (namelen * 2 + 1);
3871 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3874 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3875 tsv->getter ? 1 : 0, buf);
3878 /* Return the first trace state variable definition, and initialize
3879 the state machine that will iterate through all the tsv bits. */
3881 static void
3882 cmd_qtfv (char *packet)
3884 trace_debug ("Returning first trace state variable definition");
3886 cur_tsv = trace_state_variables;
3888 if (cur_tsv)
3889 response_tsv (packet, cur_tsv);
3890 else
3891 strcpy (packet, "l");
3894 /* Return additional trace state variable definitions. */
3896 static void
3897 cmd_qtsv (char *packet)
3899 trace_debug ("Returning additional trace state variable definition");
3901 if (cur_tsv)
3903 cur_tsv = cur_tsv->next;
3904 if (cur_tsv)
3905 response_tsv (packet, cur_tsv);
3906 else
3907 strcpy (packet, "l");
3909 else
3910 strcpy (packet, "l");
3913 /* Return the first static tracepoint marker, and initialize the state
3914 machine that will iterate through all the static tracepoints
3915 markers. */
3917 static void
3918 cmd_qtfstm (char *packet)
3920 if (!maybe_write_ipa_ust_not_loaded (packet))
3921 run_inferior_command (packet, strlen (packet) + 1);
3924 /* Return additional static tracepoints markers. */
3926 static void
3927 cmd_qtsstm (char *packet)
3929 if (!maybe_write_ipa_ust_not_loaded (packet))
3930 run_inferior_command (packet, strlen (packet) + 1);
3933 /* Return the definition of the static tracepoint at a given address.
3934 Result packet is the same as qTsST's. */
3936 static void
3937 cmd_qtstmat (char *packet)
3939 if (!maybe_write_ipa_ust_not_loaded (packet))
3940 run_inferior_command (packet, strlen (packet) + 1);
3943 /* Sent the agent a command to close it. */
3945 void
3946 gdb_agent_about_to_close (int pid)
3948 char buf[IPA_CMD_BUF_SIZE];
3950 if (!maybe_write_ipa_not_loaded (buf))
3952 scoped_restore_current_thread restore_thread;
3954 /* Find any thread which belongs to process PID. */
3955 switch_to_thread (find_any_thread_of_pid (pid));
3957 strcpy (buf, "close");
3959 run_inferior_command (buf, strlen (buf) + 1);
3963 /* Return the minimum instruction size needed for fast tracepoints as a
3964 hexadecimal number. */
3966 static void
3967 cmd_qtminftpilen (char *packet)
3969 if (current_thread == NULL)
3971 /* Indicate that the minimum length is currently unknown. */
3972 strcpy (packet, "0");
3973 return;
3976 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3979 /* Respond to qTBuffer packet with a block of raw data from the trace
3980 buffer. GDB may ask for a lot, but we are allowed to reply with
3981 only as much as will fit within packet limits or whatever. */
3983 static void
3984 cmd_qtbuffer (char *own_buf)
3986 ULONGEST offset, num, tot;
3987 unsigned char *tbp;
3988 const char *packet = own_buf;
3990 packet += strlen ("qTBuffer:");
3992 packet = unpack_varlen_hex (packet, &offset);
3993 ++packet; /* skip a comma */
3994 unpack_varlen_hex (packet, &num);
3996 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3997 (int) num, phex_nz (offset, 0));
3999 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
4001 /* If we're right at the end, reply specially that we're done. */
4002 if (offset == tot)
4004 strcpy (own_buf, "l");
4005 return;
4008 /* Object to any other out-of-bounds request. */
4009 if (offset > tot)
4011 write_enn (own_buf);
4012 return;
4015 /* Compute the pointer corresponding to the given offset, accounting
4016 for wraparound. */
4017 tbp = trace_buffer_start + offset;
4018 if (tbp >= trace_buffer_wrap)
4019 tbp -= (trace_buffer_wrap - trace_buffer_lo);
4021 /* Trim to the remaining bytes if we're close to the end. */
4022 if (num > tot - offset)
4023 num = tot - offset;
4025 /* Trim to available packet size. */
4026 if (num >= (PBUFSIZ - 16) / 2 )
4027 num = (PBUFSIZ - 16) / 2;
4029 bin2hex (tbp, own_buf, num);
4032 static void
4033 cmd_bigqtbuffer_circular (char *own_buf)
4035 ULONGEST val;
4036 char *packet = own_buf;
4038 packet += strlen ("QTBuffer:circular:");
4040 unpack_varlen_hex (packet, &val);
4041 circular_trace_buffer = val;
4042 trace_debug ("Trace buffer is now %s",
4043 circular_trace_buffer ? "circular" : "linear");
4044 write_ok (own_buf);
4047 static void
4048 cmd_bigqtbuffer_size (char *own_buf)
4050 ULONGEST val;
4051 LONGEST sval;
4052 char *packet = own_buf;
4054 /* Can't change the size during a tracing run. */
4055 if (tracing)
4057 write_enn (own_buf);
4058 return;
4061 packet += strlen ("QTBuffer:size:");
4063 /* -1 is sent as literal "-1". */
4064 if (strcmp (packet, "-1") == 0)
4065 sval = DEFAULT_TRACE_BUFFER_SIZE;
4066 else
4068 unpack_varlen_hex (packet, &val);
4069 sval = (LONGEST) val;
4072 init_trace_buffer (sval);
4073 trace_debug ("Trace buffer is now %s bytes",
4074 plongest (trace_buffer_size));
4075 write_ok (own_buf);
4078 static void
4079 cmd_qtnotes (char *own_buf)
4081 size_t nbytes;
4082 char *saved, *user, *notes, *stopnote;
4083 char *packet = own_buf;
4085 packet += strlen ("QTNotes:");
4087 while (*packet)
4089 if (startswith (packet, "user:"))
4091 packet += strlen ("user:");
4092 saved = packet;
4093 packet = strchr (packet, ';');
4094 nbytes = (packet - saved) / 2;
4095 user = (char *) xmalloc (nbytes + 1);
4096 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
4097 user[nbytes] = '\0';
4098 ++packet; /* skip the semicolon */
4099 trace_debug ("User is '%s'", user);
4100 xfree (tracing_user_name);
4101 tracing_user_name = user;
4103 else if (startswith (packet, "notes:"))
4105 packet += strlen ("notes:");
4106 saved = packet;
4107 packet = strchr (packet, ';');
4108 nbytes = (packet - saved) / 2;
4109 notes = (char *) xmalloc (nbytes + 1);
4110 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
4111 notes[nbytes] = '\0';
4112 ++packet; /* skip the semicolon */
4113 trace_debug ("Notes is '%s'", notes);
4114 xfree (tracing_notes);
4115 tracing_notes = notes;
4117 else if (startswith (packet, "tstop:"))
4119 packet += strlen ("tstop:");
4120 saved = packet;
4121 packet = strchr (packet, ';');
4122 nbytes = (packet - saved) / 2;
4123 stopnote = (char *) xmalloc (nbytes + 1);
4124 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
4125 stopnote[nbytes] = '\0';
4126 ++packet; /* skip the semicolon */
4127 trace_debug ("tstop note is '%s'", stopnote);
4128 xfree (tracing_stop_note);
4129 tracing_stop_note = stopnote;
4131 else
4132 break;
4135 write_ok (own_buf);
4139 handle_tracepoint_general_set (char *packet)
4141 if (strcmp ("QTinit", packet) == 0)
4143 cmd_qtinit (packet);
4144 return 1;
4146 else if (startswith (packet, "QTDP:"))
4148 cmd_qtdp (packet);
4149 return 1;
4151 else if (startswith (packet, "QTDPsrc:"))
4153 cmd_qtdpsrc (packet);
4154 return 1;
4156 else if (startswith (packet, "QTEnable:"))
4158 cmd_qtenable_disable (packet, 1);
4159 return 1;
4161 else if (startswith (packet, "QTDisable:"))
4163 cmd_qtenable_disable (packet, 0);
4164 return 1;
4166 else if (startswith (packet, "QTDV:"))
4168 cmd_qtdv (packet);
4169 return 1;
4171 else if (startswith (packet, "QTro:"))
4173 cmd_qtro (packet);
4174 return 1;
4176 else if (strcmp ("QTStart", packet) == 0)
4178 cmd_qtstart (packet);
4179 return 1;
4181 else if (strcmp ("QTStop", packet) == 0)
4183 cmd_qtstop (packet);
4184 return 1;
4186 else if (startswith (packet, "QTDisconnected:"))
4188 cmd_qtdisconnected (packet);
4189 return 1;
4191 else if (startswith (packet, "QTFrame:"))
4193 cmd_qtframe (packet);
4194 return 1;
4196 else if (startswith (packet, "QTBuffer:circular:"))
4198 cmd_bigqtbuffer_circular (packet);
4199 return 1;
4201 else if (startswith (packet, "QTBuffer:size:"))
4203 cmd_bigqtbuffer_size (packet);
4204 return 1;
4206 else if (startswith (packet, "QTNotes:"))
4208 cmd_qtnotes (packet);
4209 return 1;
4212 return 0;
4216 handle_tracepoint_query (char *packet)
4218 if (strcmp ("qTStatus", packet) == 0)
4220 cmd_qtstatus (packet);
4221 return 1;
4223 else if (startswith (packet, "qTP:"))
4225 cmd_qtp (packet);
4226 return 1;
4228 else if (strcmp ("qTfP", packet) == 0)
4230 cmd_qtfp (packet);
4231 return 1;
4233 else if (strcmp ("qTsP", packet) == 0)
4235 cmd_qtsp (packet);
4236 return 1;
4238 else if (strcmp ("qTfV", packet) == 0)
4240 cmd_qtfv (packet);
4241 return 1;
4243 else if (strcmp ("qTsV", packet) == 0)
4245 cmd_qtsv (packet);
4246 return 1;
4248 else if (startswith (packet, "qTV:"))
4250 cmd_qtv (packet);
4251 return 1;
4253 else if (startswith (packet, "qTBuffer:"))
4255 cmd_qtbuffer (packet);
4256 return 1;
4258 else if (strcmp ("qTfSTM", packet) == 0)
4260 cmd_qtfstm (packet);
4261 return 1;
4263 else if (strcmp ("qTsSTM", packet) == 0)
4265 cmd_qtsstm (packet);
4266 return 1;
4268 else if (startswith (packet, "qTSTMat:"))
4270 cmd_qtstmat (packet);
4271 return 1;
4273 else if (strcmp ("qTMinFTPILen", packet) == 0)
4275 cmd_qtminftpilen (packet);
4276 return 1;
4279 return 0;
4282 #endif
4283 #ifndef IN_PROCESS_AGENT
4285 /* Call this when thread TINFO has hit the tracepoint defined by
4286 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
4287 action. This adds a while-stepping collecting state item to the
4288 threads' collecting state list, so that we can keep track of
4289 multiple simultaneous while-stepping actions being collected by the
4290 same thread. This can happen in cases like:
4292 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
4293 ff0002 INSN2
4294 ff0003 INSN3 <-- TP2, collect $regs
4295 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
4296 ff0005 INSN5
4298 Notice that when instruction INSN5 is reached, the while-stepping
4299 actions of both TP1 and TP3 are still being collected, and that TP2
4300 had been collected meanwhile. The whole range of ff0001-ff0005
4301 should be single-stepped, due to at least TP1's while-stepping
4302 action covering the whole range. */
4304 static void
4305 add_while_stepping_state (struct thread_info *tinfo,
4306 int tp_number, CORE_ADDR tp_address)
4308 struct wstep_state *wstep = XNEW (struct wstep_state);
4310 wstep->next = tinfo->while_stepping;
4312 wstep->tp_number = tp_number;
4313 wstep->tp_address = tp_address;
4314 wstep->current_step = 0;
4316 tinfo->while_stepping = wstep;
4319 /* Release the while-stepping collecting state WSTEP. */
4321 static void
4322 release_while_stepping_state (struct wstep_state *wstep)
4324 free (wstep);
4327 /* Release all while-stepping collecting states currently associated
4328 with thread TINFO. */
4330 void
4331 release_while_stepping_state_list (struct thread_info *tinfo)
4333 struct wstep_state *head;
4335 while (tinfo->while_stepping)
4337 head = tinfo->while_stepping;
4338 tinfo->while_stepping = head->next;
4339 release_while_stepping_state (head);
4343 /* If TINFO was handling a 'while-stepping' action, the step has
4344 finished, so collect any step data needed, and check if any more
4345 steps are required. Return true if the thread was indeed
4346 collecting tracepoint data, false otherwise. */
4349 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
4351 struct tracepoint *tpoint;
4352 struct wstep_state *wstep;
4353 struct wstep_state **wstep_link;
4354 struct trap_tracepoint_ctx ctx;
4356 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4357 our buffer. */
4358 if (agent_loaded_p ())
4359 upload_fast_traceframes ();
4361 /* Check if we were indeed collecting data for one of more
4362 tracepoints with a 'while-stepping' count. */
4363 if (tinfo->while_stepping == NULL)
4364 return 0;
4366 if (!tracing)
4368 /* We're not even tracing anymore. Stop this thread from
4369 collecting. */
4370 release_while_stepping_state_list (tinfo);
4372 /* The thread had stopped due to a single-step request indeed
4373 explained by a tracepoint. */
4374 return 1;
4377 wstep = tinfo->while_stepping;
4378 wstep_link = &tinfo->while_stepping;
4380 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4381 target_pid_to_str (tinfo->id).c_str (),
4382 wstep->tp_number, paddress (wstep->tp_address));
4384 ctx.base.type = trap_tracepoint;
4385 ctx.regcache = get_thread_regcache (tinfo, 1);
4387 while (wstep != NULL)
4389 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4390 if (tpoint == NULL)
4392 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4393 wstep->tp_number, paddress (wstep->tp_address),
4394 target_pid_to_str (tinfo->id).c_str ());
4396 /* Unlink. */
4397 *wstep_link = wstep->next;
4398 release_while_stepping_state (wstep);
4399 wstep = *wstep_link;
4400 continue;
4403 /* We've just finished one step. */
4404 ++wstep->current_step;
4406 /* Collect data. */
4407 collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
4408 stop_pc, tpoint, wstep->current_step);
4410 if (wstep->current_step >= tpoint->step_count)
4412 /* The requested numbers of steps have occurred. */
4413 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4414 target_pid_to_str (tinfo->id).c_str (),
4415 wstep->tp_number, paddress (wstep->tp_address));
4417 /* Unlink the wstep. */
4418 *wstep_link = wstep->next;
4419 release_while_stepping_state (wstep);
4420 wstep = *wstep_link;
4422 /* Only check the hit count now, which ensure that we do all
4423 our stepping before stopping the run. */
4424 if (tpoint->pass_count > 0
4425 && tpoint->hit_count >= tpoint->pass_count
4426 && stopping_tracepoint == NULL)
4427 stopping_tracepoint = tpoint;
4429 else
4431 /* Keep single-stepping until the requested numbers of steps
4432 have occurred. */
4433 wstep_link = &wstep->next;
4434 wstep = *wstep_link;
4437 if (stopping_tracepoint
4438 || trace_buffer_is_full
4439 || expr_eval_result != expr_eval_no_error)
4441 stop_tracing ();
4442 break;
4446 return 1;
4449 /* Handle any internal tracing control breakpoint hits. That means,
4450 pull traceframes from the IPA to our buffer, and syncing both
4451 tracing agents when the IPA's tracing stops for some reason. */
4454 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
4456 /* Pull in fast tracepoint trace frames from the inferior in-process
4457 agent's buffer into our buffer. */
4459 if (!agent_loaded_p ())
4460 return 0;
4462 upload_fast_traceframes ();
4464 /* Check if the in-process agent had decided we should stop
4465 tracing. */
4466 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4468 int ipa_trace_buffer_is_full;
4469 CORE_ADDR ipa_stopping_tracepoint;
4470 int ipa_expr_eval_result;
4471 CORE_ADDR ipa_error_tracepoint;
4473 trace_debug ("lib stopped at stop_tracing");
4475 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4476 &ipa_trace_buffer_is_full);
4478 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4479 &ipa_stopping_tracepoint);
4480 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4482 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4483 &ipa_error_tracepoint);
4484 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4486 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4487 &ipa_expr_eval_result);
4488 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4490 trace_debug ("lib: trace_buffer_is_full: %d, "
4491 "stopping_tracepoint: %s, "
4492 "ipa_expr_eval_result: %d, "
4493 "error_tracepoint: %s, ",
4494 ipa_trace_buffer_is_full,
4495 paddress (ipa_stopping_tracepoint),
4496 ipa_expr_eval_result,
4497 paddress (ipa_error_tracepoint));
4499 if (ipa_trace_buffer_is_full)
4500 trace_debug ("lib stopped due to full buffer.");
4502 if (ipa_stopping_tracepoint)
4503 trace_debug ("lib stopped due to tpoint");
4505 if (ipa_error_tracepoint)
4506 trace_debug ("lib stopped due to error");
4508 if (ipa_stopping_tracepoint != 0)
4510 stopping_tracepoint
4511 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4513 else if (ipa_expr_eval_result != expr_eval_no_error)
4515 expr_eval_result = ipa_expr_eval_result;
4516 error_tracepoint
4517 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4519 stop_tracing ();
4520 return 1;
4522 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4524 trace_debug ("lib stopped at flush_trace_buffer");
4525 return 1;
4528 return 0;
4531 /* Return true if TINFO just hit a tracepoint. Collect data if
4532 so. */
4535 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
4537 struct tracepoint *tpoint;
4538 int ret = 0;
4539 struct trap_tracepoint_ctx ctx;
4541 /* Not tracing, don't handle. */
4542 if (!tracing)
4543 return 0;
4545 ctx.base.type = trap_tracepoint;
4546 ctx.regcache = get_thread_regcache (tinfo, 1);
4548 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4550 /* Note that we collect fast tracepoints here as well. We'll
4551 step over the fast tracepoint jump later, which avoids the
4552 double collect. However, we don't collect for static
4553 tracepoints here, because UST markers are compiled in program,
4554 and probes will be executed in program. So static tracepoints
4555 are collected there. */
4556 if (tpoint->enabled && stop_pc == tpoint->address
4557 && tpoint->type != static_tracepoint)
4559 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4560 target_pid_to_str (tinfo->id).c_str (),
4561 tpoint->number, paddress (tpoint->address));
4563 /* Test the condition if present, and collect if true. */
4564 if (!tpoint->cond
4565 || (condition_true_at_tracepoint
4566 ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
4567 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4568 stop_pc, tpoint);
4570 if (stopping_tracepoint
4571 || trace_buffer_is_full
4572 || expr_eval_result != expr_eval_no_error)
4574 stop_tracing ();
4576 /* If the tracepoint had a 'while-stepping' action, then set
4577 the thread to collect this tracepoint on the following
4578 single-steps. */
4579 else if (tpoint->step_count > 0)
4581 add_while_stepping_state (tinfo,
4582 tpoint->number, tpoint->address);
4585 ret = 1;
4589 return ret;
4592 #endif
4594 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4595 struct ust_marker_data;
4596 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4597 struct traceframe *tframe);
4598 #endif
4600 /* Create a trace frame for the hit of the given tracepoint in the
4601 given thread. */
4603 static void
4604 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4605 struct tracepoint *tpoint)
4607 struct traceframe *tframe;
4608 int acti;
4610 /* Only count it as a hit when we actually collect data. */
4611 tpoint->hit_count++;
4613 /* If we've exceeded a defined pass count, record the event for
4614 later, and finish the collection for this hit. This test is only
4615 for nonstepping tracepoints, stepping tracepoints test at the end
4616 of their while-stepping loop. */
4617 if (tpoint->pass_count > 0
4618 && tpoint->hit_count >= tpoint->pass_count
4619 && tpoint->step_count == 0
4620 && stopping_tracepoint == NULL)
4621 stopping_tracepoint = tpoint;
4623 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4624 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4626 tframe = add_traceframe (tpoint);
4628 if (tframe)
4630 for (acti = 0; acti < tpoint->numactions; ++acti)
4632 #ifndef IN_PROCESS_AGENT
4633 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4634 tpoint->number, paddress (tpoint->address),
4635 tpoint->actions_str[acti]);
4636 #endif
4638 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4639 tpoint->actions[acti]);
4642 finish_traceframe (tframe);
4645 if (tframe == NULL && tracing)
4646 trace_buffer_is_full = 1;
4649 #ifndef IN_PROCESS_AGENT
4651 static void
4652 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4653 CORE_ADDR stop_pc,
4654 struct tracepoint *tpoint, int current_step)
4656 struct traceframe *tframe;
4657 int acti;
4659 trace_debug ("Making new step traceframe for "
4660 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4661 tpoint->number, paddress (tpoint->address),
4662 current_step, tpoint->step_count,
4663 tpoint->hit_count);
4665 tframe = add_traceframe (tpoint);
4667 if (tframe)
4669 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4671 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4672 tpoint->number, paddress (tpoint->address),
4673 tpoint->step_actions_str[acti]);
4675 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4676 tpoint->step_actions[acti]);
4679 finish_traceframe (tframe);
4682 if (tframe == NULL && tracing)
4683 trace_buffer_is_full = 1;
4686 #endif
4688 #ifdef IN_PROCESS_AGENT
4689 /* The target description index for IPA. Passed from gdbserver, used
4690 to select ipa_tdesc. */
4691 EXTERN_C_PUSH
4692 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
4693 EXTERN_C_POP
4694 #endif
4696 static struct regcache *
4697 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4699 struct regcache *regcache = NULL;
4700 #ifdef IN_PROCESS_AGENT
4701 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
4703 if (ctx->type == fast_tracepoint)
4705 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4706 if (!fctx->regcache_initted)
4708 fctx->regcache_initted = 1;
4709 init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
4710 supply_regblock (&fctx->regcache, NULL);
4711 supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4713 regcache = &fctx->regcache;
4715 #ifdef HAVE_UST
4716 if (ctx->type == static_tracepoint)
4718 struct static_tracepoint_ctx *sctx
4719 = (struct static_tracepoint_ctx *) ctx;
4721 if (!sctx->regcache_initted)
4723 sctx->regcache_initted = 1;
4724 init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
4725 supply_regblock (&sctx->regcache, NULL);
4726 /* Pass down the tracepoint address, because REGS doesn't
4727 include the PC, but we know what it must have been. */
4728 supply_static_tracepoint_registers (&sctx->regcache,
4729 (const unsigned char *)
4730 sctx->regs,
4731 sctx->tpoint->address);
4733 regcache = &sctx->regcache;
4735 #endif
4736 #else
4737 if (ctx->type == trap_tracepoint)
4739 struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4740 regcache = tctx->regcache;
4742 #endif
4744 gdb_assert (regcache != NULL);
4746 return regcache;
4749 static void
4750 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4751 CORE_ADDR stop_pc,
4752 struct tracepoint *tpoint,
4753 struct traceframe *tframe,
4754 struct tracepoint_action *taction)
4756 enum eval_result_type err;
4758 switch (taction->type)
4760 case 'M':
4762 struct collect_memory_action *maction;
4763 struct eval_agent_expr_context ax_ctx;
4765 maction = (struct collect_memory_action *) taction;
4766 ax_ctx.regcache = NULL;
4767 ax_ctx.tframe = tframe;
4768 ax_ctx.tpoint = tpoint;
4770 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4771 pulongest (maction->len),
4772 paddress (maction->addr), maction->basereg);
4773 /* (should use basereg) */
4774 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4775 maction->len);
4776 break;
4778 case 'R':
4780 unsigned char *regspace;
4781 struct regcache tregcache;
4782 struct regcache *context_regcache;
4783 int regcache_size;
4785 trace_debug ("Want to collect registers");
4787 context_regcache = get_context_regcache (ctx);
4788 regcache_size = register_cache_size (context_regcache->tdesc);
4790 /* Collect all registers for now. */
4791 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4792 if (regspace == NULL)
4794 trace_debug ("Trace buffer block allocation failed, skipping");
4795 break;
4797 /* Identify a register block. */
4798 *regspace = 'R';
4800 /* Wrap the regblock in a register cache (in the stack, we
4801 don't want to malloc here). */
4802 init_register_cache (&tregcache, context_regcache->tdesc,
4803 regspace + 1);
4805 /* Copy the register data to the regblock. */
4806 regcache_cpy (&tregcache, context_regcache);
4808 #ifndef IN_PROCESS_AGENT
4809 /* On some platforms, trap-based tracepoints will have the PC
4810 pointing to the next instruction after the trap, but we
4811 don't want the user or GDB trying to guess whether the
4812 saved PC needs adjusting; so always record the adjusted
4813 stop_pc. Note that we can't use tpoint->address instead,
4814 since it will be wrong for while-stepping actions. This
4815 adjustment is a nop for fast tracepoints collected from the
4816 in-process lib (but not if GDBserver is collecting one
4817 preemptively), since the PC had already been adjusted to
4818 contain the tracepoint's address by the jump pad. */
4819 trace_debug ("Storing stop pc (0x%s) in regblock",
4820 paddress (stop_pc));
4822 /* This changes the regblock, not the thread's
4823 regcache. */
4824 regcache_write_pc (&tregcache, stop_pc);
4825 #endif
4827 break;
4828 case 'X':
4830 struct eval_expr_action *eaction;
4831 struct eval_agent_expr_context ax_ctx;
4833 eaction = (struct eval_expr_action *) taction;
4834 ax_ctx.regcache = get_context_regcache (ctx);
4835 ax_ctx.tframe = tframe;
4836 ax_ctx.tpoint = tpoint;
4838 trace_debug ("Want to evaluate expression");
4840 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4842 if (err != expr_eval_no_error)
4844 record_tracepoint_error (tpoint, "action expression", err);
4845 return;
4848 break;
4849 case 'L':
4851 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4852 trace_debug ("Want to collect static trace data");
4853 collect_ust_data_at_tracepoint (ctx, tframe);
4854 #else
4855 trace_debug ("warning: collecting static trace data, "
4856 "but static tracepoints are not supported");
4857 #endif
4859 break;
4860 default:
4861 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4862 break;
4866 static int
4867 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4868 struct tracepoint *tpoint)
4870 ULONGEST value = 0;
4871 enum eval_result_type err;
4873 /* Presently, gdbserver doesn't run compiled conditions, only the
4874 IPA does. If the program stops at a fast tracepoint's address
4875 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4876 gdbserver preemptively collect the fast tracepoint. Later, on
4877 resume, gdbserver steps over the fast tracepoint like it steps
4878 over breakpoints, so that the IPA doesn't see that fast
4879 tracepoint. This avoids double collects of fast tracepoints in
4880 that stopping scenario. Having gdbserver itself handle the fast
4881 tracepoint gives the user a consistent view of when fast or trap
4882 tracepoints are collected, compared to an alternative where only
4883 trap tracepoints are collected on stop, and fast tracepoints on
4884 resume. When a fast tracepoint is being processed by gdbserver,
4885 it is always the non-compiled condition expression that is
4886 used. */
4887 #ifdef IN_PROCESS_AGENT
4888 if (tpoint->compiled_cond)
4890 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4891 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4893 else
4894 #endif
4896 struct eval_agent_expr_context ax_ctx;
4898 ax_ctx.regcache = get_context_regcache (ctx);
4899 ax_ctx.tframe = NULL;
4900 ax_ctx.tpoint = tpoint;
4902 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4904 if (err != expr_eval_no_error)
4906 record_tracepoint_error (tpoint, "condition", err);
4907 /* The error case must return false. */
4908 return 0;
4911 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4912 tpoint->number, paddress (tpoint->address),
4913 pulongest (value));
4914 return (value ? 1 : 0);
4917 /* Do memory copies for bytecodes. */
4918 /* Do the recording of memory blocks for actions and bytecodes. */
4921 agent_mem_read (struct eval_agent_expr_context *ctx,
4922 unsigned char *to, CORE_ADDR from, ULONGEST len)
4924 unsigned char *mspace;
4925 ULONGEST remaining = len;
4926 unsigned short blocklen;
4928 /* If a 'to' buffer is specified, use it. */
4929 if (to != NULL)
4931 read_inferior_memory (from, to, len);
4932 return 0;
4935 /* Otherwise, create a new memory block in the trace buffer. */
4936 while (remaining > 0)
4938 size_t sp;
4940 blocklen = (remaining > 65535 ? 65535 : remaining);
4941 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4942 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4943 if (mspace == NULL)
4944 return 1;
4945 /* Identify block as a memory block. */
4946 *mspace = 'M';
4947 ++mspace;
4948 /* Record address and size. */
4949 memcpy (mspace, &from, sizeof (from));
4950 mspace += sizeof (from);
4951 memcpy (mspace, &blocklen, sizeof (blocklen));
4952 mspace += sizeof (blocklen);
4953 /* Record the memory block proper. */
4954 read_inferior_memory (from, mspace, blocklen);
4955 trace_debug ("%d bytes recorded", blocklen);
4956 remaining -= blocklen;
4957 from += blocklen;
4959 return 0;
4963 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4964 unsigned char *to, CORE_ADDR from, ULONGEST len)
4966 unsigned char *buf, *mspace;
4967 ULONGEST remaining = len;
4968 unsigned short blocklen, i;
4970 /* To save a bit of space, block lengths are 16-bit, so break large
4971 requests into multiple blocks. Bordering on overkill for strings,
4972 but it could happen that someone specifies a large max length. */
4973 while (remaining > 0)
4975 size_t sp;
4977 blocklen = (remaining > 65535 ? 65535 : remaining);
4978 /* We want working space to accumulate nonzero bytes, since
4979 traceframes must have a predecided size (otherwise it gets
4980 harder to wrap correctly for the circular case, etc). */
4981 buf = (unsigned char *) xmalloc (blocklen + 1);
4982 for (i = 0; i < blocklen; ++i)
4984 /* Read the string one byte at a time, in case the string is
4985 at the end of a valid memory area - we don't want a
4986 correctly-terminated string to engender segvio
4987 complaints. */
4988 read_inferior_memory (from + i, buf + i, 1);
4990 if (buf[i] == '\0')
4992 blocklen = i + 1;
4993 /* Make sure outer loop stops now too. */
4994 remaining = blocklen;
4995 break;
4998 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4999 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
5000 if (mspace == NULL)
5002 xfree (buf);
5003 return 1;
5005 /* Identify block as a memory block. */
5006 *mspace = 'M';
5007 ++mspace;
5008 /* Record address and size. */
5009 memcpy ((void *) mspace, (void *) &from, sizeof (from));
5010 mspace += sizeof (from);
5011 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
5012 mspace += sizeof (blocklen);
5013 /* Copy the string contents. */
5014 memcpy ((void *) mspace, (void *) buf, blocklen);
5015 remaining -= blocklen;
5016 from += blocklen;
5017 xfree (buf);
5019 return 0;
5022 /* Record the value of a trace state variable. */
5025 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
5027 unsigned char *vspace;
5028 LONGEST val;
5030 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
5031 1 + sizeof (n) + sizeof (LONGEST));
5032 if (vspace == NULL)
5033 return 1;
5034 /* Identify block as a variable. */
5035 *vspace = 'V';
5036 /* Record variable's number and value. */
5037 memcpy (vspace + 1, &n, sizeof (n));
5038 val = get_trace_state_variable_value (n);
5039 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
5040 trace_debug ("Variable %d recorded", n);
5041 return 0;
5044 #ifndef IN_PROCESS_AGENT
5046 /* Callback for traceframe_walk_blocks, used to find a given block
5047 type in a traceframe. */
5049 static int
5050 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
5052 char *wantedp = (char *) data;
5054 if (*wantedp == blocktype)
5055 return 1;
5057 return 0;
5060 /* Walk over all traceframe blocks of the traceframe buffer starting
5061 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
5062 block found, passing in DATA unmodified. If CALLBACK returns true,
5063 this returns a pointer to where the block is found. Returns NULL
5064 if no callback call returned true, indicating that all blocks have
5065 been walked. */
5067 static unsigned char *
5068 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
5069 int tfnum,
5070 int (*callback) (char blocktype,
5071 unsigned char *dataptr,
5072 void *data),
5073 void *data)
5075 unsigned char *dataptr;
5077 if (datasize == 0)
5079 trace_debug ("traceframe %d has no data", tfnum);
5080 return NULL;
5083 /* Iterate through a traceframe's blocks, looking for a block of the
5084 requested type. */
5085 for (dataptr = database;
5086 dataptr < database + datasize;
5087 /* nothing */)
5089 char blocktype;
5090 unsigned short mlen;
5092 if (dataptr == trace_buffer_wrap)
5094 /* Adjust to reflect wrapping part of the frame around to
5095 the beginning. */
5096 datasize = dataptr - database;
5097 dataptr = database = trace_buffer_lo;
5100 blocktype = *dataptr++;
5102 if ((*callback) (blocktype, dataptr, data))
5103 return dataptr;
5105 switch (blocktype)
5107 case 'R':
5108 /* Skip over the registers block. */
5109 dataptr += current_target_desc ()->registers_size;
5110 break;
5111 case 'M':
5112 /* Skip over the memory block. */
5113 dataptr += sizeof (CORE_ADDR);
5114 memcpy (&mlen, dataptr, sizeof (mlen));
5115 dataptr += (sizeof (mlen) + mlen);
5116 break;
5117 case 'V':
5118 /* Skip over the TSV block. */
5119 dataptr += (sizeof (int) + sizeof (LONGEST));
5120 break;
5121 case 'S':
5122 /* Skip over the static trace data block. */
5123 memcpy (&mlen, dataptr, sizeof (mlen));
5124 dataptr += (sizeof (mlen) + mlen);
5125 break;
5126 default:
5127 trace_debug ("traceframe %d has unknown block type 0x%x",
5128 tfnum, blocktype);
5129 return NULL;
5133 return NULL;
5136 /* Look for the block of type TYPE_WANTED in the traceframe starting
5137 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
5138 number. */
5140 static unsigned char *
5141 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
5142 int tfnum, char type_wanted)
5144 return traceframe_walk_blocks (database, datasize, tfnum,
5145 match_blocktype, &type_wanted);
5148 static unsigned char *
5149 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
5151 unsigned char *regblock;
5153 regblock = traceframe_find_block_type (tframe->data,
5154 tframe->data_size,
5155 tfnum, 'R');
5157 if (regblock == NULL)
5158 trace_debug ("traceframe %d has no register data", tfnum);
5160 return regblock;
5163 /* Get registers from a traceframe. */
5166 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
5168 unsigned char *dataptr;
5169 struct tracepoint *tpoint;
5170 struct traceframe *tframe;
5172 tframe = find_traceframe (tfnum);
5174 if (tframe == NULL)
5176 trace_debug ("traceframe %d not found", tfnum);
5177 return 1;
5180 dataptr = traceframe_find_regblock (tframe, tfnum);
5181 if (dataptr == NULL)
5183 /* Mark registers unavailable. */
5184 supply_regblock (regcache, NULL);
5186 /* We can generally guess at a PC, although this will be
5187 misleading for while-stepping frames and multi-location
5188 tracepoints. */
5189 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
5190 if (tpoint != NULL)
5191 regcache_write_pc (regcache, tpoint->address);
5193 else
5194 supply_regblock (regcache, dataptr);
5196 return 0;
5199 static CORE_ADDR
5200 traceframe_get_pc (struct traceframe *tframe)
5202 struct regcache regcache;
5203 unsigned char *dataptr;
5204 const struct target_desc *tdesc = current_target_desc ();
5206 dataptr = traceframe_find_regblock (tframe, -1);
5207 if (dataptr == NULL)
5208 return 0;
5210 init_register_cache (&regcache, tdesc, dataptr);
5211 return regcache_read_pc (&regcache);
5214 /* Read a requested block of memory from a trace frame. */
5217 traceframe_read_mem (int tfnum, CORE_ADDR addr,
5218 unsigned char *buf, ULONGEST length,
5219 ULONGEST *nbytes)
5221 struct traceframe *tframe;
5222 unsigned char *database, *dataptr;
5223 unsigned int datasize;
5224 CORE_ADDR maddr;
5225 unsigned short mlen;
5227 trace_debug ("traceframe_read_mem");
5229 tframe = find_traceframe (tfnum);
5231 if (!tframe)
5233 trace_debug ("traceframe %d not found", tfnum);
5234 return 1;
5237 datasize = tframe->data_size;
5238 database = dataptr = &tframe->data[0];
5240 /* Iterate through a traceframe's blocks, looking for memory. */
5241 while ((dataptr = traceframe_find_block_type (dataptr,
5242 datasize
5243 - (dataptr - database),
5244 tfnum, 'M')) != NULL)
5246 memcpy (&maddr, dataptr, sizeof (maddr));
5247 dataptr += sizeof (maddr);
5248 memcpy (&mlen, dataptr, sizeof (mlen));
5249 dataptr += sizeof (mlen);
5250 trace_debug ("traceframe %d has %d bytes at %s",
5251 tfnum, mlen, paddress (maddr));
5253 /* If the block includes the first part of the desired range,
5254 return as much it has; GDB will re-request the remainder,
5255 which might be in a different block of this trace frame. */
5256 if (maddr <= addr && addr < (maddr + mlen))
5258 ULONGEST amt = (maddr + mlen) - addr;
5259 if (amt > length)
5260 amt = length;
5262 memcpy (buf, dataptr + (addr - maddr), amt);
5263 *nbytes = amt;
5264 return 0;
5267 /* Skip over this block. */
5268 dataptr += mlen;
5271 trace_debug ("traceframe %d has no memory data for the desired region",
5272 tfnum);
5274 *nbytes = 0;
5275 return 0;
5278 static int
5279 traceframe_read_tsv (int tsvnum, LONGEST *val)
5281 client_state &cs = get_client_state ();
5282 int tfnum;
5283 struct traceframe *tframe;
5284 unsigned char *database, *dataptr;
5285 unsigned int datasize;
5286 int vnum;
5287 int found = 0;
5289 trace_debug ("traceframe_read_tsv");
5291 tfnum = cs.current_traceframe;
5293 if (tfnum < 0)
5295 trace_debug ("no current traceframe");
5296 return 1;
5299 tframe = find_traceframe (tfnum);
5301 if (tframe == NULL)
5303 trace_debug ("traceframe %d not found", tfnum);
5304 return 1;
5307 datasize = tframe->data_size;
5308 database = dataptr = &tframe->data[0];
5310 /* Iterate through a traceframe's blocks, looking for the last
5311 matched tsv. */
5312 while ((dataptr = traceframe_find_block_type (dataptr,
5313 datasize
5314 - (dataptr - database),
5315 tfnum, 'V')) != NULL)
5317 memcpy (&vnum, dataptr, sizeof (vnum));
5318 dataptr += sizeof (vnum);
5320 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
5322 /* Check that this is the variable we want. */
5323 if (tsvnum == vnum)
5325 memcpy (val, dataptr, sizeof (*val));
5326 found = 1;
5329 /* Skip over this block. */
5330 dataptr += sizeof (LONGEST);
5333 if (!found)
5334 trace_debug ("traceframe %d has no data for variable %d",
5335 tfnum, tsvnum);
5336 return !found;
5339 /* Read a requested block of static tracepoint data from a trace
5340 frame. */
5343 traceframe_read_sdata (int tfnum, ULONGEST offset,
5344 unsigned char *buf, ULONGEST length,
5345 ULONGEST *nbytes)
5347 struct traceframe *tframe;
5348 unsigned char *database, *dataptr;
5349 unsigned int datasize;
5350 unsigned short mlen;
5352 trace_debug ("traceframe_read_sdata");
5354 tframe = find_traceframe (tfnum);
5356 if (!tframe)
5358 trace_debug ("traceframe %d not found", tfnum);
5359 return 1;
5362 datasize = tframe->data_size;
5363 database = &tframe->data[0];
5365 /* Iterate through a traceframe's blocks, looking for static
5366 tracepoint data. */
5367 dataptr = traceframe_find_block_type (database, datasize,
5368 tfnum, 'S');
5369 if (dataptr != NULL)
5371 memcpy (&mlen, dataptr, sizeof (mlen));
5372 dataptr += sizeof (mlen);
5373 if (offset < mlen)
5375 if (offset + length > mlen)
5376 length = mlen - offset;
5378 memcpy (buf, dataptr, length);
5379 *nbytes = length;
5381 else
5382 *nbytes = 0;
5383 return 0;
5386 trace_debug ("traceframe %d has no static trace data", tfnum);
5388 *nbytes = 0;
5389 return 0;
5392 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
5393 object. DATA is pointer to a struct buffer holding the
5394 traceframe-info object being built. */
5396 static int
5397 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
5399 struct buffer *buffer = (struct buffer *) data;
5401 switch (blocktype)
5403 case 'M':
5405 unsigned short mlen;
5406 CORE_ADDR maddr;
5408 memcpy (&maddr, dataptr, sizeof (maddr));
5409 dataptr += sizeof (maddr);
5410 memcpy (&mlen, dataptr, sizeof (mlen));
5411 dataptr += sizeof (mlen);
5412 buffer_xml_printf (buffer,
5413 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
5414 paddress (maddr), phex_nz (mlen, sizeof (mlen)));
5415 break;
5417 case 'V':
5419 int vnum;
5421 memcpy (&vnum, dataptr, sizeof (vnum));
5422 buffer_xml_printf (buffer, "<tvar id=\"%d\"/>\n", vnum);
5423 break;
5425 case 'R':
5426 case 'S':
5428 break;
5430 default:
5431 warning ("Unhandled trace block type (%d) '%c ' "
5432 "while building trace frame info.",
5433 blocktype, blocktype);
5434 break;
5437 return 0;
5440 /* Build a traceframe-info object for traceframe number TFNUM into
5441 BUFFER. */
5444 traceframe_read_info (int tfnum, struct buffer *buffer)
5446 struct traceframe *tframe;
5448 trace_debug ("traceframe_read_info");
5450 tframe = find_traceframe (tfnum);
5452 if (!tframe)
5454 trace_debug ("traceframe %d not found", tfnum);
5455 return 1;
5458 buffer_grow_str (buffer, "<traceframe-info>\n");
5459 traceframe_walk_blocks (tframe->data, tframe->data_size,
5460 tfnum, build_traceframe_info_xml, buffer);
5461 buffer_grow_str0 (buffer, "</traceframe-info>\n");
5462 return 0;
5465 /* Return the first fast tracepoint whose jump pad contains PC. */
5467 static struct tracepoint *
5468 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5470 struct tracepoint *tpoint;
5472 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5473 if (tpoint->type == fast_tracepoint)
5474 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5475 return tpoint;
5477 return NULL;
5480 /* Return the first fast tracepoint whose trampoline contains PC. */
5482 static struct tracepoint *
5483 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5485 struct tracepoint *tpoint;
5487 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5489 if (tpoint->type == fast_tracepoint
5490 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5491 return tpoint;
5494 return NULL;
5497 /* Return GDBserver's tracepoint that matches the IP Agent's
5498 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5499 address space. */
5501 static struct tracepoint *
5502 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5504 struct tracepoint *tpoint;
5506 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5507 if (tpoint->type == fast_tracepoint)
5508 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5509 return tpoint;
5511 return NULL;
5514 #endif
5516 /* The type of the object that is used to synchronize fast tracepoint
5517 collection. */
5519 typedef struct collecting_t
5521 /* The fast tracepoint number currently collecting. */
5522 uintptr_t tpoint;
5524 /* A number that GDBserver can use to identify the thread that is
5525 presently holding the collect lock. This need not (and usually
5526 is not) the thread id, as getting the current thread ID usually
5527 requires a system call, which we want to avoid like the plague.
5528 Usually this is thread's TCB, found in the TLS (pseudo-)
5529 register, which is readable with a single insn on several
5530 architectures. */
5531 uintptr_t thread_area;
5532 } collecting_t;
5534 #ifndef IN_PROCESS_AGENT
5536 void
5537 force_unlock_trace_buffer (void)
5539 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5542 /* Check if the thread identified by THREAD_AREA which is stopped at
5543 STOP_PC, is presently locking the fast tracepoint collection, and
5544 if so, gather some status of said collection. Returns 0 if the
5545 thread isn't collecting or in the jump pad at all. 1, if in the
5546 jump pad (or within gdb_collect) and hasn't executed the adjusted
5547 original insn yet (can set a breakpoint there and run to it). 2,
5548 if presently executing the adjusted original insn --- in which
5549 case, if we want to move the thread out of the jump pad, we need to
5550 single-step it until this function returns 0. */
5552 fast_tpoint_collect_result
5553 fast_tracepoint_collecting (CORE_ADDR thread_area,
5554 CORE_ADDR stop_pc,
5555 struct fast_tpoint_collect_status *status)
5557 CORE_ADDR ipa_collecting;
5558 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5559 CORE_ADDR ipa_gdb_trampoline_buffer;
5560 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5561 struct tracepoint *tpoint;
5562 int needs_breakpoint;
5564 /* The thread THREAD_AREA is either:
5566 0. not collecting at all, not within the jump pad, or within
5567 gdb_collect or one of its callees.
5569 1. in the jump pad and haven't reached gdb_collect
5571 2. within gdb_collect (out of the jump pad) (collect is set)
5573 3. we're in the jump pad, after gdb_collect having returned,
5574 possibly executing the adjusted insns.
5576 For cases 1 and 3, `collecting' may or not be set. The jump pad
5577 doesn't have any complicated jump logic, so we can tell if the
5578 thread is executing the adjust original insn or not by just
5579 matching STOP_PC with known jump pad addresses. If we it isn't
5580 yet executing the original insn, set a breakpoint there, and let
5581 the thread run to it, so to quickly step over a possible (many
5582 insns) gdb_collect call. Otherwise, or when the breakpoint is
5583 hit, only a few (small number of) insns are left to be executed
5584 in the jump pad. Single-step the thread until it leaves the
5585 jump pad. */
5587 again:
5588 tpoint = NULL;
5589 needs_breakpoint = 0;
5590 trace_debug ("fast_tracepoint_collecting");
5592 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5593 &ipa_gdb_jump_pad_buffer))
5595 internal_error ("error extracting `gdb_jump_pad_buffer'");
5597 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5598 &ipa_gdb_jump_pad_buffer_end))
5600 internal_error ("error extracting `gdb_jump_pad_buffer_end'");
5603 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5604 &ipa_gdb_trampoline_buffer))
5606 internal_error ("error extracting `gdb_trampoline_buffer'");
5608 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5609 &ipa_gdb_trampoline_buffer_end))
5611 internal_error ("error extracting `gdb_trampoline_buffer_end'");
5614 if (ipa_gdb_jump_pad_buffer <= stop_pc
5615 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5617 /* We can tell which tracepoint(s) the thread is collecting by
5618 matching the jump pad address back to the tracepoint. */
5619 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5620 if (tpoint == NULL)
5622 warning ("in jump pad, but no matching tpoint?");
5623 return fast_tpoint_collect_result::not_collecting;
5625 else
5627 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5628 "adj_insn(%s, %s)",
5629 tpoint->number, paddress (tpoint->address),
5630 paddress (tpoint->jump_pad),
5631 paddress (tpoint->jump_pad_end),
5632 paddress (tpoint->adjusted_insn_addr),
5633 paddress (tpoint->adjusted_insn_addr_end));
5636 /* Definitely in the jump pad. May or may not need
5637 fast-exit-jump-pad breakpoint. */
5638 if (tpoint->jump_pad <= stop_pc
5639 && stop_pc < tpoint->adjusted_insn_addr)
5640 needs_breakpoint = 1;
5642 else if (ipa_gdb_trampoline_buffer <= stop_pc
5643 && stop_pc < ipa_gdb_trampoline_buffer_end)
5645 /* We can tell which tracepoint(s) the thread is collecting by
5646 matching the trampoline address back to the tracepoint. */
5647 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5648 if (tpoint == NULL)
5650 warning ("in trampoline, but no matching tpoint?");
5651 return fast_tpoint_collect_result::not_collecting;
5653 else
5655 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5656 tpoint->number, paddress (tpoint->address),
5657 paddress (tpoint->trampoline),
5658 paddress (tpoint->trampoline_end));
5661 /* Have not reached jump pad yet, but treat the trampoline as a
5662 part of the jump pad that is before the adjusted original
5663 instruction. */
5664 needs_breakpoint = 1;
5666 else
5668 collecting_t ipa_collecting_obj;
5670 /* If `collecting' is set/locked, then the THREAD_AREA thread
5671 may or not be the one holding the lock. We have to read the
5672 lock to find out. */
5674 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5675 &ipa_collecting))
5677 trace_debug ("fast_tracepoint_collecting:"
5678 " failed reading 'collecting' in the inferior");
5679 return fast_tpoint_collect_result::not_collecting;
5682 if (!ipa_collecting)
5684 trace_debug ("fast_tracepoint_collecting: not collecting"
5685 " (and nobody is).");
5686 return fast_tpoint_collect_result::not_collecting;
5689 /* Some thread is collecting. Check which. */
5690 if (read_inferior_memory (ipa_collecting,
5691 (unsigned char *) &ipa_collecting_obj,
5692 sizeof (ipa_collecting_obj)) != 0)
5693 goto again;
5695 if (ipa_collecting_obj.thread_area != thread_area)
5697 trace_debug ("fast_tracepoint_collecting: not collecting "
5698 "(another thread is)");
5699 return fast_tpoint_collect_result::not_collecting;
5702 tpoint
5703 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5704 if (tpoint == NULL)
5706 warning ("fast_tracepoint_collecting: collecting, "
5707 "but tpoint %s not found?",
5708 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5709 return fast_tpoint_collect_result::not_collecting;
5712 /* The thread is within `gdb_collect', skip over the rest of
5713 fast tracepoint collection quickly using a breakpoint. */
5714 needs_breakpoint = 1;
5717 /* The caller wants a bit of status detail. */
5718 if (status != NULL)
5720 status->tpoint_num = tpoint->number;
5721 status->tpoint_addr = tpoint->address;
5722 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5723 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5726 if (needs_breakpoint)
5728 /* Hasn't executed the original instruction yet. Set breakpoint
5729 there, and wait till it's hit, then single-step until exiting
5730 the jump pad. */
5732 trace_debug ("\
5733 fast_tracepoint_collecting, returning continue-until-break at %s",
5734 paddress (tpoint->adjusted_insn_addr));
5736 return fast_tpoint_collect_result::before_insn; /* continue */
5738 else
5740 /* Just single-step until exiting the jump pad. */
5742 trace_debug ("fast_tracepoint_collecting, returning "
5743 "need-single-step (%s-%s)",
5744 paddress (tpoint->adjusted_insn_addr),
5745 paddress (tpoint->adjusted_insn_addr_end));
5747 return fast_tpoint_collect_result::at_insn; /* single-step */
5751 #endif
5753 #ifdef IN_PROCESS_AGENT
5755 /* The global fast tracepoint collect lock. Points to a collecting_t
5756 object built on the stack by the jump pad, if presently locked;
5757 NULL if it isn't locked. Note that this lock *must* be set while
5758 executing any *function other than the jump pad. See
5759 fast_tracepoint_collecting. */
5760 EXTERN_C_PUSH
5761 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5762 EXTERN_C_POP
5764 /* This is needed for -Wmissing-declarations. */
5765 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5766 unsigned char *regs);
5768 /* This routine, called from the jump pad (in asm) is designed to be
5769 called from the jump pads of fast tracepoints, thus it is on the
5770 critical path. */
5772 IP_AGENT_EXPORT_FUNC void
5773 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5775 struct fast_tracepoint_ctx ctx;
5776 const struct target_desc *ipa_tdesc;
5778 /* Don't do anything until the trace run is completely set up. */
5779 if (!tracing)
5780 return;
5782 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5783 ctx.base.type = fast_tracepoint;
5784 ctx.regs = regs;
5785 ctx.regcache_initted = 0;
5786 /* Wrap the regblock in a register cache (in the stack, we don't
5787 want to malloc here). */
5788 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5789 if (ctx.regspace == NULL)
5791 trace_debug ("Trace buffer block allocation failed, skipping");
5792 return;
5795 for (ctx.tpoint = tpoint;
5796 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5797 ctx.tpoint = ctx.tpoint->next)
5799 if (!ctx.tpoint->enabled)
5800 continue;
5802 /* Multiple tracepoints of different types, such as fast tracepoint and
5803 static tracepoint, can be set at the same address. */
5804 if (ctx.tpoint->type != tpoint->type)
5805 continue;
5807 /* Test the condition if present, and collect if true. */
5808 if (ctx.tpoint->cond == NULL
5809 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5810 ctx.tpoint))
5812 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5813 ctx.tpoint->address, ctx.tpoint);
5815 /* Note that this will cause original insns to be written back
5816 to where we jumped from, but that's OK because we're jumping
5817 back to the next whole instruction. This will go badly if
5818 instruction restoration is not atomic though. */
5819 if (stopping_tracepoint
5820 || trace_buffer_is_full
5821 || expr_eval_result != expr_eval_no_error)
5823 stop_tracing ();
5824 break;
5827 else
5829 /* If there was a condition and it evaluated to false, the only
5830 way we would stop tracing is if there was an error during
5831 condition expression evaluation. */
5832 if (expr_eval_result != expr_eval_no_error)
5834 stop_tracing ();
5835 break;
5841 /* These global variables points to the corresponding functions. This is
5842 necessary on powerpc64, where asking for function symbol address from gdb
5843 results in returning the actual code pointer, instead of the descriptor
5844 pointer. */
5846 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5847 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5848 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5849 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5851 EXTERN_C_PUSH
5852 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5853 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5854 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5855 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5856 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5857 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5858 EXTERN_C_POP
5860 #endif
5862 #ifndef IN_PROCESS_AGENT
5864 CORE_ADDR
5865 get_raw_reg_func_addr (void)
5867 CORE_ADDR res;
5868 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5870 error ("error extracting get_raw_reg_ptr");
5871 return 0;
5873 return res;
5876 CORE_ADDR
5877 get_get_tsv_func_addr (void)
5879 CORE_ADDR res;
5880 if (read_inferior_data_pointer (
5881 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5883 error ("error extracting get_trace_state_variable_value_ptr");
5884 return 0;
5886 return res;
5889 CORE_ADDR
5890 get_set_tsv_func_addr (void)
5892 CORE_ADDR res;
5893 if (read_inferior_data_pointer (
5894 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5896 error ("error extracting set_trace_state_variable_value_ptr");
5897 return 0;
5899 return res;
5902 static void
5903 compile_tracepoint_condition (struct tracepoint *tpoint,
5904 CORE_ADDR *jump_entry)
5906 CORE_ADDR entry_point = *jump_entry;
5907 enum eval_result_type err;
5909 trace_debug ("Starting condition compilation for tracepoint %d\n",
5910 tpoint->number);
5912 /* Initialize the global pointer to the code being built. */
5913 current_insn_ptr = *jump_entry;
5915 emit_prologue ();
5917 err = compile_bytecodes (tpoint->cond);
5919 if (err == expr_eval_no_error)
5921 emit_epilogue ();
5923 /* Record the beginning of the compiled code. */
5924 tpoint->compiled_cond = entry_point;
5926 trace_debug ("Condition compilation for tracepoint %d complete\n",
5927 tpoint->number);
5929 else
5931 /* Leave the unfinished code in situ, but don't point to it. */
5933 tpoint->compiled_cond = 0;
5935 trace_debug ("Condition compilation for tracepoint %d failed, "
5936 "error code %d",
5937 tpoint->number, err);
5940 /* Update the code pointer passed in. Note that we do this even if
5941 the compile fails, so that we can look at the partial results
5942 instead of letting them be overwritten. */
5943 *jump_entry = current_insn_ptr;
5945 /* Leave a gap, to aid dump decipherment. */
5946 *jump_entry += 16;
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;
5956 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5957 to 8 bytes. */
5959 static CORE_ADDR
5960 target_malloc (ULONGEST size)
5962 CORE_ADDR ptr;
5964 if (target_tp_heap == 0)
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))
5970 internal_error ("couldn't get target heap head pointer");
5974 ptr = target_tp_heap;
5975 target_tp_heap += size;
5977 /* Pad to 8-byte alignment. */
5978 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5980 return ptr;
5983 static CORE_ADDR
5984 download_agent_expr (struct agent_expr *expr)
5986 CORE_ADDR expr_addr;
5987 CORE_ADDR expr_bytes;
5989 expr_addr = target_malloc (sizeof (*expr));
5990 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5992 expr_bytes = target_malloc (expr->length);
5993 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
5994 expr_bytes);
5995 target_write_memory (expr_bytes, expr->bytes, expr->length);
5997 return expr_addr;
6000 /* Align V up to N bits. */
6001 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
6003 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
6005 static void
6006 download_tracepoint_1 (struct tracepoint *tpoint)
6008 struct tracepoint target_tracepoint;
6009 CORE_ADDR tpptr = 0;
6011 gdb_assert (tpoint->type == fast_tracepoint
6012 || tpoint->type == static_tracepoint);
6014 if (tpoint->cond != NULL && target_emit_ops () != NULL)
6016 CORE_ADDR jentry, jump_entry;
6018 jentry = jump_entry = get_jump_space_head ();
6020 if (tpoint->cond != NULL)
6022 /* Pad to 8-byte alignment. (needed?) */
6023 /* Actually this should be left for the target to
6024 decide. */
6025 jentry = UALIGN (jentry, 8);
6027 compile_tracepoint_condition (tpoint, &jentry);
6030 /* Pad to 8-byte alignment. */
6031 jentry = UALIGN (jentry, 8);
6032 claim_jump_space (jentry - jump_entry);
6035 target_tracepoint = *tpoint;
6037 tpptr = target_malloc (sizeof (*tpoint));
6038 tpoint->obj_addr_on_target = tpptr;
6040 /* Write the whole object. We'll fix up its pointers in a bit.
6041 Assume no next for now. This is fixed up above on the next
6042 iteration, if there's any. */
6043 target_tracepoint.next = NULL;
6044 /* Need to clear this here too, since we're downloading the
6045 tracepoints before clearing our own copy. */
6046 target_tracepoint.hit_count = 0;
6048 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
6049 sizeof (target_tracepoint));
6051 if (tpoint->cond)
6052 write_inferior_data_pointer (tpptr
6053 + offsetof (struct tracepoint, cond),
6054 download_agent_expr (tpoint->cond));
6056 if (tpoint->numactions)
6058 int i;
6059 CORE_ADDR actions_array;
6061 /* The pointers array. */
6062 actions_array
6063 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
6064 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
6065 actions),
6066 actions_array);
6068 /* Now for each pointer, download the action. */
6069 for (i = 0; i < tpoint->numactions; i++)
6071 struct tracepoint_action *action = tpoint->actions[i];
6072 CORE_ADDR ipa_action = tracepoint_action_download (action);
6074 if (ipa_action != 0)
6075 write_inferior_data_pointer (actions_array
6076 + i * sizeof (*tpoint->actions),
6077 ipa_action);
6082 #define IPA_PROTO_FAST_TRACE_FLAG 0
6083 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
6084 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
6085 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
6086 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
6088 /* Send a command to agent to download and install tracepoint TPOINT. */
6090 static int
6091 tracepoint_send_agent (struct tracepoint *tpoint)
6093 char buf[IPA_CMD_BUF_SIZE];
6094 char *p;
6095 int i, ret;
6097 p = buf;
6098 strcpy (p, "FastTrace:");
6099 p += 10;
6101 COPY_FIELD_TO_BUF (p, tpoint, number);
6102 COPY_FIELD_TO_BUF (p, tpoint, address);
6103 COPY_FIELD_TO_BUF (p, tpoint, type);
6104 COPY_FIELD_TO_BUF (p, tpoint, enabled);
6105 COPY_FIELD_TO_BUF (p, tpoint, step_count);
6106 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
6107 COPY_FIELD_TO_BUF (p, tpoint, numactions);
6108 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
6109 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
6110 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
6111 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
6113 /* condition */
6114 p = agent_expr_send (p, tpoint->cond);
6116 /* tracepoint_action */
6117 for (i = 0; i < tpoint->numactions; i++)
6119 struct tracepoint_action *action = tpoint->actions[i];
6121 p[0] = action->type;
6122 p = tracepoint_action_send (&p[1], action);
6125 get_jump_space_head ();
6126 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
6127 agent can use jump pad from it. */
6128 if (tpoint->type == fast_tracepoint)
6130 memcpy (p, &gdb_jump_pad_head, 8);
6131 p += 8;
6134 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
6135 if (ret)
6136 return ret;
6138 if (!startswith (buf, "OK"))
6139 return 1;
6141 /* The value of tracepoint's target address is stored in BUF. */
6142 memcpy (&tpoint->obj_addr_on_target,
6143 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
6145 if (tpoint->type == fast_tracepoint)
6147 unsigned char *insn
6148 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
6149 int fjump_size;
6151 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
6152 (unsigned int) tpoint->obj_addr_on_target,
6153 (unsigned int) gdb_jump_pad_head);
6155 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
6157 /* This has been done in agent. We should also set up record for it. */
6158 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
6159 /* Wire it in. */
6160 tpoint->handle
6161 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
6164 return 0;
6167 static void
6168 download_tracepoint (struct tracepoint *tpoint)
6170 struct tracepoint *tp, *tp_prev;
6172 if (tpoint->type != fast_tracepoint
6173 && tpoint->type != static_tracepoint)
6174 return;
6176 download_tracepoint_1 (tpoint);
6178 /* Find the previous entry of TPOINT, which is fast tracepoint or
6179 static tracepoint. */
6180 tp_prev = NULL;
6181 for (tp = tracepoints; tp != tpoint; tp = tp->next)
6183 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
6184 tp_prev = tp;
6187 if (tp_prev)
6189 CORE_ADDR tp_prev_target_next_addr;
6191 /* Insert TPOINT after TP_PREV in IPA. */
6192 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
6193 + offsetof (struct tracepoint, next),
6194 &tp_prev_target_next_addr))
6196 internal_error ("error reading `tp_prev->next'");
6199 /* tpoint->next = tp_prev->next */
6200 write_inferior_data_pointer (tpoint->obj_addr_on_target
6201 + offsetof (struct tracepoint, next),
6202 tp_prev_target_next_addr);
6203 /* tp_prev->next = tpoint */
6204 write_inferior_data_pointer (tp_prev->obj_addr_on_target
6205 + offsetof (struct tracepoint, next),
6206 tpoint->obj_addr_on_target);
6208 else
6209 /* First object in list, set the head pointer in the
6210 inferior. */
6211 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
6212 tpoint->obj_addr_on_target);
6216 static void
6217 download_trace_state_variables (void)
6219 CORE_ADDR ptr = 0, prev_ptr = 0;
6220 struct trace_state_variable *tsv;
6222 /* Start out empty. */
6223 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
6225 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
6227 struct trace_state_variable target_tsv;
6229 /* TSV's with a getter have been initialized equally in both the
6230 inferior and GDBserver. Skip them. */
6231 if (tsv->getter != NULL)
6232 continue;
6234 target_tsv = *tsv;
6236 prev_ptr = ptr;
6237 ptr = target_malloc (sizeof (*tsv));
6239 if (tsv == trace_state_variables)
6241 /* First object in list, set the head pointer in the
6242 inferior. */
6244 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
6245 ptr);
6247 else
6249 write_inferior_data_pointer (prev_ptr
6250 + offsetof (struct trace_state_variable,
6251 next),
6252 ptr);
6255 /* Write the whole object. We'll fix up its pointers in a bit.
6256 Assume no next, fixup when needed. */
6257 target_tsv.next = NULL;
6259 target_write_memory (ptr, (unsigned char *) &target_tsv,
6260 sizeof (target_tsv));
6262 if (tsv->name != NULL)
6264 size_t size = strlen (tsv->name) + 1;
6265 CORE_ADDR name_addr = target_malloc (size);
6266 target_write_memory (name_addr,
6267 (unsigned char *) tsv->name, size);
6268 write_inferior_data_pointer (ptr
6269 + offsetof (struct trace_state_variable,
6270 name),
6271 name_addr);
6274 gdb_assert (tsv->getter == NULL);
6277 if (prev_ptr != 0)
6279 /* Fixup the next pointer in the last item in the list. */
6280 write_inferior_data_pointer (prev_ptr
6281 + offsetof (struct trace_state_variable,
6282 next), 0);
6286 /* Upload complete trace frames out of the IP Agent's trace buffer
6287 into GDBserver's trace buffer. This always uploads either all or
6288 no trace frames. This is the counter part of
6289 `trace_alloc_trace_buffer'. See its description of the atomic
6290 syncing mechanism. */
6292 static void
6293 upload_fast_traceframes (void)
6295 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
6296 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
6297 CORE_ADDR tf;
6298 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
6299 unsigned int curr_tbctrl_idx;
6300 unsigned int ipa_trace_buffer_ctrl_curr;
6301 unsigned int ipa_trace_buffer_ctrl_curr_old;
6302 CORE_ADDR ipa_trace_buffer_ctrl_addr;
6303 struct breakpoint *about_to_request_buffer_space_bkpt;
6304 CORE_ADDR ipa_trace_buffer_lo;
6305 CORE_ADDR ipa_trace_buffer_hi;
6307 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6308 &ipa_traceframe_read_count_racy))
6310 /* This will happen in most targets if the current thread is
6311 running. */
6312 return;
6315 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6316 &ipa_traceframe_write_count_racy))
6317 return;
6319 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
6320 ipa_traceframe_write_count_racy
6321 - ipa_traceframe_read_count_racy,
6322 ipa_traceframe_write_count_racy,
6323 ipa_traceframe_read_count_racy);
6325 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
6326 return;
6328 about_to_request_buffer_space_bkpt
6329 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
6330 NULL);
6332 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6333 &ipa_trace_buffer_ctrl_curr))
6334 return;
6336 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
6338 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
6341 unsigned int prev, counter;
6343 /* Update the token, with new counters, and the GDBserver stamp
6344 bit. Alway reuse the current TBC index. */
6345 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6346 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6348 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
6349 | (prev << 12)
6350 | counter
6351 | curr_tbctrl_idx);
6354 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6355 ipa_trace_buffer_ctrl_curr))
6356 return;
6358 trace_debug ("Lib: Committed %08x -> %08x",
6359 ipa_trace_buffer_ctrl_curr_old,
6360 ipa_trace_buffer_ctrl_curr);
6362 /* Re-read these, now that we've installed the
6363 `about_to_request_buffer_space' breakpoint/lock. A thread could
6364 have finished a traceframe between the last read of these
6365 counters and setting the breakpoint above. If we start
6366 uploading, we never want to leave this function with
6367 traceframe_read_count != 0, otherwise, GDBserver could end up
6368 incrementing the counter tokens more than once (due to event loop
6369 nesting), which would break the IP agent's "effective" detection
6370 (see trace_alloc_trace_buffer). */
6371 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6372 &ipa_traceframe_read_count))
6373 return;
6374 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6375 &ipa_traceframe_write_count))
6376 return;
6378 if (debug_threads)
6380 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
6381 ipa_traceframe_write_count - ipa_traceframe_read_count,
6382 ipa_traceframe_write_count, ipa_traceframe_read_count);
6384 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
6385 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
6386 trace_debug ("note that ipa_traceframe_count's parts changed");
6389 /* Get the address of the current TBC object (the IP agent has an
6390 array of 3 such objects). The index is stored in the TBC
6391 token. */
6392 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
6393 ipa_trace_buffer_ctrl_addr
6394 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
6396 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
6397 (unsigned char *) &ipa_trace_buffer_ctrl,
6398 sizeof (struct ipa_trace_buffer_control)))
6399 return;
6401 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
6402 &ipa_trace_buffer_lo))
6403 return;
6404 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
6405 &ipa_trace_buffer_hi))
6406 return;
6408 /* Offsets are easier to grok for debugging than raw addresses,
6409 especially for the small trace buffer sizes that are useful for
6410 testing. */
6411 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6412 "endfree=%d wrap=%d hi=%d",
6413 curr_tbctrl_idx,
6414 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6415 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6416 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6417 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6418 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6420 /* Note that the IPA's buffer is always circular. */
6422 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6424 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6425 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6427 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6428 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6429 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6430 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6431 : 0))
6433 tf = IPA_FIRST_TRACEFRAME ();
6435 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6437 struct tracepoint *tpoint;
6438 struct traceframe *tframe;
6439 unsigned char *block;
6440 struct traceframe ipa_tframe;
6442 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6443 offsetof (struct traceframe, data)))
6444 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6446 if (ipa_tframe.tpnum == 0)
6448 internal_error ("Uploading: No (more) fast traceframes, but"
6449 " ipa_traceframe_count == %u??\n",
6450 ipa_traceframe_write_count
6451 - ipa_traceframe_read_count);
6454 /* Note that this will be incorrect for multi-location
6455 tracepoints... */
6456 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6458 tframe = add_traceframe (tpoint);
6459 if (tframe == NULL)
6461 trace_buffer_is_full = 1;
6462 trace_debug ("Uploading: trace buffer is full");
6464 else
6466 /* Copy the whole set of blocks in one go for now. FIXME:
6467 split this in smaller blocks. */
6468 block = add_traceframe_block (tframe, tpoint,
6469 ipa_tframe.data_size);
6470 if (block != NULL)
6472 if (read_inferior_memory (tf
6473 + offsetof (struct traceframe, data),
6474 block, ipa_tframe.data_size))
6475 error ("Uploading: Couldn't read traceframe data at %s\n",
6476 paddress (tf + offsetof (struct traceframe, data)));
6479 trace_debug ("Uploading: traceframe didn't fit");
6480 finish_traceframe (tframe);
6483 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6485 /* If we freed the traceframe that wrapped around, go back
6486 to the non-wrap case. */
6487 if (tf < ipa_trace_buffer_ctrl.start)
6489 trace_debug ("Lib: Discarding past the wraparound");
6490 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6492 ipa_trace_buffer_ctrl.start = tf;
6493 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6494 ++ipa_traceframe_read_count;
6496 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6497 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6499 trace_debug ("Lib: buffer is fully empty. "
6500 "Trace buffer [%d] start=%d free=%d endfree=%d",
6501 curr_tbctrl_idx,
6502 (int) (ipa_trace_buffer_ctrl.start
6503 - ipa_trace_buffer_lo),
6504 (int) (ipa_trace_buffer_ctrl.free
6505 - ipa_trace_buffer_lo),
6506 (int) (ipa_trace_buffer_ctrl.end_free
6507 - ipa_trace_buffer_lo));
6509 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6510 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6511 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6512 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6515 trace_debug ("Uploaded a traceframe\n"
6516 "Lib: Trace buffer [%d] start=%d free=%d "
6517 "endfree=%d wrap=%d hi=%d",
6518 curr_tbctrl_idx,
6519 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6520 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6521 (int) (ipa_trace_buffer_ctrl.end_free
6522 - ipa_trace_buffer_lo),
6523 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6524 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6527 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6528 (unsigned char *) &ipa_trace_buffer_ctrl,
6529 sizeof (struct ipa_trace_buffer_control)))
6530 return;
6532 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6533 ipa_traceframe_read_count);
6535 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6537 target_pause_all (true);
6539 delete_breakpoint (about_to_request_buffer_space_bkpt);
6540 about_to_request_buffer_space_bkpt = NULL;
6542 target_unpause_all (true);
6544 if (trace_buffer_is_full)
6545 stop_tracing ();
6547 #endif
6549 #ifdef IN_PROCESS_AGENT
6551 IP_AGENT_EXPORT_VAR int ust_loaded;
6552 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6554 #ifdef HAVE_UST
6556 /* Static tracepoints. */
6558 /* UST puts a "struct tracepoint" in the global namespace, which
6559 conflicts with our tracepoint. Arguably, being a library, it
6560 shouldn't take ownership of such a generic name. We work around it
6561 here. */
6562 #define tracepoint ust_tracepoint
6563 #include <ust/ust.h>
6564 #undef tracepoint
6566 extern int serialize_to_text (char *outbuf, int bufsize,
6567 const char *fmt, va_list ap);
6569 #define GDB_PROBE_NAME "gdb"
6571 /* We dynamically search for the UST symbols instead of linking them
6572 in. This lets the user decide if the application uses static
6573 tracepoints, instead of always pulling libust.so in. This vector
6574 holds pointers to all functions we care about. */
6576 static struct
6578 int (*serialize_to_text) (char *outbuf, int bufsize,
6579 const char *fmt, va_list ap);
6581 int (*ltt_probe_register) (struct ltt_available_probe *pdata);
6582 int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
6584 int (*ltt_marker_connect) (const char *channel, const char *mname,
6585 const char *pname);
6586 int (*ltt_marker_disconnect) (const char *channel, const char *mname,
6587 const char *pname);
6589 void (*marker_iter_start) (struct marker_iter *iter);
6590 void (*marker_iter_next) (struct marker_iter *iter);
6591 void (*marker_iter_stop) (struct marker_iter *iter);
6592 void (*marker_iter_reset) (struct marker_iter *iter);
6593 } ust_ops;
6595 #include <dlfcn.h>
6597 /* Cast through typeof to catch incompatible API changes. Since UST
6598 only builds with gcc, we can freely use gcc extensions here
6599 too. */
6600 #define GET_UST_SYM(SYM) \
6601 do \
6603 if (ust_ops.SYM == NULL) \
6604 ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM); \
6605 if (ust_ops.SYM == NULL) \
6606 return 0; \
6607 } while (0)
6609 #define USTF(SYM) ust_ops.SYM
6611 /* Get pointers to all libust.so functions we care about. */
6613 static int
6614 dlsym_ust (void)
6616 GET_UST_SYM (serialize_to_text);
6618 GET_UST_SYM (ltt_probe_register);
6619 GET_UST_SYM (ltt_probe_unregister);
6620 GET_UST_SYM (ltt_marker_connect);
6621 GET_UST_SYM (ltt_marker_disconnect);
6623 GET_UST_SYM (marker_iter_start);
6624 GET_UST_SYM (marker_iter_next);
6625 GET_UST_SYM (marker_iter_stop);
6626 GET_UST_SYM (marker_iter_reset);
6628 ust_loaded = 1;
6629 return 1;
6632 /* Given an UST marker, return the matching gdb static tracepoint.
6633 The match is done by address. */
6635 static struct tracepoint *
6636 ust_marker_to_static_tracepoint (const struct marker *mdata)
6638 struct tracepoint *tpoint;
6640 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
6642 if (tpoint->type != static_tracepoint)
6643 continue;
6645 if (tpoint->address == (uintptr_t) mdata->location)
6646 return tpoint;
6649 return NULL;
6652 /* The probe function we install on lttng/ust markers. Whenever a
6653 probed ust marker is hit, this function is called. This is similar
6654 to gdb_collect, only for static tracepoints, instead of fast
6655 tracepoints. */
6657 static void
6658 gdb_probe (const struct marker *mdata, void *probe_private,
6659 struct registers *regs, void *call_private,
6660 const char *fmt, va_list *args)
6662 struct tracepoint *tpoint;
6663 struct static_tracepoint_ctx ctx;
6664 const struct target_desc *ipa_tdesc;
6666 /* Don't do anything until the trace run is completely set up. */
6667 if (!tracing)
6669 trace_debug ("gdb_probe: not tracing\n");
6670 return;
6673 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
6674 ctx.base.type = static_tracepoint;
6675 ctx.regcache_initted = 0;
6676 ctx.regs = regs;
6677 ctx.fmt = fmt;
6678 ctx.args = args;
6680 /* Wrap the regblock in a register cache (in the stack, we don't
6681 want to malloc here). */
6682 ctx.regspace = alloca (ipa_tdesc->registers_size);
6683 if (ctx.regspace == NULL)
6685 trace_debug ("Trace buffer block allocation failed, skipping");
6686 return;
6689 tpoint = ust_marker_to_static_tracepoint (mdata);
6690 if (tpoint == NULL)
6692 trace_debug ("gdb_probe: marker not known: "
6693 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6694 mdata->location, mdata->channel,
6695 mdata->name, mdata->format);
6696 return;
6699 if (!tpoint->enabled)
6701 trace_debug ("gdb_probe: tracepoint disabled");
6702 return;
6705 ctx.tpoint = tpoint;
6707 trace_debug ("gdb_probe: collecting marker: "
6708 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6709 mdata->location, mdata->channel,
6710 mdata->name, mdata->format);
6712 /* Test the condition if present, and collect if true. */
6713 if (tpoint->cond == NULL
6714 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6715 tpoint))
6717 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6718 tpoint->address, tpoint);
6720 if (stopping_tracepoint
6721 || trace_buffer_is_full
6722 || expr_eval_result != expr_eval_no_error)
6723 stop_tracing ();
6725 else
6727 /* If there was a condition and it evaluated to false, the only
6728 way we would stop tracing is if there was an error during
6729 condition expression evaluation. */
6730 if (expr_eval_result != expr_eval_no_error)
6731 stop_tracing ();
6735 /* Called if the gdb static tracepoint requested collecting "$_sdata",
6736 static tracepoint string data. This is a string passed to the
6737 tracing library by the user, at the time of the tracepoint marker
6738 call. E.g., in the UST marker call:
6740 trace_mark (ust, bar33, "str %s", "FOOBAZ");
6742 the collected data is "str FOOBAZ".
6745 static void
6746 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
6747 struct traceframe *tframe)
6749 struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
6750 unsigned char *bufspace;
6751 int size;
6752 va_list copy;
6753 unsigned short blocklen;
6755 if (umd == NULL)
6757 trace_debug ("Wanted to collect static trace data, "
6758 "but there's no static trace data");
6759 return;
6762 va_copy (copy, *umd->args);
6763 size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
6764 va_end (copy);
6766 trace_debug ("Want to collect ust data");
6768 /* 'S' + size + string */
6769 bufspace = add_traceframe_block (tframe, umd->tpoint,
6770 1 + sizeof (blocklen) + size + 1);
6771 if (bufspace == NULL)
6773 trace_debug ("Trace buffer block allocation failed, skipping");
6774 return;
6777 /* Identify a static trace data block. */
6778 *bufspace = 'S';
6780 blocklen = size + 1;
6781 memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
6783 va_copy (copy, *umd->args);
6784 USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
6785 size + 1, umd->fmt, copy);
6786 va_end (copy);
6788 trace_debug ("Storing static tracepoint data in regblock: %s",
6789 bufspace + 1 + sizeof (blocklen));
6792 /* The probe to register with lttng/ust. */
6793 static struct ltt_available_probe gdb_ust_probe =
6795 GDB_PROBE_NAME,
6796 NULL,
6797 gdb_probe,
6800 #endif /* HAVE_UST */
6801 #endif /* IN_PROCESS_AGENT */
6803 #ifndef IN_PROCESS_AGENT
6805 /* Ask the in-process agent to run a command. Since we don't want to
6806 have to handle the IPA hitting breakpoints while running the
6807 command, we pause all threads, remove all breakpoints, and then set
6808 the helper thread re-running. We communicate with the helper
6809 thread by means of direct memory xfering, and a socket for
6810 synchronization. */
6812 static int
6813 run_inferior_command (char *cmd, int len)
6815 int err = -1;
6816 int pid = current_ptid.pid ();
6818 trace_debug ("run_inferior_command: running: %s", cmd);
6820 target_pause_all (false);
6821 uninsert_all_breakpoints ();
6823 err = agent_run_command (pid, (const char *) cmd, len);
6825 reinsert_all_breakpoints ();
6826 target_unpause_all (false);
6828 return err;
6831 #else /* !IN_PROCESS_AGENT */
6833 #include <sys/socket.h>
6834 #include <sys/un.h>
6836 #ifndef UNIX_PATH_MAX
6837 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6838 #endif
6840 /* Where we put the socked used for synchronization. */
6841 #define SOCK_DIR P_tmpdir
6843 /* Thread ID of the helper thread. GDBserver reads this to know which
6844 is the help thread. This is an LWP id on Linux. */
6845 EXTERN_C_PUSH
6846 IP_AGENT_EXPORT_VAR int helper_thread_id;
6847 EXTERN_C_POP
6849 static int
6850 init_named_socket (const char *name)
6852 int result, fd;
6853 struct sockaddr_un addr;
6855 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6856 if (result == -1)
6858 warning ("socket creation failed: %s", safe_strerror (errno));
6859 return -1;
6862 addr.sun_family = AF_UNIX;
6864 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6866 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6867 return -1;
6870 strcpy (addr.sun_path, name);
6872 result = access (name, F_OK);
6873 if (result == 0)
6875 /* File exists. */
6876 result = unlink (name);
6877 if (result == -1)
6879 warning ("unlink failed: %s", safe_strerror (errno));
6880 close (fd);
6881 return -1;
6883 warning ("socket %s already exists; overwriting", name);
6886 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6887 if (result == -1)
6889 warning ("bind failed: %s", safe_strerror (errno));
6890 close (fd);
6891 return -1;
6894 result = listen (fd, 1);
6895 if (result == -1)
6897 warning ("listen: %s", safe_strerror (errno));
6898 close (fd);
6899 return -1;
6902 return fd;
6905 static char agent_socket_name[UNIX_PATH_MAX];
6907 static int
6908 gdb_agent_socket_init (void)
6910 int result, fd;
6912 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6913 SOCK_DIR, getpid ());
6914 if (result >= UNIX_PATH_MAX)
6916 trace_debug ("string overflow allocating socket name");
6917 return -1;
6920 fd = init_named_socket (agent_socket_name);
6921 if (fd < 0)
6922 warning ("Error initializing named socket (%s) for communication with the "
6923 "ust helper thread. Check that directory exists and that it "
6924 "is writable.", agent_socket_name);
6926 return fd;
6929 #ifdef HAVE_UST
6931 /* The next marker to be returned on a qTsSTM command. */
6932 static const struct marker *next_st;
6934 /* Returns the first known marker. */
6936 struct marker *
6937 first_marker (void)
6939 struct marker_iter iter;
6941 USTF(marker_iter_reset) (&iter);
6942 USTF(marker_iter_start) (&iter);
6944 return iter.marker;
6947 /* Returns the marker following M. */
6949 const struct marker *
6950 next_marker (const struct marker *m)
6952 struct marker_iter iter;
6954 USTF(marker_iter_reset) (&iter);
6955 USTF(marker_iter_start) (&iter);
6957 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
6959 if (iter.marker == m)
6961 USTF(marker_iter_next) (&iter);
6962 return iter.marker;
6966 return NULL;
6969 /* Return an hexstr version of the STR C string, fit for sending to
6970 GDB. */
6972 static char *
6973 cstr_to_hexstr (const char *str)
6975 int len = strlen (str);
6976 char *hexstr = xmalloc (len * 2 + 1);
6977 bin2hex ((gdb_byte *) str, hexstr, len);
6978 return hexstr;
6981 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
6982 packets. */
6984 static void
6985 response_ust_marker (char *packet, const struct marker *st)
6987 char *strid, *format, *tmp;
6989 next_st = next_marker (st);
6991 tmp = xmalloc (strlen (st->channel) + 1 +
6992 strlen (st->name) + 1);
6993 sprintf (tmp, "%s/%s", st->channel, st->name);
6995 strid = cstr_to_hexstr (tmp);
6996 free (tmp);
6998 format = cstr_to_hexstr (st->format);
7000 sprintf (packet, "m%s:%s:%s",
7001 paddress ((uintptr_t) st->location),
7002 strid,
7003 format);
7005 free (strid);
7006 free (format);
7009 /* Return the first static tracepoint, and initialize the state
7010 machine that will iterate through all the static tracepoints. */
7012 static void
7013 cmd_qtfstm (char *packet)
7015 trace_debug ("Returning first trace state variable definition");
7017 if (first_marker ())
7018 response_ust_marker (packet, first_marker ());
7019 else
7020 strcpy (packet, "l");
7023 /* Return additional trace state variable definitions. */
7025 static void
7026 cmd_qtsstm (char *packet)
7028 trace_debug ("Returning static tracepoint");
7030 if (next_st)
7031 response_ust_marker (packet, next_st);
7032 else
7033 strcpy (packet, "l");
7036 /* Disconnect the GDB probe from a marker at a given address. */
7038 static void
7039 unprobe_marker_at (char *packet)
7041 char *p = packet;
7042 ULONGEST address;
7043 struct marker_iter iter;
7045 p += sizeof ("unprobe_marker_at:") - 1;
7047 p = unpack_varlen_hex (p, &address);
7049 USTF(marker_iter_reset) (&iter);
7050 USTF(marker_iter_start) (&iter);
7051 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7052 if ((uintptr_t ) iter.marker->location == address)
7054 int result;
7056 result = USTF(ltt_marker_disconnect) (iter.marker->channel,
7057 iter.marker->name,
7058 GDB_PROBE_NAME);
7059 if (result < 0)
7060 warning ("could not disable marker %s/%s",
7061 iter.marker->channel, iter.marker->name);
7062 break;
7066 /* Connect the GDB probe to a marker at a given address. */
7068 static int
7069 probe_marker_at (char *packet)
7071 char *p = packet;
7072 ULONGEST address;
7073 struct marker_iter iter;
7074 struct marker *m;
7076 p += sizeof ("probe_marker_at:") - 1;
7078 p = unpack_varlen_hex (p, &address);
7080 USTF(marker_iter_reset) (&iter);
7082 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7083 m != NULL;
7084 USTF(marker_iter_next) (&iter), m = iter.marker)
7085 if ((uintptr_t ) m->location == address)
7087 int result;
7089 trace_debug ("found marker for address. "
7090 "ltt_marker_connect (marker = %s/%s)",
7091 m->channel, m->name);
7093 result = USTF(ltt_marker_connect) (m->channel, m->name,
7094 GDB_PROBE_NAME);
7095 if (result && result != -EEXIST)
7096 trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
7097 m->channel, m->name, -result);
7099 if (result < 0)
7101 sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
7102 m->channel, m->name);
7103 return -1;
7106 strcpy (packet, "OK");
7107 return 0;
7110 sprintf (packet, "E.no marker found at 0x%s", paddress (address));
7111 return -1;
7114 static int
7115 cmd_qtstmat (char *packet)
7117 char *p = packet;
7118 ULONGEST address;
7119 struct marker_iter iter;
7120 struct marker *m;
7122 p += sizeof ("qTSTMat:") - 1;
7124 p = unpack_varlen_hex (p, &address);
7126 USTF(marker_iter_reset) (&iter);
7128 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7129 m != NULL;
7130 USTF(marker_iter_next) (&iter), m = iter.marker)
7131 if ((uintptr_t ) m->location == address)
7133 response_ust_marker (packet, m);
7134 return 0;
7137 strcpy (packet, "l");
7138 return -1;
7141 static void
7142 gdb_ust_init (void)
7144 if (!dlsym_ust ())
7145 return;
7147 USTF(ltt_probe_register) (&gdb_ust_probe);
7150 #endif /* HAVE_UST */
7152 #include <sys/syscall.h>
7154 static void
7155 gdb_agent_remove_socket (void)
7157 unlink (agent_socket_name);
7160 /* Helper thread of agent. */
7162 static void *
7163 gdb_agent_helper_thread (void *arg)
7165 int listen_fd;
7167 atexit (gdb_agent_remove_socket);
7169 while (1)
7171 listen_fd = gdb_agent_socket_init ();
7173 if (helper_thread_id == 0)
7174 helper_thread_id = syscall (SYS_gettid);
7176 if (listen_fd == -1)
7178 warning ("could not create sync socket");
7179 break;
7182 while (1)
7184 socklen_t tmp;
7185 struct sockaddr_un sockaddr;
7186 int fd;
7187 char buf[1];
7188 int ret;
7189 int stop_loop = 0;
7191 tmp = sizeof (sockaddr);
7195 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
7197 /* It seems an ERESTARTSYS can escape out of accept. */
7198 while (fd == -512 || (fd == -1 && errno == EINTR));
7200 if (fd < 0)
7202 warning ("Accept returned %d, error: %s",
7203 fd, safe_strerror (errno));
7204 break;
7209 ret = read (fd, buf, 1);
7210 } while (ret == -1 && errno == EINTR);
7212 if (ret == -1)
7214 warning ("reading socket (fd=%d) failed with %s",
7215 fd, safe_strerror (errno));
7216 close (fd);
7217 break;
7220 if (cmd_buf[0])
7222 if (startswith (cmd_buf, "close"))
7224 stop_loop = 1;
7226 #ifdef HAVE_UST
7227 else if (strcmp ("qTfSTM", cmd_buf) == 0)
7229 cmd_qtfstm (cmd_buf);
7231 else if (strcmp ("qTsSTM", cmd_buf) == 0)
7233 cmd_qtsstm (cmd_buf);
7235 else if (startswith (cmd_buf, "unprobe_marker_at:"))
7237 unprobe_marker_at (cmd_buf);
7239 else if (startswith (cmd_buf, "probe_marker_at:"))
7241 probe_marker_at (cmd_buf);
7243 else if (startswith (cmd_buf, "qTSTMat:"))
7245 cmd_qtstmat (cmd_buf);
7247 #endif /* HAVE_UST */
7250 /* Fix compiler's warning: ignoring return value of 'write'. */
7251 ret = write (fd, buf, 1);
7252 close (fd);
7254 if (stop_loop)
7256 close (listen_fd);
7257 unlink (agent_socket_name);
7259 /* Sleep endlessly to wait the whole inferior stops. This
7260 thread can not exit because GDB or GDBserver may still need
7261 'current_thread' (representing this thread) to access
7262 inferior memory. Otherwise, this thread exits earlier than
7263 other threads, and 'current_thread' is set to NULL. */
7264 while (1)
7265 sleep (10);
7270 return NULL;
7273 #include <signal.h>
7274 #include <pthread.h>
7276 EXTERN_C_PUSH
7277 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
7278 EXTERN_C_POP
7280 static void
7281 gdb_agent_init (void)
7283 int res;
7284 pthread_t thread;
7285 sigset_t new_mask;
7286 sigset_t orig_mask;
7288 /* We want the helper thread to be as transparent as possible, so
7289 have it inherit an all-signals-blocked mask. */
7291 sigfillset (&new_mask);
7292 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
7293 if (res)
7294 perror_with_name ("pthread_sigmask (1)");
7296 res = pthread_create (&thread,
7297 NULL,
7298 gdb_agent_helper_thread,
7299 NULL);
7301 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
7302 if (res)
7303 perror_with_name ("pthread_sigmask (2)");
7305 while (helper_thread_id == 0)
7306 usleep (1);
7308 #ifdef HAVE_UST
7309 gdb_ust_init ();
7310 #endif
7313 #include <sys/mman.h>
7315 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
7316 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
7317 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
7318 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
7319 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
7320 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
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. */
7326 void
7327 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
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");
7337 static void __attribute__ ((constructor))
7338 initialize_tracepoint_ftlib (void)
7340 initialize_tracepoint ();
7342 gdb_agent_init ();
7345 #ifndef HAVE_GETAUXVAL
7346 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
7347 found, 0 is returned. This function is provided if glibc is too old. */
7349 unsigned long
7350 getauxval (unsigned long type)
7352 unsigned long data[2];
7353 FILE *f = fopen ("/proc/self/auxv", "r");
7354 unsigned long value = 0;
7356 if (f == NULL)
7357 return 0;
7359 while (fread (data, sizeof (data), 1, f) > 0)
7361 if (data[0] == type)
7363 value = data[1];
7364 break;
7368 fclose (f);
7369 return value;
7371 #endif
7373 #endif /* IN_PROCESS_AGENT */
7375 /* Return a timestamp, expressed as microseconds of the usual Unix
7376 time. (As the result is a 64-bit number, it will not overflow any
7377 time soon.) */
7379 static LONGEST
7380 get_timestamp (void)
7382 using namespace std::chrono;
7384 steady_clock::time_point now = steady_clock::now ();
7385 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
7388 void
7389 initialize_tracepoint (void)
7391 /* Start with the default size. */
7392 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
7394 /* Wire trace state variable 1 to be the timestamp. This will be
7395 uploaded to GDB upon connection and become one of its trace state
7396 variables. (In case you're wondering, if GDB already has a trace
7397 variable numbered 1, it will be renumbered.) */
7398 create_trace_state_variable (1, 0);
7399 set_trace_state_variable_name (1, "trace_timestamp");
7400 set_trace_state_variable_getter (1, get_timestamp);
7402 #ifdef IN_PROCESS_AGENT
7404 int pagesize;
7405 size_t jump_pad_size;
7407 pagesize = sysconf (_SC_PAGE_SIZE);
7408 if (pagesize == -1)
7409 perror_with_name ("sysconf");
7411 #define SCRATCH_BUFFER_NPAGES 20
7413 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
7415 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
7416 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
7417 if (gdb_jump_pad_buffer == NULL)
7418 perror_with_name ("mmap");
7419 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
7422 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
7424 /* It's not a fatal error for something to go wrong with trampoline
7425 buffer setup, but it can be mysterious, so create a channel to
7426 report back on what went wrong, using a fixed size since we may
7427 not be able to allocate space later when the problem occurs. */
7428 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
7430 strcpy (gdb_trampoline_buffer_error, "No errors reported");
7432 initialize_low_tracepoint ();
7433 #endif