Add documentation for the MIPS assembler's -march=from-abi command line option
[binutils-gdb.git] / gdbserver / tracepoint.cc
bloba5f58fd54eb1693bd570a2260817111bac961616
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" {
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;
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 #define AX_RESULT_TYPE(ENUM,STR) STR,
863 #include "ax-result-types.def"
864 #undef AX_RESULT_TYPE
867 #endif
869 /* The tracepoint in which the error occurred. */
871 extern "C" {
872 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
875 struct trace_state_variable
877 /* This is the name of the variable as used in GDB. The target
878 doesn't use the name, but needs to have it for saving and
879 reconnection purposes. */
880 char *name;
882 /* This number identifies the variable uniquely. Numbers may be
883 assigned either by the target (in the case of builtin variables),
884 or by GDB, and are presumed unique during the course of a trace
885 experiment. */
886 int number;
888 /* The variable's initial value, a 64-bit signed integer always. */
889 LONGEST initial_value;
891 /* The variable's value, a 64-bit signed integer always. */
892 LONGEST value;
894 /* Pointer to a getter function, used to supply computed values. */
895 LONGEST (*getter) (void);
897 /* Link to the next variable. */
898 struct trace_state_variable *next;
901 /* Linked list of all trace state variables. */
903 #ifdef IN_PROCESS_AGENT
904 static struct trace_state_variable *alloced_trace_state_variables;
905 #endif
907 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
909 /* The results of tracing go into a fixed-size space known as the
910 "trace buffer". Because usage follows a limited number of
911 patterns, we manage it ourselves rather than with malloc. Basic
912 rules are that we create only one trace frame at a time, each is
913 variable in size, they are never moved once created, and we only
914 discard if we are doing a circular buffer, and then only the oldest
915 ones. Each trace frame includes its own size, so we don't need to
916 link them together, and the trace frame number is relative to the
917 first one, so we don't need to record numbers. A trace frame also
918 records the number of the tracepoint that created it. The data
919 itself is a series of blocks, each introduced by a single character
920 and with a defined format. Each type of block has enough
921 type/length info to allow scanners to jump quickly from one block
922 to the next without reading each byte in the block. */
924 /* Trace buffer management would be simple - advance a free pointer
925 from beginning to end, then stop - were it not for the circular
926 buffer option, which is a useful way to prevent a trace run from
927 stopping prematurely because the buffer filled up. In the circular
928 case, the location of the first trace frame (trace_buffer_start)
929 moves as old trace frames are discarded. Also, since we grow trace
930 frames incrementally as actions are performed, we wrap around to
931 the beginning of the trace buffer. This is per-block, so each
932 block within a trace frame remains contiguous. Things get messy
933 when the wrapped-around trace frame is the one being discarded; the
934 free space ends up in two parts at opposite ends of the buffer. */
936 #ifndef ATTR_PACKED
937 # if defined(__GNUC__)
938 # define ATTR_PACKED __attribute__ ((packed))
939 # else
940 # define ATTR_PACKED /* nothing */
941 # endif
942 #endif
944 /* The data collected at a tracepoint hit. This object should be as
945 small as possible, since there may be a great many of them. We do
946 not need to keep a frame number, because they are all sequential
947 and there are no deletions; so the Nth frame in the buffer is
948 always frame number N. */
950 struct traceframe
952 /* Number of the tracepoint that collected this traceframe. A value
953 of 0 indicates the current end of the trace buffer. We make this
954 a 16-bit field because it's never going to happen that GDB's
955 numbering of tracepoints reaches 32,000. */
956 int tpnum : 16;
958 /* The size of the data in this trace frame. We limit this to 32
959 bits, even on a 64-bit target, because it's just implausible that
960 one is validly going to collect 4 gigabytes of data at a single
961 tracepoint hit. */
962 unsigned int data_size : 32;
964 /* The base of the trace data, which is contiguous from this point. */
965 unsigned char data[0];
967 } ATTR_PACKED;
969 /* The size of the EOB marker, in bytes. A traceframe with zeroed
970 fields (and no data) marks the end of trace data. */
971 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
973 /* This flag is true if the trace buffer is circular, meaning that
974 when it fills, the oldest trace frames are discarded in order to
975 make room. */
977 #ifndef IN_PROCESS_AGENT
978 static int circular_trace_buffer;
979 #endif
981 /* Size of the trace buffer. */
983 static LONGEST trace_buffer_size;
985 extern "C" {
987 /* Pointer to the block of memory that traceframes all go into. */
989 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
991 /* Pointer to the end of the trace buffer, more precisely to the byte
992 after the end of the buffer. */
994 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
998 /* Control structure holding the read/write/etc. pointers into the
999 trace buffer. We need more than one of these to implement a
1000 transaction-like mechanism to guarantees that both GDBserver and the
1001 in-process agent can try to change the trace buffer
1002 simultaneously. */
1004 struct trace_buffer_control
1006 /* Pointer to the first trace frame in the buffer. In the
1007 non-circular case, this is equal to trace_buffer_lo, otherwise it
1008 moves around in the buffer. */
1009 unsigned char *start;
1011 /* Pointer to the free part of the trace buffer. Note that we clear
1012 several bytes at and after this pointer, so that traceframe
1013 scans/searches terminate properly. */
1014 unsigned char *free;
1016 /* Pointer to the byte after the end of the free part. Note that
1017 this may be smaller than trace_buffer_free in the circular case,
1018 and means that the free part is in two pieces. Initially it is
1019 equal to trace_buffer_hi, then is generally equivalent to
1020 trace_buffer_start. */
1021 unsigned char *end_free;
1023 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
1024 this is the point at which the trace data breaks, and resumes at
1025 trace_buffer_lo. */
1026 unsigned char *wrap;
1029 /* Same as above, to be used by GDBserver when updating the in-process
1030 agent. */
1031 struct ipa_trace_buffer_control
1033 uintptr_t start;
1034 uintptr_t free;
1035 uintptr_t end_free;
1036 uintptr_t wrap;
1040 /* We have possibly both GDBserver and an inferior thread accessing
1041 the same IPA trace buffer memory. The IPA is the producer (tries
1042 to put new frames in the buffer), while GDBserver occasionally
1043 consumes them, that is, flushes the IPA's buffer into its own
1044 buffer. Both sides need to update the trace buffer control
1045 pointers (current head, tail, etc.). We can't use a global lock to
1046 synchronize the accesses, as otherwise we could deadlock GDBserver
1047 (if the thread holding the lock stops for a signal, say). So
1048 instead of that, we use a transaction scheme where GDBserver writes
1049 always prevail over the IPAs writes, and, we have the IPA detect
1050 the commit failure/overwrite, and retry the whole attempt. This is
1051 mainly implemented by having a global token object that represents
1052 who wrote last to the buffer control structure. We need to freeze
1053 any inferior writing to the buffer while GDBserver touches memory,
1054 so that the inferior can correctly detect that GDBserver had been
1055 there, otherwise, it could mistakingly think its commit was
1056 successful; that's implemented by simply having GDBserver set a
1057 breakpoint the inferior hits if it is the critical region.
1059 There are three cycling trace buffer control structure copies
1060 (buffer head, tail, etc.), with the token object including an index
1061 indicating which is current live copy. The IPA tentatively builds
1062 an updated copy in a non-current control structure, while GDBserver
1063 always clobbers the current version directly. The IPA then tries
1064 to atomically "commit" its version; if GDBserver clobbered the
1065 structure meanwhile, that will fail, and the IPA restarts the
1066 allocation process.
1068 Listing the step in further detail, we have:
1070 In-process agent (producer):
1072 - passes by `about_to_request_buffer_space' breakpoint/lock
1074 - reads current token, extracts current trace buffer control index,
1075 and starts tentatively updating the rightmost one (0->1, 1->2,
1076 2->0). Note that only one inferior thread is executing this code
1077 at any given time, due to an outer lock in the jump pads.
1079 - updates counters, and tries to commit the token.
1081 - passes by second `about_to_request_buffer_space' breakpoint/lock,
1082 leaving the sync region.
1084 - checks if the update was effective.
1086 - if trace buffer was found full, hits flush_trace_buffer
1087 breakpoint, and restarts later afterwards.
1089 GDBserver (consumer):
1091 - sets `about_to_request_buffer_space' breakpoint/lock.
1093 - updates the token unconditionally, using the current buffer
1094 control index, since it knows that the IP agent always writes to
1095 the rightmost, and due to the breakpoint, at most one IP thread
1096 can try to update the trace buffer concurrently to GDBserver, so
1097 there will be no danger of trace buffer control index wrap making
1098 the IPA write to the same index as GDBserver.
1100 - flushes the IP agent's trace buffer completely, and updates the
1101 current trace buffer control structure. GDBserver *always* wins.
1103 - removes the `about_to_request_buffer_space' breakpoint.
1105 The token is stored in the `trace_buffer_ctrl_curr' variable.
1106 Internally, it's bits are defined as:
1108 |-------------+-----+-------------+--------+-------------+--------------|
1109 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1110 |-------------+-----+-------------+--------+-------------+--------------|
1111 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1112 |-------------+-----+-------------+--------+-------------+--------------|
1114 GSB - GDBserver Stamp Bit
1115 PC - Previous Counter
1116 CC - Current Counter
1117 TBCI - Trace Buffer Control Index
1120 An IPA update of `trace_buffer_ctrl_curr' does:
1122 - read CC from the current token, save as PC.
1123 - updates pointers
1124 - atomically tries to write PC+1,CC
1126 A GDBserver update of `trace_buffer_ctrl_curr' does:
1128 - reads PC and CC from the current token.
1129 - updates pointers
1130 - writes GSB,PC,CC
1133 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1134 for the counters described below. The cleared bits are used to
1135 hold the index of the items of the `trace_buffer_ctrl' array that
1136 is "current". */
1137 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1139 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1140 counter, and the `current' counter. */
1142 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1143 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1145 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1146 always stamps this bit as set. */
1147 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1149 #ifdef IN_PROCESS_AGENT
1150 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1151 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1153 # define TRACE_BUFFER_CTRL_CURR \
1154 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1156 #else
1158 /* The GDBserver side agent only needs one instance of this object, as
1159 it doesn't need to sync with itself. Define it as array anyway so
1160 that the rest of the code base doesn't need to care for the
1161 difference. */
1162 static trace_buffer_control trace_buffer_ctrl[1];
1163 # define TRACE_BUFFER_CTRL_CURR 0
1164 #endif
1166 /* These are convenience macros used to access the current trace
1167 buffer control in effect. */
1168 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1169 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1170 #define trace_buffer_end_free \
1171 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1172 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1175 /* Macro that returns a pointer to the first traceframe in the buffer. */
1177 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1179 /* Macro that returns a pointer to the next traceframe in the buffer.
1180 If the computed location is beyond the wraparound point, subtract
1181 the offset of the wraparound. */
1183 #define NEXT_TRACEFRAME_1(TF) \
1184 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1186 #define NEXT_TRACEFRAME(TF) \
1187 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1188 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1189 ? (trace_buffer_wrap - trace_buffer_lo) \
1190 : 0)))
1192 /* The difference between these counters represents the total number
1193 of complete traceframes present in the trace buffer. The IP agent
1194 writes to the write count, GDBserver writes to read count. */
1196 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1197 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1199 /* Convenience macro. */
1201 #define traceframe_count \
1202 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1204 /* The count of all traceframes created in the current run, including
1205 ones that were discarded to make room. */
1207 IP_AGENT_EXPORT_VAR int traceframes_created;
1209 #ifndef IN_PROCESS_AGENT
1211 /* Read-only regions are address ranges whose contents don't change,
1212 and so can be read from target memory even while looking at a trace
1213 frame. Without these, disassembly for instance will likely fail,
1214 because the program code is not usually collected into a trace
1215 frame. This data structure does not need to be very complicated or
1216 particularly efficient, it's only going to be used occasionally,
1217 and only by some commands. */
1219 struct readonly_region
1221 /* The bounds of the region. */
1222 CORE_ADDR start, end;
1224 /* Link to the next one. */
1225 struct readonly_region *next;
1228 /* Linked list of readonly regions. This list stays in effect from
1229 one tstart to the next. */
1231 static struct readonly_region *readonly_regions;
1233 #endif
1235 /* The global that controls tracing overall. */
1237 IP_AGENT_EXPORT_VAR int tracing;
1239 #ifndef IN_PROCESS_AGENT
1241 /* Controls whether tracing should continue after GDB disconnects. */
1243 int disconnected_tracing;
1245 /* The reason for the last tracing run to have stopped. We initialize
1246 to a distinct string so that GDB can distinguish between "stopped
1247 after running" and "stopped because never run" cases. */
1249 static const char *tracing_stop_reason = "tnotrun";
1251 static int tracing_stop_tpnum;
1253 /* 64-bit timestamps for the trace run's start and finish, expressed
1254 in microseconds from the Unix epoch. */
1256 static LONGEST tracing_start_time;
1257 static LONGEST tracing_stop_time;
1259 /* The (optional) user-supplied name of the user that started the run.
1260 This is an arbitrary string, and may be NULL. */
1262 static char *tracing_user_name;
1264 /* Optional user-supplied text describing the run. This is
1265 an arbitrary string, and may be NULL. */
1267 static char *tracing_notes;
1269 /* Optional user-supplied text explaining a tstop command. This is an
1270 arbitrary string, and may be NULL. */
1272 static char *tracing_stop_note;
1274 #endif
1276 /* Functions local to this file. */
1278 /* Base "class" for tracepoint type specific data to be passed down to
1279 collect_data_at_tracepoint. */
1280 struct tracepoint_hit_ctx
1282 enum tracepoint_type type;
1285 #ifdef IN_PROCESS_AGENT
1287 /* Fast/jump tracepoint specific data to be passed down to
1288 collect_data_at_tracepoint. */
1289 struct fast_tracepoint_ctx
1291 struct tracepoint_hit_ctx base;
1293 struct regcache regcache;
1294 int regcache_initted;
1295 unsigned char *regspace;
1297 unsigned char *regs;
1298 struct tracepoint *tpoint;
1301 /* Static tracepoint specific data to be passed down to
1302 collect_data_at_tracepoint. */
1303 struct static_tracepoint_ctx
1305 struct tracepoint_hit_ctx base;
1307 /* The regcache corresponding to the registers state at the time of
1308 the tracepoint hit. Initialized lazily, from REGS. */
1309 struct regcache regcache;
1310 int regcache_initted;
1312 /* The buffer space REGCACHE above uses. We use a separate buffer
1313 instead of letting the regcache malloc for both signal safety and
1314 performance reasons; this is allocated on the stack instead. */
1315 unsigned char *regspace;
1317 /* The register buffer as passed on by lttng/ust. */
1318 struct registers *regs;
1320 /* The "printf" formatter and the args the user passed to the marker
1321 call. We use this to be able to collect "static trace data"
1322 ($_sdata). */
1323 const char *fmt;
1324 va_list *args;
1326 /* The GDB tracepoint matching the probed marker that was "hit". */
1327 struct tracepoint *tpoint;
1330 #else
1332 /* Static tracepoint specific data to be passed down to
1333 collect_data_at_tracepoint. */
1334 struct trap_tracepoint_ctx
1336 struct tracepoint_hit_ctx base;
1338 struct regcache *regcache;
1341 #endif
1343 #ifndef IN_PROCESS_AGENT
1344 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1345 static int traceframe_read_tsv (int num, LONGEST *val);
1346 #endif
1348 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1349 struct tracepoint *tpoint);
1351 #ifndef IN_PROCESS_AGENT
1352 static void clear_readonly_regions (void);
1353 static void clear_installed_tracepoints (void);
1354 #endif
1356 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1357 CORE_ADDR stop_pc,
1358 struct tracepoint *tpoint);
1359 #ifndef IN_PROCESS_AGENT
1360 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1361 CORE_ADDR stop_pc,
1362 struct tracepoint *tpoint, int current_step);
1363 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1364 CORE_ADDR *jump_entry);
1365 #endif
1366 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1367 CORE_ADDR stop_pc,
1368 struct tracepoint *tpoint,
1369 struct traceframe *tframe,
1370 struct tracepoint_action *taction);
1372 #ifndef IN_PROCESS_AGENT
1373 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1375 static void install_tracepoint (struct tracepoint *, char *own_buf);
1376 static void download_tracepoint (struct tracepoint *);
1377 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1378 static void clone_fast_tracepoint (struct tracepoint *to,
1379 const struct tracepoint *from);
1380 #endif
1382 static LONGEST get_timestamp (void);
1384 #if defined(__GNUC__)
1385 # define memory_barrier() asm volatile ("" : : : "memory")
1386 #else
1387 # define memory_barrier() do {} while (0)
1388 #endif
1390 /* We only build the IPA if this builtin is supported, and there are
1391 no uses of this in GDBserver itself, so we're safe in defining this
1392 unconditionally. */
1393 #define cmpxchg(mem, oldval, newval) \
1394 __sync_val_compare_and_swap (mem, oldval, newval)
1396 /* Record that an error occurred during expression evaluation. */
1398 static void
1399 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1400 enum eval_result_type rtype)
1402 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1403 tpoint->number, paddress (tpoint->address), which, rtype);
1405 #ifdef IN_PROCESS_AGENT
1406 /* Only record the first error we get. */
1407 if (cmpxchg (&expr_eval_result,
1408 expr_eval_no_error,
1409 rtype) != expr_eval_no_error)
1410 return;
1411 #else
1412 if (expr_eval_result != expr_eval_no_error)
1413 return;
1414 #endif
1416 error_tracepoint = tpoint;
1419 /* Trace buffer management. */
1421 static void
1422 clear_trace_buffer (void)
1424 trace_buffer_start = trace_buffer_lo;
1425 trace_buffer_free = trace_buffer_lo;
1426 trace_buffer_end_free = trace_buffer_hi;
1427 trace_buffer_wrap = trace_buffer_hi;
1428 /* A traceframe with zeroed fields marks the end of trace data. */
1429 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1430 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1431 traceframe_read_count = traceframe_write_count = 0;
1432 traceframes_created = 0;
1435 #ifndef IN_PROCESS_AGENT
1437 static void
1438 clear_inferior_trace_buffer (void)
1440 CORE_ADDR ipa_trace_buffer_lo;
1441 CORE_ADDR ipa_trace_buffer_hi;
1442 struct traceframe ipa_traceframe = { 0 };
1443 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1445 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1446 &ipa_trace_buffer_lo);
1447 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1448 &ipa_trace_buffer_hi);
1450 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1451 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1452 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1453 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1455 /* A traceframe with zeroed fields marks the end of trace data. */
1456 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1457 (unsigned char *) &ipa_trace_buffer_ctrl,
1458 sizeof (ipa_trace_buffer_ctrl));
1460 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1462 /* A traceframe with zeroed fields marks the end of trace data. */
1463 target_write_memory (ipa_trace_buffer_lo,
1464 (unsigned char *) &ipa_traceframe,
1465 sizeof (ipa_traceframe));
1467 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1468 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1469 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1472 #endif
1474 static void
1475 init_trace_buffer (LONGEST bufsize)
1477 size_t alloc_size;
1479 trace_buffer_size = bufsize;
1481 /* Make sure to internally allocate at least space for the EOB
1482 marker. */
1483 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1484 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1485 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1487 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1489 clear_trace_buffer ();
1492 #ifdef IN_PROCESS_AGENT
1494 /* This is needed for -Wmissing-declarations. */
1495 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1497 IP_AGENT_EXPORT_FUNC void
1498 about_to_request_buffer_space (void)
1500 /* GDBserver places breakpoint here while it goes about to flush
1501 data at random times. */
1502 UNKNOWN_SIDE_EFFECTS();
1505 #endif
1507 /* Carve out a piece of the trace buffer, returning NULL in case of
1508 failure. */
1510 static void *
1511 trace_buffer_alloc (size_t amt)
1513 unsigned char *rslt;
1514 struct trace_buffer_control *tbctrl;
1515 unsigned int curr;
1516 #ifdef IN_PROCESS_AGENT
1517 unsigned int prev, prev_filtered;
1518 unsigned int commit_count;
1519 unsigned int commit;
1520 unsigned int readout;
1521 #else
1522 struct traceframe *oldest;
1523 unsigned char *new_start;
1524 #endif
1526 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1527 (long) amt, (long) sizeof (struct traceframe));
1529 /* Account for the EOB marker. */
1530 amt += TRACEFRAME_EOB_MARKER_SIZE;
1532 #ifdef IN_PROCESS_AGENT
1533 again:
1534 memory_barrier ();
1536 /* Read the current token and extract the index to try to write to,
1537 storing it in CURR. */
1538 prev = trace_buffer_ctrl_curr;
1539 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1540 curr = prev_filtered + 1;
1541 if (curr > 2)
1542 curr = 0;
1544 about_to_request_buffer_space ();
1546 /* Start out with a copy of the current state. GDBserver may be
1547 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1548 be able to commit anyway if that happens. */
1549 trace_buffer_ctrl[curr]
1550 = trace_buffer_ctrl[prev_filtered];
1551 trace_debug ("trying curr=%u", curr);
1552 #else
1553 /* The GDBserver's agent doesn't need all that syncing, and always
1554 updates TCB 0 (there's only one, mind you). */
1555 curr = 0;
1556 #endif
1557 tbctrl = &trace_buffer_ctrl[curr];
1559 /* Offsets are easier to grok for debugging than raw addresses,
1560 especially for the small trace buffer sizes that are useful for
1561 testing. */
1562 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1563 curr,
1564 (int) (tbctrl->start - trace_buffer_lo),
1565 (int) (tbctrl->free - trace_buffer_lo),
1566 (int) (tbctrl->end_free - trace_buffer_lo),
1567 (int) (tbctrl->wrap - trace_buffer_lo),
1568 (int) (trace_buffer_hi - trace_buffer_lo));
1570 /* The algorithm here is to keep trying to get a contiguous block of
1571 the requested size, possibly discarding older traceframes to free
1572 up space. Since free space might come in one or two pieces,
1573 depending on whether discarded traceframes wrapped around at the
1574 high end of the buffer, we test both pieces after each
1575 discard. */
1576 while (1)
1578 /* First, if we have two free parts, try the upper one first. */
1579 if (tbctrl->end_free < tbctrl->free)
1581 if (tbctrl->free + amt <= trace_buffer_hi)
1582 /* We have enough in the upper part. */
1583 break;
1584 else
1586 /* Our high part of free space wasn't enough. Give up
1587 on it for now, set wraparound. We will recover the
1588 space later, if/when the wrapped-around traceframe is
1589 discarded. */
1590 trace_debug ("Upper part too small, setting wraparound");
1591 tbctrl->wrap = tbctrl->free;
1592 tbctrl->free = trace_buffer_lo;
1596 /* The normal case. */
1597 if (tbctrl->free + amt <= tbctrl->end_free)
1598 break;
1600 #ifdef IN_PROCESS_AGENT
1601 /* The IP Agent's buffer is always circular. It isn't used
1602 currently, but `circular_trace_buffer' could represent
1603 GDBserver's mode. If we didn't find space, ask GDBserver to
1604 flush. */
1606 flush_trace_buffer ();
1607 memory_barrier ();
1608 if (tracing)
1610 trace_debug ("gdbserver flushed buffer, retrying");
1611 goto again;
1614 /* GDBserver cancelled the tracing. Bail out as well. */
1615 return NULL;
1616 #else
1617 /* If we're here, then neither part is big enough, and
1618 non-circular trace buffers are now full. */
1619 if (!circular_trace_buffer)
1621 trace_debug ("Not enough space in the trace buffer");
1622 return NULL;
1625 trace_debug ("Need more space in the trace buffer");
1627 /* If we have a circular buffer, we can try discarding the
1628 oldest traceframe and see if that helps. */
1629 oldest = FIRST_TRACEFRAME ();
1630 if (oldest->tpnum == 0)
1632 /* Not good; we have no traceframes to free. Perhaps we're
1633 asking for a block that is larger than the buffer? In
1634 any case, give up. */
1635 trace_debug ("No traceframes to discard");
1636 return NULL;
1639 /* We don't run this code in the in-process agent currently.
1640 E.g., we could leave the in-process agent in autonomous
1641 circular mode if we only have fast tracepoints. If we do
1642 that, then this bit becomes racy with GDBserver, which also
1643 writes to this counter. */
1644 --traceframe_write_count;
1646 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1647 /* If we freed the traceframe that wrapped around, go back
1648 to the non-wrap case. */
1649 if (new_start < tbctrl->start)
1651 trace_debug ("Discarding past the wraparound");
1652 tbctrl->wrap = trace_buffer_hi;
1654 tbctrl->start = new_start;
1655 tbctrl->end_free = tbctrl->start;
1657 trace_debug ("Discarded a traceframe\n"
1658 "Trace buffer [%d], start=%d free=%d "
1659 "endfree=%d wrap=%d hi=%d",
1660 curr,
1661 (int) (tbctrl->start - trace_buffer_lo),
1662 (int) (tbctrl->free - trace_buffer_lo),
1663 (int) (tbctrl->end_free - trace_buffer_lo),
1664 (int) (tbctrl->wrap - trace_buffer_lo),
1665 (int) (trace_buffer_hi - trace_buffer_lo));
1667 /* Now go back around the loop. The discard might have resulted
1668 in either one or two pieces of free space, so we want to try
1669 both before freeing any more traceframes. */
1670 #endif
1673 /* If we get here, we know we can provide the asked-for space. */
1675 rslt = tbctrl->free;
1677 /* Adjust the request back down, now that we know we have space for
1678 the marker, but don't commit to AMT yet, we may still need to
1679 restart the operation if GDBserver touches the trace buffer
1680 (obviously only important in the in-process agent's version). */
1681 tbctrl->free += (amt - sizeof (struct traceframe));
1683 /* Or not. If GDBserver changed the trace buffer behind our back,
1684 we get to restart a new allocation attempt. */
1686 #ifdef IN_PROCESS_AGENT
1687 /* Build the tentative token. */
1688 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1689 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1690 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1691 | commit_count
1692 | curr);
1694 /* Try to commit it. */
1695 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1696 if (readout != prev)
1698 trace_debug ("GDBserver has touched the trace buffer, restarting."
1699 " (prev=%08x, commit=%08x, readout=%08x)",
1700 prev, commit, readout);
1701 goto again;
1704 /* Hold your horses here. Even if that change was committed,
1705 GDBserver could come in, and clobber it. We need to hold to be
1706 able to tell if GDBserver clobbers before or after we committed
1707 the change. Whenever GDBserver goes about touching the IPA
1708 buffer, it sets a breakpoint in this routine, so we have a sync
1709 point here. */
1710 about_to_request_buffer_space ();
1712 /* Check if the change has been effective, even if GDBserver stopped
1713 us at the breakpoint. */
1716 unsigned int refetch;
1718 memory_barrier ();
1720 refetch = trace_buffer_ctrl_curr;
1722 if (refetch == commit
1723 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1725 /* effective */
1726 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1727 "readout=%08x, refetch=%08x)",
1728 prev, commit, readout, refetch);
1730 else
1732 trace_debug ("GDBserver has touched the trace buffer, not effective."
1733 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1734 prev, commit, readout, refetch);
1735 goto again;
1738 #endif
1740 /* We have a new piece of the trace buffer. Hurray! */
1742 /* Add an EOB marker just past this allocation. */
1743 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1744 ((struct traceframe *) tbctrl->free)->data_size = 0;
1746 /* Adjust the request back down, now that we know we have space for
1747 the marker. */
1748 amt -= sizeof (struct traceframe);
1750 if (debug_threads)
1752 trace_debug ("Allocated %d bytes", (int) amt);
1753 trace_debug ("Trace buffer [%d] start=%d free=%d "
1754 "endfree=%d wrap=%d hi=%d",
1755 curr,
1756 (int) (tbctrl->start - trace_buffer_lo),
1757 (int) (tbctrl->free - trace_buffer_lo),
1758 (int) (tbctrl->end_free - trace_buffer_lo),
1759 (int) (tbctrl->wrap - trace_buffer_lo),
1760 (int) (trace_buffer_hi - trace_buffer_lo));
1763 return rslt;
1766 #ifndef IN_PROCESS_AGENT
1768 /* Return the total free space. This is not necessarily the largest
1769 block we can allocate, because of the two-part case. */
1771 static int
1772 free_space (void)
1774 if (trace_buffer_free <= trace_buffer_end_free)
1775 return trace_buffer_end_free - trace_buffer_free;
1776 else
1777 return ((trace_buffer_end_free - trace_buffer_lo)
1778 + (trace_buffer_hi - trace_buffer_free));
1781 /* An 'S' in continuation packets indicates remainder are for
1782 while-stepping. */
1784 static int seen_step_action_flag;
1786 /* Create a tracepoint (location) with given number and address. Add this
1787 new tracepoint to list and sort this list. */
1789 static struct tracepoint *
1790 add_tracepoint (int num, CORE_ADDR addr)
1792 struct tracepoint *tpoint, **tp_next;
1794 tpoint = XNEW (struct tracepoint);
1795 tpoint->number = num;
1796 tpoint->address = addr;
1797 tpoint->numactions = 0;
1798 tpoint->actions = NULL;
1799 tpoint->actions_str = NULL;
1800 tpoint->cond = NULL;
1801 tpoint->num_step_actions = 0;
1802 tpoint->step_actions = NULL;
1803 tpoint->step_actions_str = NULL;
1804 /* Start all off as regular (slow) tracepoints. */
1805 tpoint->type = trap_tracepoint;
1806 tpoint->orig_size = -1;
1807 tpoint->source_strings = NULL;
1808 tpoint->compiled_cond = 0;
1809 tpoint->handle = NULL;
1810 tpoint->next = NULL;
1812 /* Find a place to insert this tracepoint into list in order to keep
1813 the tracepoint list still in the ascending order. There may be
1814 multiple tracepoints at the same address as TPOINT's, and this
1815 guarantees TPOINT is inserted after all the tracepoints which are
1816 set at the same address. For example, fast tracepoints A, B, C are
1817 set at the same address, and D is to be insert at the same place as
1818 well,
1820 -->| A |--> | B |-->| C |->...
1822 One jump pad was created for tracepoint A, B, and C, and the target
1823 address of A is referenced/used in jump pad. So jump pad will let
1824 inferior jump to A. If D is inserted in front of A, like this,
1826 -->| D |-->| A |--> | B |-->| C |->...
1828 without updating jump pad, D is not reachable during collect, which
1829 is wrong. As we can see, the order of B, C and D doesn't matter, but
1830 A should always be the `first' one. */
1831 for (tp_next = &tracepoints;
1832 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1833 tp_next = &(*tp_next)->next)
1835 tpoint->next = *tp_next;
1836 *tp_next = tpoint;
1837 last_tracepoint = tpoint;
1839 seen_step_action_flag = 0;
1841 return tpoint;
1844 #ifndef IN_PROCESS_AGENT
1846 /* Return the tracepoint with the given number and address, or NULL. */
1848 static struct tracepoint *
1849 find_tracepoint (int id, CORE_ADDR addr)
1851 struct tracepoint *tpoint;
1853 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1854 if (tpoint->number == id && tpoint->address == addr)
1855 return tpoint;
1857 return NULL;
1860 /* Remove TPOINT from global list. */
1862 static void
1863 remove_tracepoint (struct tracepoint *tpoint)
1865 struct tracepoint *tp, *tp_prev;
1867 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1868 tp_prev = tp, tp = tp->next)
1871 if (tp)
1873 if (tp_prev)
1874 tp_prev->next = tp->next;
1875 else
1876 tracepoints = tp->next;
1878 xfree (tp);
1882 /* There may be several tracepoints with the same number (because they
1883 are "locations", in GDB parlance); return the next one after the
1884 given tracepoint, or search from the beginning of the list if the
1885 first argument is NULL. */
1887 static struct tracepoint *
1888 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1890 struct tracepoint *tpoint;
1892 if (prev_tp)
1893 tpoint = prev_tp->next;
1894 else
1895 tpoint = tracepoints;
1896 for (; tpoint; tpoint = tpoint->next)
1897 if (tpoint->number == num)
1898 return tpoint;
1900 return NULL;
1903 #endif
1905 /* Append another action to perform when the tracepoint triggers. */
1907 static void
1908 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1910 const char *act;
1912 if (*packet == 'S')
1914 seen_step_action_flag = 1;
1915 ++packet;
1918 act = packet;
1920 while (*act)
1922 const char *act_start = act;
1923 struct tracepoint_action *action = NULL;
1925 switch (*act)
1927 case 'M':
1929 struct collect_memory_action *maction =
1930 XNEW (struct collect_memory_action);
1931 ULONGEST basereg;
1932 int is_neg;
1934 maction->base.type = *act;
1935 action = &maction->base;
1937 ++act;
1938 is_neg = (*act == '-');
1939 if (*act == '-')
1940 ++act;
1941 act = unpack_varlen_hex (act, &basereg);
1942 ++act;
1943 act = unpack_varlen_hex (act, &maction->addr);
1944 ++act;
1945 act = unpack_varlen_hex (act, &maction->len);
1946 maction->basereg = (is_neg
1947 ? - (int) basereg
1948 : (int) basereg);
1949 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1950 pulongest (maction->len),
1951 paddress (maction->addr), maction->basereg);
1952 break;
1954 case 'R':
1956 struct collect_registers_action *raction =
1957 XNEW (struct collect_registers_action);
1959 raction->base.type = *act;
1960 action = &raction->base;
1962 trace_debug ("Want to collect registers");
1963 ++act;
1964 /* skip past hex digits of mask for now */
1965 while (isxdigit(*act))
1966 ++act;
1967 break;
1969 case 'L':
1971 struct collect_static_trace_data_action *raction =
1972 XNEW (struct collect_static_trace_data_action);
1974 raction->base.type = *act;
1975 action = &raction->base;
1977 trace_debug ("Want to collect static trace data");
1978 ++act;
1979 break;
1981 case 'S':
1982 trace_debug ("Unexpected step action, ignoring");
1983 ++act;
1984 break;
1985 case 'X':
1987 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1989 xaction->base.type = *act;
1990 action = &xaction->base;
1992 trace_debug ("Want to evaluate expression");
1993 xaction->expr = gdb_parse_agent_expr (&act);
1994 break;
1996 default:
1997 trace_debug ("unknown trace action '%c', ignoring...", *act);
1998 break;
1999 case '-':
2000 break;
2003 if (action == NULL)
2004 break;
2006 if (seen_step_action_flag)
2008 tpoint->num_step_actions++;
2010 tpoint->step_actions
2011 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
2012 tpoint->num_step_actions);
2013 tpoint->step_actions_str
2014 = XRESIZEVEC (char *, tpoint->step_actions_str,
2015 tpoint->num_step_actions);
2016 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
2017 tpoint->step_actions_str[tpoint->num_step_actions - 1]
2018 = savestring (act_start, act - act_start);
2020 else
2022 tpoint->numactions++;
2023 tpoint->actions
2024 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
2025 tpoint->numactions);
2026 tpoint->actions_str
2027 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
2028 tpoint->actions[tpoint->numactions - 1] = action;
2029 tpoint->actions_str[tpoint->numactions - 1]
2030 = savestring (act_start, act - act_start);
2035 #endif
2037 /* Find or create a trace state variable with the given number. */
2039 static struct trace_state_variable *
2040 get_trace_state_variable (int num)
2042 struct trace_state_variable *tsv;
2044 #ifdef IN_PROCESS_AGENT
2045 /* Search for an existing variable. */
2046 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
2047 if (tsv->number == num)
2048 return tsv;
2049 #endif
2051 /* Search for an existing variable. */
2052 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
2053 if (tsv->number == num)
2054 return tsv;
2056 return NULL;
2059 /* Find or create a trace state variable with the given number. */
2061 static struct trace_state_variable *
2062 create_trace_state_variable (int num, int gdb)
2064 struct trace_state_variable *tsv;
2066 tsv = get_trace_state_variable (num);
2067 if (tsv != NULL)
2068 return tsv;
2070 /* Create a new variable. */
2071 tsv = XNEW (struct trace_state_variable);
2072 tsv->number = num;
2073 tsv->initial_value = 0;
2074 tsv->value = 0;
2075 tsv->getter = NULL;
2076 tsv->name = NULL;
2077 #ifdef IN_PROCESS_AGENT
2078 if (!gdb)
2080 tsv->next = alloced_trace_state_variables;
2081 alloced_trace_state_variables = tsv;
2083 else
2084 #endif
2086 tsv->next = trace_state_variables;
2087 trace_state_variables = tsv;
2089 return tsv;
2092 /* This is needed for -Wmissing-declarations. */
2093 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
2095 IP_AGENT_EXPORT_FUNC LONGEST
2096 get_trace_state_variable_value (int num)
2098 struct trace_state_variable *tsv;
2100 tsv = get_trace_state_variable (num);
2102 if (!tsv)
2104 trace_debug ("No trace state variable %d, skipping value get", num);
2105 return 0;
2108 /* Call a getter function if we have one. While it's tempting to
2109 set up something to only call the getter once per tracepoint hit,
2110 it could run afoul of thread races. Better to let the getter
2111 handle it directly, if necessary to worry about it. */
2112 if (tsv->getter)
2113 tsv->value = (tsv->getter) ();
2115 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2116 num, plongest (tsv->value));
2118 return tsv->value;
2121 /* This is needed for -Wmissing-declarations. */
2122 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
2123 LONGEST val);
2125 IP_AGENT_EXPORT_FUNC void
2126 set_trace_state_variable_value (int num, LONGEST val)
2128 struct trace_state_variable *tsv;
2130 tsv = get_trace_state_variable (num);
2132 if (!tsv)
2134 trace_debug ("No trace state variable %d, skipping value set", num);
2135 return;
2138 tsv->value = val;
2141 LONGEST
2142 agent_get_trace_state_variable_value (int num)
2144 return get_trace_state_variable_value (num);
2147 void
2148 agent_set_trace_state_variable_value (int num, LONGEST val)
2150 set_trace_state_variable_value (num, val);
2153 static void
2154 set_trace_state_variable_name (int num, const char *name)
2156 struct trace_state_variable *tsv;
2158 tsv = get_trace_state_variable (num);
2160 if (!tsv)
2162 trace_debug ("No trace state variable %d, skipping name set", num);
2163 return;
2166 tsv->name = (char *) name;
2169 static void
2170 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2172 struct trace_state_variable *tsv;
2174 tsv = get_trace_state_variable (num);
2176 if (!tsv)
2178 trace_debug ("No trace state variable %d, skipping getter set", num);
2179 return;
2182 tsv->getter = getter;
2185 /* Add a raw traceframe for the given tracepoint. */
2187 static struct traceframe *
2188 add_traceframe (struct tracepoint *tpoint)
2190 struct traceframe *tframe;
2192 tframe
2193 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2195 if (tframe == NULL)
2196 return NULL;
2198 tframe->tpnum = tpoint->number;
2199 tframe->data_size = 0;
2201 return tframe;
2204 /* Add a block to the traceframe currently being worked on. */
2206 static unsigned char *
2207 add_traceframe_block (struct traceframe *tframe,
2208 struct tracepoint *tpoint, int amt)
2210 unsigned char *block;
2212 if (!tframe)
2213 return NULL;
2215 block = (unsigned char *) trace_buffer_alloc (amt);
2217 if (!block)
2218 return NULL;
2220 gdb_assert (tframe->tpnum == tpoint->number);
2222 tframe->data_size += amt;
2223 tpoint->traceframe_usage += amt;
2225 return block;
2228 /* Flag that the current traceframe is finished. */
2230 static void
2231 finish_traceframe (struct traceframe *tframe)
2233 ++traceframe_write_count;
2234 ++traceframes_created;
2237 #ifndef IN_PROCESS_AGENT
2239 /* Given a traceframe number NUM, find the NUMth traceframe in the
2240 buffer. */
2242 static struct traceframe *
2243 find_traceframe (int num)
2245 struct traceframe *tframe;
2246 int tfnum = 0;
2248 for (tframe = FIRST_TRACEFRAME ();
2249 tframe->tpnum != 0;
2250 tframe = NEXT_TRACEFRAME (tframe))
2252 if (tfnum == num)
2253 return tframe;
2254 ++tfnum;
2257 return NULL;
2260 static CORE_ADDR
2261 get_traceframe_address (struct traceframe *tframe)
2263 CORE_ADDR addr;
2264 struct tracepoint *tpoint;
2266 addr = traceframe_get_pc (tframe);
2268 if (addr)
2269 return addr;
2271 /* Fallback strategy, will be incorrect for while-stepping frames
2272 and multi-location tracepoints. */
2273 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2274 return tpoint->address;
2277 /* Search for the next traceframe whose address is inside or outside
2278 the given range. */
2280 static struct traceframe *
2281 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2282 int *tfnump)
2284 client_state &cs = get_client_state ();
2285 struct traceframe *tframe;
2286 CORE_ADDR tfaddr;
2288 *tfnump = cs.current_traceframe + 1;
2289 tframe = find_traceframe (*tfnump);
2290 /* The search is not supposed to wrap around. */
2291 if (!tframe)
2293 *tfnump = -1;
2294 return NULL;
2297 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2299 tfaddr = get_traceframe_address (tframe);
2300 if (inside_p
2301 ? (lo <= tfaddr && tfaddr <= hi)
2302 : (lo > tfaddr || tfaddr > hi))
2303 return tframe;
2304 ++*tfnump;
2307 *tfnump = -1;
2308 return NULL;
2311 /* Search for the next traceframe recorded by the given tracepoint.
2312 Note that for multi-location tracepoints, this will find whatever
2313 location appears first. */
2315 static struct traceframe *
2316 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2318 client_state &cs = get_client_state ();
2319 struct traceframe *tframe;
2321 *tfnump = cs.current_traceframe + 1;
2322 tframe = find_traceframe (*tfnump);
2323 /* The search is not supposed to wrap around. */
2324 if (!tframe)
2326 *tfnump = -1;
2327 return NULL;
2330 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2332 if (tframe->tpnum == num)
2333 return tframe;
2334 ++*tfnump;
2337 *tfnump = -1;
2338 return NULL;
2341 #endif
2343 #ifndef IN_PROCESS_AGENT
2345 /* Clear all past trace state. */
2347 static void
2348 cmd_qtinit (char *packet)
2350 client_state &cs = get_client_state ();
2351 struct trace_state_variable *tsv, *prev, *next;
2353 /* Can't do this command without a pid attached. */
2354 if (current_thread == NULL)
2356 write_enn (packet);
2357 return;
2360 /* Make sure we don't try to read from a trace frame. */
2361 cs.current_traceframe = -1;
2363 stop_tracing ();
2365 trace_debug ("Initializing the trace");
2367 clear_installed_tracepoints ();
2368 clear_readonly_regions ();
2370 tracepoints = NULL;
2371 last_tracepoint = NULL;
2373 /* Clear out any leftover trace state variables. Ones with target
2374 defined getters should be kept however. */
2375 prev = NULL;
2376 tsv = trace_state_variables;
2377 while (tsv)
2379 trace_debug ("Looking at var %d", tsv->number);
2380 if (tsv->getter == NULL)
2382 next = tsv->next;
2383 if (prev)
2384 prev->next = next;
2385 else
2386 trace_state_variables = next;
2387 trace_debug ("Deleting var %d", tsv->number);
2388 free (tsv);
2389 tsv = next;
2391 else
2393 prev = tsv;
2394 tsv = tsv->next;
2398 clear_trace_buffer ();
2399 clear_inferior_trace_buffer ();
2401 write_ok (packet);
2404 /* Unprobe the UST marker at ADDRESS. */
2406 static void
2407 unprobe_marker_at (CORE_ADDR address)
2409 char cmd[IPA_CMD_BUF_SIZE];
2411 sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
2412 run_inferior_command (cmd, strlen (cmd) + 1);
2415 /* Restore the program to its pre-tracing state. This routine may be called
2416 in error situations, so it needs to be careful about only restoring
2417 from known-valid bits. */
2419 static void
2420 clear_installed_tracepoints (void)
2422 struct tracepoint *tpoint;
2423 struct tracepoint *prev_stpoint;
2425 target_pause_all (true);
2427 prev_stpoint = NULL;
2429 /* Restore any bytes overwritten by tracepoints. */
2430 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2432 /* Catch the case where we might try to remove a tracepoint that
2433 was never actually installed. */
2434 if (tpoint->handle == NULL)
2436 trace_debug ("Tracepoint %d at 0x%s was "
2437 "never installed, nothing to clear",
2438 tpoint->number, paddress (tpoint->address));
2439 continue;
2442 switch (tpoint->type)
2444 case trap_tracepoint:
2446 struct breakpoint *bp
2447 = (struct breakpoint *) tpoint->handle;
2449 delete_breakpoint (bp);
2451 break;
2452 case fast_tracepoint:
2454 struct fast_tracepoint_jump *jump
2455 = (struct fast_tracepoint_jump *) tpoint->handle;
2457 delete_fast_tracepoint_jump (jump);
2459 break;
2460 case static_tracepoint:
2461 if (prev_stpoint != NULL
2462 && prev_stpoint->address == tpoint->address)
2463 /* Nothing to do. We already unprobed a tracepoint set at
2464 this marker address (and there can only be one probe
2465 per marker). */
2467 else
2469 unprobe_marker_at (tpoint->address);
2470 prev_stpoint = tpoint;
2472 break;
2475 tpoint->handle = NULL;
2478 target_unpause_all (true);
2481 /* Parse a packet that defines a tracepoint. */
2483 static void
2484 cmd_qtdp (char *own_buf)
2486 int tppacket;
2487 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2488 int trail_hyphen = 0;
2489 ULONGEST num;
2490 ULONGEST addr;
2491 ULONGEST count;
2492 struct tracepoint *tpoint;
2493 const char *packet = own_buf;
2495 packet += strlen ("QTDP:");
2497 /* A hyphen at the beginning marks a packet specifying actions for a
2498 tracepoint already supplied. */
2499 tppacket = 1;
2500 if (*packet == '-')
2502 tppacket = 0;
2503 ++packet;
2505 packet = unpack_varlen_hex (packet, &num);
2506 ++packet; /* skip a colon */
2507 packet = unpack_varlen_hex (packet, &addr);
2508 ++packet; /* skip a colon */
2510 /* See if we already have this tracepoint. */
2511 tpoint = find_tracepoint (num, addr);
2513 if (tppacket)
2515 /* Duplicate tracepoints are never allowed. */
2516 if (tpoint)
2518 trace_debug ("Tracepoint error: tracepoint %d"
2519 " at 0x%s already exists",
2520 (int) num, paddress (addr));
2521 write_enn (own_buf);
2522 return;
2525 tpoint = add_tracepoint (num, addr);
2527 tpoint->enabled = (*packet == 'E');
2528 ++packet; /* skip 'E' */
2529 ++packet; /* skip a colon */
2530 packet = unpack_varlen_hex (packet, &count);
2531 tpoint->step_count = count;
2532 ++packet; /* skip a colon */
2533 packet = unpack_varlen_hex (packet, &count);
2534 tpoint->pass_count = count;
2535 /* See if we have any of the additional optional fields. */
2536 while (*packet == ':')
2538 ++packet;
2539 if (*packet == 'F')
2541 tpoint->type = fast_tracepoint;
2542 ++packet;
2543 packet = unpack_varlen_hex (packet, &count);
2544 tpoint->orig_size = count;
2546 else if (*packet == 'S')
2548 tpoint->type = static_tracepoint;
2549 ++packet;
2551 else if (*packet == 'X')
2553 tpoint->cond = gdb_parse_agent_expr (&packet);
2555 else if (*packet == '-')
2556 break;
2557 else if (*packet == '\0')
2558 break;
2559 else
2560 trace_debug ("Unknown optional tracepoint field");
2562 if (*packet == '-')
2564 trail_hyphen = 1;
2565 trace_debug ("Also has actions\n");
2568 trace_debug ("Defined %stracepoint %d at 0x%s, "
2569 "enabled %d step %" PRIu64 " pass %" PRIu64,
2570 tpoint->type == fast_tracepoint ? "fast "
2571 : tpoint->type == static_tracepoint ? "static " : "",
2572 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2573 tpoint->step_count, tpoint->pass_count);
2575 else if (tpoint)
2576 add_tracepoint_action (tpoint, packet);
2577 else
2579 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2580 (int) num, paddress (addr));
2581 write_enn (own_buf);
2582 return;
2585 /* Install tracepoint during tracing only once for each tracepoint location.
2586 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2587 determine the last QTDP packet for one tracepoint location by checking
2588 trailing hyphen in QTDP packet. */
2589 if (tracing && !trail_hyphen)
2591 struct tracepoint *tp = NULL;
2593 /* Pause all threads temporarily while we patch tracepoints. */
2594 target_pause_all (false);
2596 /* download_tracepoint will update global `tracepoints'
2597 list, so it is unsafe to leave threads in jump pad. */
2598 target_stabilize_threads ();
2600 /* Freeze threads. */
2601 target_pause_all (true);
2604 if (tpoint->type != trap_tracepoint)
2606 /* Find another fast or static tracepoint at the same address. */
2607 for (tp = tracepoints; tp; tp = tp->next)
2609 if (tp->address == tpoint->address && tp->type == tpoint->type
2610 && tp->number != tpoint->number)
2611 break;
2614 /* TPOINT is installed at the same address as TP. */
2615 if (tp)
2617 if (tpoint->type == fast_tracepoint)
2618 clone_fast_tracepoint (tpoint, tp);
2619 else if (tpoint->type == static_tracepoint)
2620 tpoint->handle = (void *) -1;
2624 if (use_agent && tpoint->type == fast_tracepoint
2625 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2627 /* Download and install fast tracepoint by agent. */
2628 if (tracepoint_send_agent (tpoint) == 0)
2629 write_ok (own_buf);
2630 else
2632 write_enn (own_buf);
2633 remove_tracepoint (tpoint);
2636 else
2638 download_tracepoint (tpoint);
2640 if (tpoint->type == trap_tracepoint || tp == NULL)
2642 install_tracepoint (tpoint, own_buf);
2643 if (strcmp (own_buf, "OK") != 0)
2644 remove_tracepoint (tpoint);
2646 else
2647 write_ok (own_buf);
2650 target_unpause_all (true);
2651 return;
2654 write_ok (own_buf);
2657 static void
2658 cmd_qtdpsrc (char *own_buf)
2660 ULONGEST num, addr, start, slen;
2661 struct tracepoint *tpoint;
2662 const char *packet = own_buf;
2663 const char *saved;
2664 char *srctype, *src;
2665 size_t nbytes;
2666 struct source_string *last, *newlast;
2668 packet += strlen ("QTDPsrc:");
2670 packet = unpack_varlen_hex (packet, &num);
2671 ++packet; /* skip a colon */
2672 packet = unpack_varlen_hex (packet, &addr);
2673 ++packet; /* skip a colon */
2675 /* See if we already have this tracepoint. */
2676 tpoint = find_tracepoint (num, addr);
2678 if (!tpoint)
2680 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2681 (int) num, paddress (addr));
2682 write_enn (own_buf);
2683 return;
2686 saved = packet;
2687 packet = strchr (packet, ':');
2688 srctype = (char *) xmalloc (packet - saved + 1);
2689 memcpy (srctype, saved, packet - saved);
2690 srctype[packet - saved] = '\0';
2691 ++packet;
2692 packet = unpack_varlen_hex (packet, &start);
2693 ++packet; /* skip a colon */
2694 packet = unpack_varlen_hex (packet, &slen);
2695 ++packet; /* skip a colon */
2696 src = (char *) xmalloc (slen + 1);
2697 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2698 src[nbytes] = '\0';
2700 newlast = XNEW (struct source_string);
2701 newlast->type = srctype;
2702 newlast->str = src;
2703 newlast->next = NULL;
2704 /* Always add a source string to the end of the list;
2705 this keeps sequences of actions/commands in the right
2706 order. */
2707 if (tpoint->source_strings)
2709 for (last = tpoint->source_strings; last->next; last = last->next)
2711 last->next = newlast;
2713 else
2714 tpoint->source_strings = newlast;
2716 write_ok (own_buf);
2719 static void
2720 cmd_qtdv (char *own_buf)
2722 ULONGEST num, val, builtin;
2723 char *varname;
2724 size_t nbytes;
2725 struct trace_state_variable *tsv;
2726 const char *packet = own_buf;
2728 packet += strlen ("QTDV:");
2730 packet = unpack_varlen_hex (packet, &num);
2731 ++packet; /* skip a colon */
2732 packet = unpack_varlen_hex (packet, &val);
2733 ++packet; /* skip a colon */
2734 packet = unpack_varlen_hex (packet, &builtin);
2735 ++packet; /* skip a colon */
2737 nbytes = strlen (packet) / 2;
2738 varname = (char *) xmalloc (nbytes + 1);
2739 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2740 varname[nbytes] = '\0';
2742 tsv = create_trace_state_variable (num, 1);
2743 tsv->initial_value = (LONGEST) val;
2744 tsv->name = varname;
2746 set_trace_state_variable_value (num, (LONGEST) val);
2748 write_ok (own_buf);
2751 static void
2752 cmd_qtenable_disable (char *own_buf, int enable)
2754 const char *packet = own_buf;
2755 ULONGEST num, addr;
2756 struct tracepoint *tp;
2758 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2759 packet = unpack_varlen_hex (packet, &num);
2760 ++packet; /* skip a colon */
2761 packet = unpack_varlen_hex (packet, &addr);
2763 tp = find_tracepoint (num, addr);
2765 if (tp)
2767 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2769 trace_debug ("Tracepoint %d at 0x%s is already %s",
2770 (int) num, paddress (addr),
2771 enable ? "enabled" : "disabled");
2772 write_ok (own_buf);
2773 return;
2776 trace_debug ("%s tracepoint %d at 0x%s",
2777 enable ? "Enabling" : "Disabling",
2778 (int) num, paddress (addr));
2780 tp->enabled = enable;
2782 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
2784 int offset = offsetof (struct tracepoint, enabled);
2785 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2787 int ret = write_inferior_int8 (obj_addr, enable);
2788 if (ret)
2790 trace_debug ("Cannot write enabled flag into "
2791 "inferior process memory");
2792 write_enn (own_buf);
2793 return;
2797 write_ok (own_buf);
2799 else
2801 trace_debug ("Tracepoint %d at 0x%s not found",
2802 (int) num, paddress (addr));
2803 write_enn (own_buf);
2807 static void
2808 cmd_qtv (char *own_buf)
2810 client_state &cs = get_client_state ();
2811 ULONGEST num;
2812 LONGEST val = 0;
2813 int err;
2814 char *packet = own_buf;
2816 packet += strlen ("qTV:");
2817 unpack_varlen_hex (packet, &num);
2819 if (cs.current_traceframe >= 0)
2821 err = traceframe_read_tsv ((int) num, &val);
2822 if (err)
2824 strcpy (own_buf, "U");
2825 return;
2828 /* Only make tsv's be undefined before the first trace run. After a
2829 trace run is over, the user might want to see the last value of
2830 the tsv, and it might not be available in a traceframe. */
2831 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2833 strcpy (own_buf, "U");
2834 return;
2836 else
2837 val = get_trace_state_variable_value (num);
2839 sprintf (own_buf, "V%s", phex_nz (val, 0));
2842 /* Clear out the list of readonly regions. */
2844 static void
2845 clear_readonly_regions (void)
2847 struct readonly_region *roreg;
2849 while (readonly_regions)
2851 roreg = readonly_regions;
2852 readonly_regions = readonly_regions->next;
2853 free (roreg);
2857 /* Parse the collection of address ranges whose contents GDB believes
2858 to be unchanging and so can be read directly from target memory
2859 even while looking at a traceframe. */
2861 static void
2862 cmd_qtro (char *own_buf)
2864 ULONGEST start, end;
2865 struct readonly_region *roreg;
2866 const char *packet = own_buf;
2868 trace_debug ("Want to mark readonly regions");
2870 clear_readonly_regions ();
2872 packet += strlen ("QTro");
2874 while (*packet == ':')
2876 ++packet; /* skip a colon */
2877 packet = unpack_varlen_hex (packet, &start);
2878 ++packet; /* skip a comma */
2879 packet = unpack_varlen_hex (packet, &end);
2881 roreg = XNEW (struct readonly_region);
2882 roreg->start = start;
2883 roreg->end = end;
2884 roreg->next = readonly_regions;
2885 readonly_regions = roreg;
2886 trace_debug ("Added readonly region from 0x%s to 0x%s",
2887 paddress (roreg->start), paddress (roreg->end));
2890 write_ok (own_buf);
2893 /* Test to see if the given range is in our list of readonly ranges.
2894 We only test for being entirely within a range, GDB is not going to
2895 send a single memory packet that spans multiple regions. */
2898 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2900 struct readonly_region *roreg;
2902 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2903 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2904 return 1;
2906 return 0;
2909 static CORE_ADDR gdb_jump_pad_head;
2911 /* Return the address of the next free jump space. */
2913 static CORE_ADDR
2914 get_jump_space_head (void)
2916 if (gdb_jump_pad_head == 0)
2918 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2919 &gdb_jump_pad_head))
2921 internal_error ("error extracting jump_pad_buffer");
2925 return gdb_jump_pad_head;
2928 /* Reserve USED bytes from the jump space. */
2930 static void
2931 claim_jump_space (ULONGEST used)
2933 trace_debug ("claim_jump_space reserves %s bytes at %s",
2934 pulongest (used), paddress (gdb_jump_pad_head));
2935 gdb_jump_pad_head += used;
2938 static CORE_ADDR trampoline_buffer_head = 0;
2939 static CORE_ADDR trampoline_buffer_tail;
2941 /* Reserve USED bytes from the trampoline buffer and return the
2942 address of the start of the reserved space in TRAMPOLINE. Returns
2943 non-zero if the space is successfully claimed. */
2946 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2948 if (!trampoline_buffer_head)
2950 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2951 &trampoline_buffer_tail))
2953 internal_error ("error extracting trampoline_buffer");
2956 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2957 &trampoline_buffer_head))
2959 internal_error ("error extracting trampoline_buffer_end");
2963 /* Start claiming space from the top of the trampoline space. If
2964 the space is located at the bottom of the virtual address space,
2965 this reduces the possibility that corruption will occur if a null
2966 pointer is used to write to memory. */
2967 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2969 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2970 pulongest (used));
2971 return 0;
2974 trampoline_buffer_head -= used;
2976 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2977 pulongest (used), paddress (trampoline_buffer_head));
2979 *trampoline = trampoline_buffer_head;
2980 return 1;
2983 /* Returns non-zero if there is space allocated for use in trampolines
2984 for fast tracepoints. */
2987 have_fast_tracepoint_trampoline_buffer (char *buf)
2989 CORE_ADDR trampoline_end, errbuf;
2991 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2992 &trampoline_end))
2994 internal_error ("error extracting trampoline_buffer_end");
2997 if (buf)
2999 buf[0] = '\0';
3000 strcpy (buf, "was claiming");
3001 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
3002 &errbuf))
3004 internal_error ("error extracting errbuf");
3007 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
3010 return trampoline_end != 0;
3013 /* Ask the IPA to probe the marker at ADDRESS. Returns -1 if running
3014 the command fails, or 0 otherwise. If the command ran
3015 successfully, but probing the marker failed, ERROUT will be filled
3016 with the error to reply to GDB, and -1 is also returned. This
3017 allows directly passing IPA errors to GDB. */
3019 static int
3020 probe_marker_at (CORE_ADDR address, char *errout)
3022 char cmd[IPA_CMD_BUF_SIZE];
3023 int err;
3025 sprintf (cmd, "probe_marker_at:%s", paddress (address));
3026 err = run_inferior_command (cmd, strlen (cmd) + 1);
3028 if (err == 0)
3030 if (*cmd == 'E')
3032 strcpy (errout, cmd);
3033 return -1;
3037 return err;
3040 static void
3041 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
3043 to->jump_pad = from->jump_pad;
3044 to->jump_pad_end = from->jump_pad_end;
3045 to->trampoline = from->trampoline;
3046 to->trampoline_end = from->trampoline_end;
3047 to->adjusted_insn_addr = from->adjusted_insn_addr;
3048 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
3049 to->handle = from->handle;
3051 gdb_assert (from->handle);
3052 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
3055 #define MAX_JUMP_SIZE 20
3057 /* Install fast tracepoint. Return 0 if successful, otherwise return
3058 non-zero. */
3060 static int
3061 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
3063 CORE_ADDR jentry, jump_entry;
3064 CORE_ADDR trampoline;
3065 CORE_ADDR collect;
3066 ULONGEST trampoline_size;
3067 int err = 0;
3068 /* The jump to the jump pad of the last fast tracepoint
3069 installed. */
3070 unsigned char fjump[MAX_JUMP_SIZE];
3071 ULONGEST fjump_size;
3073 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
3075 trace_debug ("Requested a fast tracepoint on an instruction "
3076 "that is of less than the minimum length.");
3077 return 0;
3080 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
3081 &collect))
3083 error ("error extracting gdb_collect_ptr");
3084 return 1;
3087 jentry = jump_entry = get_jump_space_head ();
3089 trampoline = 0;
3090 trampoline_size = 0;
3092 /* Install the jump pad. */
3093 err = target_install_fast_tracepoint_jump_pad
3094 (tpoint->obj_addr_on_target, tpoint->address, collect,
3095 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
3096 &trampoline, &trampoline_size, fjump, &fjump_size,
3097 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
3099 if (err)
3100 return 1;
3102 /* Wire it in. */
3103 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
3104 fjump_size);
3106 if (tpoint->handle != NULL)
3108 tpoint->jump_pad = jump_entry;
3109 tpoint->jump_pad_end = jentry;
3110 tpoint->trampoline = trampoline;
3111 tpoint->trampoline_end = trampoline + trampoline_size;
3113 /* Pad to 8-byte alignment. */
3114 jentry = ((jentry + 7) & ~0x7);
3115 claim_jump_space (jentry - jump_entry);
3118 return 0;
3122 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
3124 static void
3125 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
3127 tpoint->handle = NULL;
3128 *own_buf = '\0';
3130 if (tpoint->type == trap_tracepoint)
3132 /* Tracepoints are installed as memory breakpoints. Just go
3133 ahead and install the trap. The breakpoints module
3134 handles duplicated breakpoints, and the memory read
3135 routine handles un-patching traps from memory reads. */
3136 tpoint->handle = set_breakpoint_at (tpoint->address,
3137 tracepoint_handler);
3139 else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
3141 if (!agent_loaded_p ())
3143 trace_debug ("Requested a %s tracepoint, but fast "
3144 "tracepoints aren't supported.",
3145 tpoint->type == static_tracepoint ? "static" : "fast");
3146 write_e_ipa_not_loaded (own_buf);
3147 return;
3149 if (tpoint->type == static_tracepoint
3150 && !in_process_agent_supports_ust ())
3152 trace_debug ("Requested a static tracepoint, but static "
3153 "tracepoints are not supported.");
3154 write_e_ust_not_loaded (own_buf);
3155 return;
3158 if (tpoint->type == fast_tracepoint)
3159 install_fast_tracepoint (tpoint, own_buf);
3160 else
3162 if (probe_marker_at (tpoint->address, own_buf) == 0)
3163 tpoint->handle = (void *) -1;
3167 else
3168 internal_error ("Unknown tracepoint type");
3170 if (tpoint->handle == NULL)
3172 if (*own_buf == '\0')
3173 write_enn (own_buf);
3175 else
3176 write_ok (own_buf);
3179 static void download_tracepoint_1 (struct tracepoint *tpoint);
3181 static void
3182 cmd_qtstart (char *packet)
3184 struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
3185 CORE_ADDR tpptr = 0, prev_tpptr = 0;
3187 trace_debug ("Starting the trace");
3189 /* Pause all threads temporarily while we patch tracepoints. */
3190 target_pause_all (false);
3192 /* Get threads out of jump pads. Safe to do here, since this is a
3193 top level command. And, required to do here, since we're
3194 deleting/rewriting jump pads. */
3196 target_stabilize_threads ();
3198 /* Freeze threads. */
3199 target_pause_all (true);
3201 /* Sync the fast tracepoints list in the inferior ftlib. */
3202 if (agent_loaded_p ())
3203 download_trace_state_variables ();
3205 /* No previous fast tpoint yet. */
3206 prev_ftpoint = NULL;
3208 /* No previous static tpoint yet. */
3209 prev_stpoint = NULL;
3211 *packet = '\0';
3213 if (agent_loaded_p ())
3215 /* Tell IPA about the correct tdesc. */
3216 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
3217 target_get_ipa_tdesc_idx ()))
3218 error ("Error setting ipa_tdesc_idx variable in lib");
3221 /* Start out empty. */
3222 if (agent_loaded_p ())
3223 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
3225 /* Download and install tracepoints. */
3226 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3228 /* Ensure all the hit counts start at zero. */
3229 tpoint->hit_count = 0;
3230 tpoint->traceframe_usage = 0;
3232 if (tpoint->type == trap_tracepoint)
3234 /* Tracepoints are installed as memory breakpoints. Just go
3235 ahead and install the trap. The breakpoints module
3236 handles duplicated breakpoints, and the memory read
3237 routine handles un-patching traps from memory reads. */
3238 tpoint->handle = set_breakpoint_at (tpoint->address,
3239 tracepoint_handler);
3241 else if (tpoint->type == fast_tracepoint
3242 || tpoint->type == static_tracepoint)
3244 if (maybe_write_ipa_not_loaded (packet))
3246 trace_debug ("Requested a %s tracepoint, but fast "
3247 "tracepoints aren't supported.",
3248 tpoint->type == static_tracepoint
3249 ? "static" : "fast");
3250 break;
3253 if (tpoint->type == fast_tracepoint)
3255 int use_agent_p
3256 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3258 if (prev_ftpoint != NULL
3259 && prev_ftpoint->address == tpoint->address)
3261 if (use_agent_p)
3262 tracepoint_send_agent (tpoint);
3263 else
3264 download_tracepoint_1 (tpoint);
3266 clone_fast_tracepoint (tpoint, prev_ftpoint);
3268 else
3270 /* Tracepoint is installed successfully? */
3271 int installed = 0;
3273 /* Download and install fast tracepoint by agent. */
3274 if (use_agent_p)
3275 installed = !tracepoint_send_agent (tpoint);
3276 else
3278 download_tracepoint_1 (tpoint);
3279 installed = !install_fast_tracepoint (tpoint, packet);
3282 if (installed)
3283 prev_ftpoint = tpoint;
3286 else
3288 if (!in_process_agent_supports_ust ())
3290 trace_debug ("Requested a static tracepoint, but static "
3291 "tracepoints are not supported.");
3292 break;
3295 download_tracepoint_1 (tpoint);
3296 /* Can only probe a given marker once. */
3297 if (prev_stpoint != NULL
3298 && prev_stpoint->address == tpoint->address)
3299 tpoint->handle = (void *) -1;
3300 else
3302 if (probe_marker_at (tpoint->address, packet) == 0)
3304 tpoint->handle = (void *) -1;
3306 /* So that we can handle multiple static tracepoints
3307 at the same address easily. */
3308 prev_stpoint = tpoint;
3313 prev_tpptr = tpptr;
3314 tpptr = tpoint->obj_addr_on_target;
3316 if (tpoint == tracepoints)
3317 /* First object in list, set the head pointer in the
3318 inferior. */
3319 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3320 else
3321 write_inferior_data_pointer (prev_tpptr
3322 + offsetof (struct tracepoint, next),
3323 tpptr);
3326 /* Any failure in the inner loop is sufficient cause to give
3327 up. */
3328 if (tpoint->handle == NULL)
3329 break;
3332 /* Any error in tracepoint insertion is unacceptable; better to
3333 address the problem now, than end up with a useless or misleading
3334 trace run. */
3335 if (tpoint != NULL)
3337 clear_installed_tracepoints ();
3338 if (*packet == '\0')
3339 write_enn (packet);
3340 target_unpause_all (true);
3341 return;
3344 stopping_tracepoint = NULL;
3345 trace_buffer_is_full = 0;
3346 expr_eval_result = expr_eval_no_error;
3347 error_tracepoint = NULL;
3348 tracing_start_time = get_timestamp ();
3350 /* Tracing is now active, hits will now start being logged. */
3351 tracing = 1;
3353 if (agent_loaded_p ())
3355 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3357 internal_error ("Error setting tracing variable in lib");
3360 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3363 internal_error ("Error clearing stopping_tracepoint variable"
3364 " in lib");
3367 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3369 internal_error ("Error clearing trace_buffer_is_full variable"
3370 " in lib");
3373 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3374 stop_tracing_handler);
3375 if (stop_tracing_bkpt == NULL)
3376 error ("Error setting stop_tracing breakpoint");
3378 flush_trace_buffer_bkpt
3379 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3380 flush_trace_buffer_handler);
3381 if (flush_trace_buffer_bkpt == NULL)
3382 error ("Error setting flush_trace_buffer breakpoint");
3385 target_unpause_all (true);
3387 write_ok (packet);
3390 /* End a tracing run, filling in a stop reason to report back to GDB,
3391 and removing the tracepoints from the code. */
3393 void
3394 stop_tracing (void)
3396 if (!tracing)
3398 trace_debug ("Tracing is already off, ignoring");
3399 return;
3402 trace_debug ("Stopping the trace");
3404 /* Pause all threads before removing fast jumps from memory,
3405 breakpoints, and touching IPA state variables (inferior memory).
3406 Some thread may hit the internal tracing breakpoints, or be
3407 collecting this moment, but that's ok, we don't release the
3408 tpoint object's memory or the jump pads here (we only do that
3409 when we're sure we can move all threads out of the jump pads).
3410 We can't now, since we may be getting here due to the inferior
3411 agent calling us. */
3412 target_pause_all (true);
3414 /* Stop logging. Tracepoints can still be hit, but they will not be
3415 recorded. */
3416 tracing = 0;
3417 if (agent_loaded_p ())
3419 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3421 internal_error ("Error clearing tracing variable in lib");
3425 tracing_stop_time = get_timestamp ();
3426 tracing_stop_reason = "t???";
3427 tracing_stop_tpnum = 0;
3428 if (stopping_tracepoint)
3430 trace_debug ("Stopping the trace because "
3431 "tracepoint %d was hit %" PRIu64 " times",
3432 stopping_tracepoint->number,
3433 stopping_tracepoint->pass_count);
3434 tracing_stop_reason = "tpasscount";
3435 tracing_stop_tpnum = stopping_tracepoint->number;
3437 else if (trace_buffer_is_full)
3439 trace_debug ("Stopping the trace because the trace buffer is full");
3440 tracing_stop_reason = "tfull";
3442 else if (expr_eval_result != expr_eval_no_error)
3444 trace_debug ("Stopping the trace because of an expression eval error");
3445 tracing_stop_reason = eval_result_names[expr_eval_result];
3446 tracing_stop_tpnum = error_tracepoint->number;
3448 #ifndef IN_PROCESS_AGENT
3449 else if (!gdb_connected ())
3451 trace_debug ("Stopping the trace because GDB disconnected");
3452 tracing_stop_reason = "tdisconnected";
3454 #endif
3455 else
3457 trace_debug ("Stopping the trace because of a tstop command");
3458 tracing_stop_reason = "tstop";
3461 stopping_tracepoint = NULL;
3462 error_tracepoint = NULL;
3464 /* Clear out the tracepoints. */
3465 clear_installed_tracepoints ();
3467 if (agent_loaded_p ())
3469 /* Pull in fast tracepoint trace frames from the inferior lib
3470 buffer into our buffer, even if our buffer is already full,
3471 because we want to present the full number of created frames
3472 in addition to what fit in the trace buffer. */
3473 upload_fast_traceframes ();
3476 if (stop_tracing_bkpt != NULL)
3478 delete_breakpoint (stop_tracing_bkpt);
3479 stop_tracing_bkpt = NULL;
3482 if (flush_trace_buffer_bkpt != NULL)
3484 delete_breakpoint (flush_trace_buffer_bkpt);
3485 flush_trace_buffer_bkpt = NULL;
3488 target_unpause_all (true);
3491 static int
3492 stop_tracing_handler (CORE_ADDR addr)
3494 trace_debug ("lib hit stop_tracing");
3496 /* Don't actually handle it here. When we stop tracing we remove
3497 breakpoints from the inferior, and that is not allowed in a
3498 breakpoint handler (as the caller is walking the breakpoint
3499 list). */
3500 return 0;
3503 static int
3504 flush_trace_buffer_handler (CORE_ADDR addr)
3506 trace_debug ("lib hit flush_trace_buffer");
3507 return 0;
3510 static void
3511 cmd_qtstop (char *packet)
3513 stop_tracing ();
3514 write_ok (packet);
3517 static void
3518 cmd_qtdisconnected (char *own_buf)
3520 ULONGEST setting;
3521 char *packet = own_buf;
3523 packet += strlen ("QTDisconnected:");
3525 unpack_varlen_hex (packet, &setting);
3527 write_ok (own_buf);
3529 disconnected_tracing = setting;
3532 static void
3533 cmd_qtframe (char *own_buf)
3535 client_state &cs = get_client_state ();
3536 ULONGEST frame, pc, lo, hi, num;
3537 int tfnum, tpnum;
3538 struct traceframe *tframe;
3539 const char *packet = own_buf;
3541 packet += strlen ("QTFrame:");
3543 if (startswith (packet, "pc:"))
3545 packet += strlen ("pc:");
3546 unpack_varlen_hex (packet, &pc);
3547 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3548 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3550 else if (startswith (packet, "range:"))
3552 packet += strlen ("range:");
3553 packet = unpack_varlen_hex (packet, &lo);
3554 ++packet;
3555 unpack_varlen_hex (packet, &hi);
3556 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3557 paddress (lo), paddress (hi));
3558 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3560 else if (startswith (packet, "outside:"))
3562 packet += strlen ("outside:");
3563 packet = unpack_varlen_hex (packet, &lo);
3564 ++packet;
3565 unpack_varlen_hex (packet, &hi);
3566 trace_debug ("Want to find next traceframe "
3567 "outside the range 0x%s to 0x%s",
3568 paddress (lo), paddress (hi));
3569 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3571 else if (startswith (packet, "tdp:"))
3573 packet += strlen ("tdp:");
3574 unpack_varlen_hex (packet, &num);
3575 tpnum = (int) num;
3576 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3577 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3579 else
3581 unpack_varlen_hex (packet, &frame);
3582 tfnum = (int) frame;
3583 if (tfnum == -1)
3585 trace_debug ("Want to stop looking at traceframes");
3586 cs.current_traceframe = -1;
3587 write_ok (own_buf);
3588 return;
3590 trace_debug ("Want to look at traceframe %d", tfnum);
3591 tframe = find_traceframe (tfnum);
3594 if (tframe)
3596 cs.current_traceframe = tfnum;
3597 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3599 else
3600 sprintf (own_buf, "F-1");
3603 static void
3604 cmd_qtstatus (char *packet)
3606 char *stop_reason_rsp = NULL;
3607 char *buf1, *buf2, *buf3;
3608 const char *str;
3609 int slen;
3611 /* Translate the plain text of the notes back into hex for
3612 transmission. */
3614 str = (tracing_user_name ? tracing_user_name : "");
3615 slen = strlen (str);
3616 buf1 = (char *) alloca (slen * 2 + 1);
3617 bin2hex ((gdb_byte *) str, buf1, slen);
3619 str = (tracing_notes ? tracing_notes : "");
3620 slen = strlen (str);
3621 buf2 = (char *) alloca (slen * 2 + 1);
3622 bin2hex ((gdb_byte *) str, buf2, slen);
3624 str = (tracing_stop_note ? tracing_stop_note : "");
3625 slen = strlen (str);
3626 buf3 = (char *) alloca (slen * 2 + 1);
3627 bin2hex ((gdb_byte *) str, buf3, slen);
3629 trace_debug ("Returning trace status as %d, stop reason %s",
3630 tracing, tracing_stop_reason);
3632 if (agent_loaded_p ())
3634 target_pause_all (true);
3636 upload_fast_traceframes ();
3638 target_unpause_all (true);
3641 stop_reason_rsp = (char *) tracing_stop_reason;
3643 /* The user visible error string in terror needs to be hex encoded.
3644 We leave it as plain string in `tracing_stop_reason' to ease
3645 debugging. */
3646 if (startswith (stop_reason_rsp, "terror:"))
3648 const char *result_name;
3649 int hexstr_len;
3650 char *p;
3652 result_name = stop_reason_rsp + strlen ("terror:");
3653 hexstr_len = strlen (result_name) * 2;
3654 p = stop_reason_rsp
3655 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3656 strcpy (p, "terror:");
3657 p += strlen (p);
3658 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3661 /* If this was a forced stop, include any stop note that was supplied. */
3662 if (strcmp (stop_reason_rsp, "tstop") == 0)
3664 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3665 strcpy (stop_reason_rsp, "tstop:");
3666 strcat (stop_reason_rsp, buf3);
3669 sprintf (packet,
3670 "T%d;"
3671 "%s:%x;"
3672 "tframes:%x;tcreated:%x;"
3673 "tfree:%x;tsize:%s;"
3674 "circular:%d;"
3675 "disconn:%d;"
3676 "starttime:%s;stoptime:%s;"
3677 "username:%s;notes:%s:",
3678 tracing ? 1 : 0,
3679 stop_reason_rsp, tracing_stop_tpnum,
3680 traceframe_count, traceframes_created,
3681 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3682 circular_trace_buffer,
3683 disconnected_tracing,
3684 phex_nz (tracing_start_time, sizeof (tracing_start_time)),
3685 phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
3686 buf1, buf2);
3689 static void
3690 cmd_qtp (char *own_buf)
3692 ULONGEST num, addr;
3693 struct tracepoint *tpoint;
3694 const char *packet = own_buf;
3696 packet += strlen ("qTP:");
3698 packet = unpack_varlen_hex (packet, &num);
3699 ++packet; /* skip a colon */
3700 packet = unpack_varlen_hex (packet, &addr);
3702 /* See if we already have this tracepoint. */
3703 tpoint = find_tracepoint (num, addr);
3705 if (!tpoint)
3707 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3708 (int) num, paddress (addr));
3709 write_enn (own_buf);
3710 return;
3713 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3714 tpoint->traceframe_usage);
3717 /* State variables to help return all the tracepoint bits. */
3718 static struct tracepoint *cur_tpoint;
3719 static unsigned int cur_action;
3720 static unsigned int cur_step_action;
3721 static struct source_string *cur_source_string;
3722 static struct trace_state_variable *cur_tsv;
3724 /* Compose a response that is an imitation of the syntax by which the
3725 tracepoint was originally downloaded. */
3727 static void
3728 response_tracepoint (char *packet, struct tracepoint *tpoint)
3730 char *buf;
3732 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3733 paddress (tpoint->address),
3734 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3735 tpoint->pass_count);
3736 if (tpoint->type == fast_tracepoint)
3737 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3738 else if (tpoint->type == static_tracepoint)
3739 sprintf (packet + strlen (packet), ":S");
3741 if (tpoint->cond)
3743 buf = gdb_unparse_agent_expr (tpoint->cond);
3744 sprintf (packet + strlen (packet), ":X%x,%s",
3745 tpoint->cond->length, buf);
3746 free (buf);
3750 /* Compose a response that is an imitation of the syntax by which the
3751 tracepoint action was originally downloaded (with the difference
3752 that due to the way we store the actions, this will output a packet
3753 per action, while GDB could have combined more than one action
3754 per-packet. */
3756 static void
3757 response_action (char *packet, struct tracepoint *tpoint,
3758 char *taction, int step)
3760 sprintf (packet, "%c%x:%s:%s",
3761 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3762 taction);
3765 /* Compose a response that is an imitation of the syntax by which the
3766 tracepoint source piece was originally downloaded. */
3768 static void
3769 response_source (char *packet,
3770 struct tracepoint *tpoint, struct source_string *src)
3772 char *buf;
3773 int len;
3775 len = strlen (src->str);
3776 buf = (char *) alloca (len * 2 + 1);
3777 bin2hex ((gdb_byte *) src->str, buf, len);
3779 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3780 tpoint->number, paddress (tpoint->address),
3781 src->type, 0, len, buf);
3784 /* Return the first piece of tracepoint definition, and initialize the
3785 state machine that will iterate through all the tracepoint
3786 bits. */
3788 static void
3789 cmd_qtfp (char *packet)
3791 trace_debug ("Returning first tracepoint definition piece");
3793 cur_tpoint = tracepoints;
3794 cur_action = cur_step_action = 0;
3795 cur_source_string = NULL;
3797 if (cur_tpoint)
3798 response_tracepoint (packet, cur_tpoint);
3799 else
3800 strcpy (packet, "l");
3803 /* Return additional pieces of tracepoint definition. Each action and
3804 stepping action must go into its own packet, because of packet size
3805 limits, and so we use state variables to deliver one piece at a
3806 time. */
3808 static void
3809 cmd_qtsp (char *packet)
3811 trace_debug ("Returning subsequent tracepoint definition piece");
3813 if (!cur_tpoint)
3815 /* This case would normally never occur, but be prepared for
3816 GDB misbehavior. */
3817 strcpy (packet, "l");
3819 else if (cur_action < cur_tpoint->numactions)
3821 response_action (packet, cur_tpoint,
3822 cur_tpoint->actions_str[cur_action], 0);
3823 ++cur_action;
3825 else if (cur_step_action < cur_tpoint->num_step_actions)
3827 response_action (packet, cur_tpoint,
3828 cur_tpoint->step_actions_str[cur_step_action], 1);
3829 ++cur_step_action;
3831 else if ((cur_source_string
3832 ? cur_source_string->next
3833 : cur_tpoint->source_strings))
3835 if (cur_source_string)
3836 cur_source_string = cur_source_string->next;
3837 else
3838 cur_source_string = cur_tpoint->source_strings;
3839 response_source (packet, cur_tpoint, cur_source_string);
3841 else
3843 cur_tpoint = cur_tpoint->next;
3844 cur_action = cur_step_action = 0;
3845 cur_source_string = NULL;
3846 if (cur_tpoint)
3847 response_tracepoint (packet, cur_tpoint);
3848 else
3849 strcpy (packet, "l");
3853 /* Compose a response that is an imitation of the syntax by which the
3854 trace state variable was originally downloaded. */
3856 static void
3857 response_tsv (char *packet, struct trace_state_variable *tsv)
3859 char *buf = (char *) "";
3860 int namelen;
3862 if (tsv->name)
3864 namelen = strlen (tsv->name);
3865 buf = (char *) alloca (namelen * 2 + 1);
3866 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3869 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3870 tsv->getter ? 1 : 0, buf);
3873 /* Return the first trace state variable definition, and initialize
3874 the state machine that will iterate through all the tsv bits. */
3876 static void
3877 cmd_qtfv (char *packet)
3879 trace_debug ("Returning first trace state variable definition");
3881 cur_tsv = trace_state_variables;
3883 if (cur_tsv)
3884 response_tsv (packet, cur_tsv);
3885 else
3886 strcpy (packet, "l");
3889 /* Return additional trace state variable definitions. */
3891 static void
3892 cmd_qtsv (char *packet)
3894 trace_debug ("Returning additional trace state variable definition");
3896 if (cur_tsv)
3898 cur_tsv = cur_tsv->next;
3899 if (cur_tsv)
3900 response_tsv (packet, cur_tsv);
3901 else
3902 strcpy (packet, "l");
3904 else
3905 strcpy (packet, "l");
3908 /* Return the first static tracepoint marker, and initialize the state
3909 machine that will iterate through all the static tracepoints
3910 markers. */
3912 static void
3913 cmd_qtfstm (char *packet)
3915 if (!maybe_write_ipa_ust_not_loaded (packet))
3916 run_inferior_command (packet, strlen (packet) + 1);
3919 /* Return additional static tracepoints markers. */
3921 static void
3922 cmd_qtsstm (char *packet)
3924 if (!maybe_write_ipa_ust_not_loaded (packet))
3925 run_inferior_command (packet, strlen (packet) + 1);
3928 /* Return the definition of the static tracepoint at a given address.
3929 Result packet is the same as qTsST's. */
3931 static void
3932 cmd_qtstmat (char *packet)
3934 if (!maybe_write_ipa_ust_not_loaded (packet))
3935 run_inferior_command (packet, strlen (packet) + 1);
3938 /* Sent the agent a command to close it. */
3940 void
3941 gdb_agent_about_to_close (int pid)
3943 char buf[IPA_CMD_BUF_SIZE];
3945 if (!maybe_write_ipa_not_loaded (buf))
3947 scoped_restore_current_thread restore_thread;
3949 /* Find any thread which belongs to process PID. */
3950 switch_to_thread (find_any_thread_of_pid (pid));
3952 strcpy (buf, "close");
3954 run_inferior_command (buf, strlen (buf) + 1);
3958 /* Return the minimum instruction size needed for fast tracepoints as a
3959 hexadecimal number. */
3961 static void
3962 cmd_qtminftpilen (char *packet)
3964 if (current_thread == NULL)
3966 /* Indicate that the minimum length is currently unknown. */
3967 strcpy (packet, "0");
3968 return;
3971 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3974 /* Respond to qTBuffer packet with a block of raw data from the trace
3975 buffer. GDB may ask for a lot, but we are allowed to reply with
3976 only as much as will fit within packet limits or whatever. */
3978 static void
3979 cmd_qtbuffer (char *own_buf)
3981 ULONGEST offset, num, tot;
3982 unsigned char *tbp;
3983 const char *packet = own_buf;
3985 packet += strlen ("qTBuffer:");
3987 packet = unpack_varlen_hex (packet, &offset);
3988 ++packet; /* skip a comma */
3989 unpack_varlen_hex (packet, &num);
3991 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3992 (int) num, phex_nz (offset, 0));
3994 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3996 /* If we're right at the end, reply specially that we're done. */
3997 if (offset == tot)
3999 strcpy (own_buf, "l");
4000 return;
4003 /* Object to any other out-of-bounds request. */
4004 if (offset > tot)
4006 write_enn (own_buf);
4007 return;
4010 /* Compute the pointer corresponding to the given offset, accounting
4011 for wraparound. */
4012 tbp = trace_buffer_start + offset;
4013 if (tbp >= trace_buffer_wrap)
4014 tbp -= (trace_buffer_wrap - trace_buffer_lo);
4016 /* Trim to the remaining bytes if we're close to the end. */
4017 if (num > tot - offset)
4018 num = tot - offset;
4020 /* Trim to available packet size. */
4021 if (num >= (PBUFSIZ - 16) / 2 )
4022 num = (PBUFSIZ - 16) / 2;
4024 bin2hex (tbp, own_buf, num);
4027 static void
4028 cmd_bigqtbuffer_circular (char *own_buf)
4030 ULONGEST val;
4031 char *packet = own_buf;
4033 packet += strlen ("QTBuffer:circular:");
4035 unpack_varlen_hex (packet, &val);
4036 circular_trace_buffer = val;
4037 trace_debug ("Trace buffer is now %s",
4038 circular_trace_buffer ? "circular" : "linear");
4039 write_ok (own_buf);
4042 static void
4043 cmd_bigqtbuffer_size (char *own_buf)
4045 ULONGEST val;
4046 LONGEST sval;
4047 char *packet = own_buf;
4049 /* Can't change the size during a tracing run. */
4050 if (tracing)
4052 write_enn (own_buf);
4053 return;
4056 packet += strlen ("QTBuffer:size:");
4058 /* -1 is sent as literal "-1". */
4059 if (strcmp (packet, "-1") == 0)
4060 sval = DEFAULT_TRACE_BUFFER_SIZE;
4061 else
4063 unpack_varlen_hex (packet, &val);
4064 sval = (LONGEST) val;
4067 init_trace_buffer (sval);
4068 trace_debug ("Trace buffer is now %s bytes",
4069 plongest (trace_buffer_size));
4070 write_ok (own_buf);
4073 static void
4074 cmd_qtnotes (char *own_buf)
4076 size_t nbytes;
4077 char *saved, *user, *notes, *stopnote;
4078 char *packet = own_buf;
4080 packet += strlen ("QTNotes:");
4082 while (*packet)
4084 if (startswith (packet, "user:"))
4086 packet += strlen ("user:");
4087 saved = packet;
4088 packet = strchr (packet, ';');
4089 nbytes = (packet - saved) / 2;
4090 user = (char *) xmalloc (nbytes + 1);
4091 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
4092 user[nbytes] = '\0';
4093 ++packet; /* skip the semicolon */
4094 trace_debug ("User is '%s'", user);
4095 xfree (tracing_user_name);
4096 tracing_user_name = user;
4098 else if (startswith (packet, "notes:"))
4100 packet += strlen ("notes:");
4101 saved = packet;
4102 packet = strchr (packet, ';');
4103 nbytes = (packet - saved) / 2;
4104 notes = (char *) xmalloc (nbytes + 1);
4105 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
4106 notes[nbytes] = '\0';
4107 ++packet; /* skip the semicolon */
4108 trace_debug ("Notes is '%s'", notes);
4109 xfree (tracing_notes);
4110 tracing_notes = notes;
4112 else if (startswith (packet, "tstop:"))
4114 packet += strlen ("tstop:");
4115 saved = packet;
4116 packet = strchr (packet, ';');
4117 nbytes = (packet - saved) / 2;
4118 stopnote = (char *) xmalloc (nbytes + 1);
4119 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
4120 stopnote[nbytes] = '\0';
4121 ++packet; /* skip the semicolon */
4122 trace_debug ("tstop note is '%s'", stopnote);
4123 xfree (tracing_stop_note);
4124 tracing_stop_note = stopnote;
4126 else
4127 break;
4130 write_ok (own_buf);
4134 handle_tracepoint_general_set (char *packet)
4136 if (strcmp ("QTinit", packet) == 0)
4138 cmd_qtinit (packet);
4139 return 1;
4141 else if (startswith (packet, "QTDP:"))
4143 cmd_qtdp (packet);
4144 return 1;
4146 else if (startswith (packet, "QTDPsrc:"))
4148 cmd_qtdpsrc (packet);
4149 return 1;
4151 else if (startswith (packet, "QTEnable:"))
4153 cmd_qtenable_disable (packet, 1);
4154 return 1;
4156 else if (startswith (packet, "QTDisable:"))
4158 cmd_qtenable_disable (packet, 0);
4159 return 1;
4161 else if (startswith (packet, "QTDV:"))
4163 cmd_qtdv (packet);
4164 return 1;
4166 else if (startswith (packet, "QTro:"))
4168 cmd_qtro (packet);
4169 return 1;
4171 else if (strcmp ("QTStart", packet) == 0)
4173 cmd_qtstart (packet);
4174 return 1;
4176 else if (strcmp ("QTStop", packet) == 0)
4178 cmd_qtstop (packet);
4179 return 1;
4181 else if (startswith (packet, "QTDisconnected:"))
4183 cmd_qtdisconnected (packet);
4184 return 1;
4186 else if (startswith (packet, "QTFrame:"))
4188 cmd_qtframe (packet);
4189 return 1;
4191 else if (startswith (packet, "QTBuffer:circular:"))
4193 cmd_bigqtbuffer_circular (packet);
4194 return 1;
4196 else if (startswith (packet, "QTBuffer:size:"))
4198 cmd_bigqtbuffer_size (packet);
4199 return 1;
4201 else if (startswith (packet, "QTNotes:"))
4203 cmd_qtnotes (packet);
4204 return 1;
4207 return 0;
4211 handle_tracepoint_query (char *packet)
4213 if (strcmp ("qTStatus", packet) == 0)
4215 cmd_qtstatus (packet);
4216 return 1;
4218 else if (startswith (packet, "qTP:"))
4220 cmd_qtp (packet);
4221 return 1;
4223 else if (strcmp ("qTfP", packet) == 0)
4225 cmd_qtfp (packet);
4226 return 1;
4228 else if (strcmp ("qTsP", packet) == 0)
4230 cmd_qtsp (packet);
4231 return 1;
4233 else if (strcmp ("qTfV", packet) == 0)
4235 cmd_qtfv (packet);
4236 return 1;
4238 else if (strcmp ("qTsV", packet) == 0)
4240 cmd_qtsv (packet);
4241 return 1;
4243 else if (startswith (packet, "qTV:"))
4245 cmd_qtv (packet);
4246 return 1;
4248 else if (startswith (packet, "qTBuffer:"))
4250 cmd_qtbuffer (packet);
4251 return 1;
4253 else if (strcmp ("qTfSTM", packet) == 0)
4255 cmd_qtfstm (packet);
4256 return 1;
4258 else if (strcmp ("qTsSTM", packet) == 0)
4260 cmd_qtsstm (packet);
4261 return 1;
4263 else if (startswith (packet, "qTSTMat:"))
4265 cmd_qtstmat (packet);
4266 return 1;
4268 else if (strcmp ("qTMinFTPILen", packet) == 0)
4270 cmd_qtminftpilen (packet);
4271 return 1;
4274 return 0;
4277 #endif
4278 #ifndef IN_PROCESS_AGENT
4280 /* Call this when thread TINFO has hit the tracepoint defined by
4281 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
4282 action. This adds a while-stepping collecting state item to the
4283 threads' collecting state list, so that we can keep track of
4284 multiple simultaneous while-stepping actions being collected by the
4285 same thread. This can happen in cases like:
4287 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
4288 ff0002 INSN2
4289 ff0003 INSN3 <-- TP2, collect $regs
4290 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
4291 ff0005 INSN5
4293 Notice that when instruction INSN5 is reached, the while-stepping
4294 actions of both TP1 and TP3 are still being collected, and that TP2
4295 had been collected meanwhile. The whole range of ff0001-ff0005
4296 should be single-stepped, due to at least TP1's while-stepping
4297 action covering the whole range. */
4299 static void
4300 add_while_stepping_state (struct thread_info *tinfo,
4301 int tp_number, CORE_ADDR tp_address)
4303 struct wstep_state *wstep = XNEW (struct wstep_state);
4305 wstep->next = tinfo->while_stepping;
4307 wstep->tp_number = tp_number;
4308 wstep->tp_address = tp_address;
4309 wstep->current_step = 0;
4311 tinfo->while_stepping = wstep;
4314 /* Release the while-stepping collecting state WSTEP. */
4316 static void
4317 release_while_stepping_state (struct wstep_state *wstep)
4319 free (wstep);
4322 /* Release all while-stepping collecting states currently associated
4323 with thread TINFO. */
4325 void
4326 release_while_stepping_state_list (struct thread_info *tinfo)
4328 struct wstep_state *head;
4330 while (tinfo->while_stepping)
4332 head = tinfo->while_stepping;
4333 tinfo->while_stepping = head->next;
4334 release_while_stepping_state (head);
4338 /* If TINFO was handling a 'while-stepping' action, the step has
4339 finished, so collect any step data needed, and check if any more
4340 steps are required. Return true if the thread was indeed
4341 collecting tracepoint data, false otherwise. */
4344 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
4346 struct tracepoint *tpoint;
4347 struct wstep_state *wstep;
4348 struct wstep_state **wstep_link;
4349 struct trap_tracepoint_ctx ctx;
4351 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4352 our buffer. */
4353 if (agent_loaded_p ())
4354 upload_fast_traceframes ();
4356 /* Check if we were indeed collecting data for one of more
4357 tracepoints with a 'while-stepping' count. */
4358 if (tinfo->while_stepping == NULL)
4359 return 0;
4361 if (!tracing)
4363 /* We're not even tracing anymore. Stop this thread from
4364 collecting. */
4365 release_while_stepping_state_list (tinfo);
4367 /* The thread had stopped due to a single-step request indeed
4368 explained by a tracepoint. */
4369 return 1;
4372 wstep = tinfo->while_stepping;
4373 wstep_link = &tinfo->while_stepping;
4375 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4376 target_pid_to_str (tinfo->id).c_str (),
4377 wstep->tp_number, paddress (wstep->tp_address));
4379 ctx.base.type = trap_tracepoint;
4380 ctx.regcache = get_thread_regcache (tinfo, 1);
4382 while (wstep != NULL)
4384 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4385 if (tpoint == NULL)
4387 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4388 wstep->tp_number, paddress (wstep->tp_address),
4389 target_pid_to_str (tinfo->id).c_str ());
4391 /* Unlink. */
4392 *wstep_link = wstep->next;
4393 release_while_stepping_state (wstep);
4394 wstep = *wstep_link;
4395 continue;
4398 /* We've just finished one step. */
4399 ++wstep->current_step;
4401 /* Collect data. */
4402 collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
4403 stop_pc, tpoint, wstep->current_step);
4405 if (wstep->current_step >= tpoint->step_count)
4407 /* The requested numbers of steps have occurred. */
4408 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4409 target_pid_to_str (tinfo->id).c_str (),
4410 wstep->tp_number, paddress (wstep->tp_address));
4412 /* Unlink the wstep. */
4413 *wstep_link = wstep->next;
4414 release_while_stepping_state (wstep);
4415 wstep = *wstep_link;
4417 /* Only check the hit count now, which ensure that we do all
4418 our stepping before stopping the run. */
4419 if (tpoint->pass_count > 0
4420 && tpoint->hit_count >= tpoint->pass_count
4421 && stopping_tracepoint == NULL)
4422 stopping_tracepoint = tpoint;
4424 else
4426 /* Keep single-stepping until the requested numbers of steps
4427 have occurred. */
4428 wstep_link = &wstep->next;
4429 wstep = *wstep_link;
4432 if (stopping_tracepoint
4433 || trace_buffer_is_full
4434 || expr_eval_result != expr_eval_no_error)
4436 stop_tracing ();
4437 break;
4441 return 1;
4444 /* Handle any internal tracing control breakpoint hits. That means,
4445 pull traceframes from the IPA to our buffer, and syncing both
4446 tracing agents when the IPA's tracing stops for some reason. */
4449 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
4451 /* Pull in fast tracepoint trace frames from the inferior in-process
4452 agent's buffer into our buffer. */
4454 if (!agent_loaded_p ())
4455 return 0;
4457 upload_fast_traceframes ();
4459 /* Check if the in-process agent had decided we should stop
4460 tracing. */
4461 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4463 int ipa_trace_buffer_is_full;
4464 CORE_ADDR ipa_stopping_tracepoint;
4465 int ipa_expr_eval_result;
4466 CORE_ADDR ipa_error_tracepoint;
4468 trace_debug ("lib stopped at stop_tracing");
4470 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4471 &ipa_trace_buffer_is_full);
4473 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4474 &ipa_stopping_tracepoint);
4475 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4477 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4478 &ipa_error_tracepoint);
4479 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4481 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4482 &ipa_expr_eval_result);
4483 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4485 trace_debug ("lib: trace_buffer_is_full: %d, "
4486 "stopping_tracepoint: %s, "
4487 "ipa_expr_eval_result: %d, "
4488 "error_tracepoint: %s, ",
4489 ipa_trace_buffer_is_full,
4490 paddress (ipa_stopping_tracepoint),
4491 ipa_expr_eval_result,
4492 paddress (ipa_error_tracepoint));
4494 if (ipa_trace_buffer_is_full)
4495 trace_debug ("lib stopped due to full buffer.");
4497 if (ipa_stopping_tracepoint)
4498 trace_debug ("lib stopped due to tpoint");
4500 if (ipa_error_tracepoint)
4501 trace_debug ("lib stopped due to error");
4503 if (ipa_stopping_tracepoint != 0)
4505 stopping_tracepoint
4506 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4508 else if (ipa_expr_eval_result != expr_eval_no_error)
4510 expr_eval_result = ipa_expr_eval_result;
4511 error_tracepoint
4512 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4514 stop_tracing ();
4515 return 1;
4517 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4519 trace_debug ("lib stopped at flush_trace_buffer");
4520 return 1;
4523 return 0;
4526 /* Return true if TINFO just hit a tracepoint. Collect data if
4527 so. */
4530 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
4532 struct tracepoint *tpoint;
4533 int ret = 0;
4534 struct trap_tracepoint_ctx ctx;
4536 /* Not tracing, don't handle. */
4537 if (!tracing)
4538 return 0;
4540 ctx.base.type = trap_tracepoint;
4541 ctx.regcache = get_thread_regcache (tinfo, 1);
4543 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4545 /* Note that we collect fast tracepoints here as well. We'll
4546 step over the fast tracepoint jump later, which avoids the
4547 double collect. However, we don't collect for static
4548 tracepoints here, because UST markers are compiled in program,
4549 and probes will be executed in program. So static tracepoints
4550 are collected there. */
4551 if (tpoint->enabled && stop_pc == tpoint->address
4552 && tpoint->type != static_tracepoint)
4554 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4555 target_pid_to_str (tinfo->id).c_str (),
4556 tpoint->number, paddress (tpoint->address));
4558 /* Test the condition if present, and collect if true. */
4559 if (!tpoint->cond
4560 || (condition_true_at_tracepoint
4561 ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
4562 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4563 stop_pc, tpoint);
4565 if (stopping_tracepoint
4566 || trace_buffer_is_full
4567 || expr_eval_result != expr_eval_no_error)
4569 stop_tracing ();
4571 /* If the tracepoint had a 'while-stepping' action, then set
4572 the thread to collect this tracepoint on the following
4573 single-steps. */
4574 else if (tpoint->step_count > 0)
4576 add_while_stepping_state (tinfo,
4577 tpoint->number, tpoint->address);
4580 ret = 1;
4584 return ret;
4587 #endif
4589 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4590 struct ust_marker_data;
4591 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4592 struct traceframe *tframe);
4593 #endif
4595 /* Create a trace frame for the hit of the given tracepoint in the
4596 given thread. */
4598 static void
4599 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4600 struct tracepoint *tpoint)
4602 struct traceframe *tframe;
4603 int acti;
4605 /* Only count it as a hit when we actually collect data. */
4606 tpoint->hit_count++;
4608 /* If we've exceeded a defined pass count, record the event for
4609 later, and finish the collection for this hit. This test is only
4610 for nonstepping tracepoints, stepping tracepoints test at the end
4611 of their while-stepping loop. */
4612 if (tpoint->pass_count > 0
4613 && tpoint->hit_count >= tpoint->pass_count
4614 && tpoint->step_count == 0
4615 && stopping_tracepoint == NULL)
4616 stopping_tracepoint = tpoint;
4618 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4619 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4621 tframe = add_traceframe (tpoint);
4623 if (tframe)
4625 for (acti = 0; acti < tpoint->numactions; ++acti)
4627 #ifndef IN_PROCESS_AGENT
4628 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4629 tpoint->number, paddress (tpoint->address),
4630 tpoint->actions_str[acti]);
4631 #endif
4633 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4634 tpoint->actions[acti]);
4637 finish_traceframe (tframe);
4640 if (tframe == NULL && tracing)
4641 trace_buffer_is_full = 1;
4644 #ifndef IN_PROCESS_AGENT
4646 static void
4647 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4648 CORE_ADDR stop_pc,
4649 struct tracepoint *tpoint, int current_step)
4651 struct traceframe *tframe;
4652 int acti;
4654 trace_debug ("Making new step traceframe for "
4655 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4656 tpoint->number, paddress (tpoint->address),
4657 current_step, tpoint->step_count,
4658 tpoint->hit_count);
4660 tframe = add_traceframe (tpoint);
4662 if (tframe)
4664 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4666 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4667 tpoint->number, paddress (tpoint->address),
4668 tpoint->step_actions_str[acti]);
4670 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4671 tpoint->step_actions[acti]);
4674 finish_traceframe (tframe);
4677 if (tframe == NULL && tracing)
4678 trace_buffer_is_full = 1;
4681 #endif
4683 #ifdef IN_PROCESS_AGENT
4684 /* The target description index for IPA. Passed from gdbserver, used
4685 to select ipa_tdesc. */
4686 extern "C" {
4687 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
4689 #endif
4691 static struct regcache *
4692 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4694 struct regcache *regcache = NULL;
4695 #ifdef IN_PROCESS_AGENT
4696 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
4698 if (ctx->type == fast_tracepoint)
4700 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4701 if (!fctx->regcache_initted)
4703 fctx->regcache_initted = 1;
4704 init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
4705 supply_regblock (&fctx->regcache, NULL);
4706 supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4708 regcache = &fctx->regcache;
4710 #ifdef HAVE_UST
4711 if (ctx->type == static_tracepoint)
4713 struct static_tracepoint_ctx *sctx
4714 = (struct static_tracepoint_ctx *) ctx;
4716 if (!sctx->regcache_initted)
4718 sctx->regcache_initted = 1;
4719 init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
4720 supply_regblock (&sctx->regcache, NULL);
4721 /* Pass down the tracepoint address, because REGS doesn't
4722 include the PC, but we know what it must have been. */
4723 supply_static_tracepoint_registers (&sctx->regcache,
4724 (const unsigned char *)
4725 sctx->regs,
4726 sctx->tpoint->address);
4728 regcache = &sctx->regcache;
4730 #endif
4731 #else
4732 if (ctx->type == trap_tracepoint)
4734 struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4735 regcache = tctx->regcache;
4737 #endif
4739 gdb_assert (regcache != NULL);
4741 return regcache;
4744 static void
4745 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4746 CORE_ADDR stop_pc,
4747 struct tracepoint *tpoint,
4748 struct traceframe *tframe,
4749 struct tracepoint_action *taction)
4751 enum eval_result_type err;
4753 switch (taction->type)
4755 case 'M':
4757 struct collect_memory_action *maction;
4758 struct eval_agent_expr_context ax_ctx;
4760 maction = (struct collect_memory_action *) taction;
4761 ax_ctx.regcache = NULL;
4762 ax_ctx.tframe = tframe;
4763 ax_ctx.tpoint = tpoint;
4765 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4766 pulongest (maction->len),
4767 paddress (maction->addr), maction->basereg);
4768 /* (should use basereg) */
4769 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4770 maction->len);
4771 break;
4773 case 'R':
4775 unsigned char *regspace;
4776 struct regcache tregcache;
4777 struct regcache *context_regcache;
4778 int regcache_size;
4780 trace_debug ("Want to collect registers");
4782 context_regcache = get_context_regcache (ctx);
4783 regcache_size = register_cache_size (context_regcache->tdesc);
4785 /* Collect all registers for now. */
4786 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4787 if (regspace == NULL)
4789 trace_debug ("Trace buffer block allocation failed, skipping");
4790 break;
4792 /* Identify a register block. */
4793 *regspace = 'R';
4795 /* Wrap the regblock in a register cache (in the stack, we
4796 don't want to malloc here). */
4797 init_register_cache (&tregcache, context_regcache->tdesc,
4798 regspace + 1);
4800 /* Copy the register data to the regblock. */
4801 regcache_cpy (&tregcache, context_regcache);
4803 #ifndef IN_PROCESS_AGENT
4804 /* On some platforms, trap-based tracepoints will have the PC
4805 pointing to the next instruction after the trap, but we
4806 don't want the user or GDB trying to guess whether the
4807 saved PC needs adjusting; so always record the adjusted
4808 stop_pc. Note that we can't use tpoint->address instead,
4809 since it will be wrong for while-stepping actions. This
4810 adjustment is a nop for fast tracepoints collected from the
4811 in-process lib (but not if GDBserver is collecting one
4812 preemptively), since the PC had already been adjusted to
4813 contain the tracepoint's address by the jump pad. */
4814 trace_debug ("Storing stop pc (0x%s) in regblock",
4815 paddress (stop_pc));
4817 /* This changes the regblock, not the thread's
4818 regcache. */
4819 regcache_write_pc (&tregcache, stop_pc);
4820 #endif
4822 break;
4823 case 'X':
4825 struct eval_expr_action *eaction;
4826 struct eval_agent_expr_context ax_ctx;
4828 eaction = (struct eval_expr_action *) taction;
4829 ax_ctx.regcache = get_context_regcache (ctx);
4830 ax_ctx.tframe = tframe;
4831 ax_ctx.tpoint = tpoint;
4833 trace_debug ("Want to evaluate expression");
4835 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4837 if (err != expr_eval_no_error)
4839 record_tracepoint_error (tpoint, "action expression", err);
4840 return;
4843 break;
4844 case 'L':
4846 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4847 trace_debug ("Want to collect static trace data");
4848 collect_ust_data_at_tracepoint (ctx, tframe);
4849 #else
4850 trace_debug ("warning: collecting static trace data, "
4851 "but static tracepoints are not supported");
4852 #endif
4854 break;
4855 default:
4856 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4857 break;
4861 static int
4862 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4863 struct tracepoint *tpoint)
4865 ULONGEST value = 0;
4866 enum eval_result_type err;
4868 /* Presently, gdbserver doesn't run compiled conditions, only the
4869 IPA does. If the program stops at a fast tracepoint's address
4870 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4871 gdbserver preemptively collect the fast tracepoint. Later, on
4872 resume, gdbserver steps over the fast tracepoint like it steps
4873 over breakpoints, so that the IPA doesn't see that fast
4874 tracepoint. This avoids double collects of fast tracepoints in
4875 that stopping scenario. Having gdbserver itself handle the fast
4876 tracepoint gives the user a consistent view of when fast or trap
4877 tracepoints are collected, compared to an alternative where only
4878 trap tracepoints are collected on stop, and fast tracepoints on
4879 resume. When a fast tracepoint is being processed by gdbserver,
4880 it is always the non-compiled condition expression that is
4881 used. */
4882 #ifdef IN_PROCESS_AGENT
4883 if (tpoint->compiled_cond)
4885 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4886 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4888 else
4889 #endif
4891 struct eval_agent_expr_context ax_ctx;
4893 ax_ctx.regcache = get_context_regcache (ctx);
4894 ax_ctx.tframe = NULL;
4895 ax_ctx.tpoint = tpoint;
4897 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4899 if (err != expr_eval_no_error)
4901 record_tracepoint_error (tpoint, "condition", err);
4902 /* The error case must return false. */
4903 return 0;
4906 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4907 tpoint->number, paddress (tpoint->address),
4908 pulongest (value));
4909 return (value ? 1 : 0);
4912 /* See tracepoint.h. */
4915 agent_mem_read (struct eval_agent_expr_context *ctx,
4916 unsigned char *to, CORE_ADDR from, ULONGEST len)
4918 unsigned char *mspace;
4919 ULONGEST remaining = len;
4920 unsigned short blocklen;
4922 /* If a 'to' buffer is specified, use it. */
4923 if (to != NULL)
4924 return read_inferior_memory (from, to, len);
4926 /* Otherwise, create a new memory block in the trace buffer. */
4927 while (remaining > 0)
4929 size_t sp;
4931 blocklen = (remaining > 65535 ? 65535 : remaining);
4932 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4933 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4934 if (mspace == NULL)
4935 return 1;
4936 /* Identify block as a memory block. */
4937 *mspace = 'M';
4938 ++mspace;
4939 /* Record address and size. */
4940 memcpy (mspace, &from, sizeof (from));
4941 mspace += sizeof (from);
4942 memcpy (mspace, &blocklen, sizeof (blocklen));
4943 mspace += sizeof (blocklen);
4944 /* Record the memory block proper. */
4945 if (read_inferior_memory (from, mspace, blocklen) != 0)
4946 return 1;
4947 trace_debug ("%d bytes recorded", blocklen);
4948 remaining -= blocklen;
4949 from += blocklen;
4951 return 0;
4955 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4956 unsigned char *to, CORE_ADDR from, ULONGEST len)
4958 unsigned char *buf, *mspace;
4959 ULONGEST remaining = len;
4960 unsigned short blocklen, i;
4962 /* To save a bit of space, block lengths are 16-bit, so break large
4963 requests into multiple blocks. Bordering on overkill for strings,
4964 but it could happen that someone specifies a large max length. */
4965 while (remaining > 0)
4967 size_t sp;
4969 blocklen = (remaining > 65535 ? 65535 : remaining);
4970 /* We want working space to accumulate nonzero bytes, since
4971 traceframes must have a predecided size (otherwise it gets
4972 harder to wrap correctly for the circular case, etc). */
4973 buf = (unsigned char *) xmalloc (blocklen + 1);
4974 for (i = 0; i < blocklen; ++i)
4976 /* Read the string one byte at a time, in case the string is
4977 at the end of a valid memory area - we don't want a
4978 correctly-terminated string to engender segvio
4979 complaints. */
4980 read_inferior_memory (from + i, buf + i, 1);
4982 if (buf[i] == '\0')
4984 blocklen = i + 1;
4985 /* Make sure outer loop stops now too. */
4986 remaining = blocklen;
4987 break;
4990 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4991 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4992 if (mspace == NULL)
4994 xfree (buf);
4995 return 1;
4997 /* Identify block as a memory block. */
4998 *mspace = 'M';
4999 ++mspace;
5000 /* Record address and size. */
5001 memcpy ((void *) mspace, (void *) &from, sizeof (from));
5002 mspace += sizeof (from);
5003 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
5004 mspace += sizeof (blocklen);
5005 /* Copy the string contents. */
5006 memcpy ((void *) mspace, (void *) buf, blocklen);
5007 remaining -= blocklen;
5008 from += blocklen;
5009 xfree (buf);
5011 return 0;
5014 /* Record the value of a trace state variable. */
5017 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
5019 unsigned char *vspace;
5020 LONGEST val;
5022 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
5023 1 + sizeof (n) + sizeof (LONGEST));
5024 if (vspace == NULL)
5025 return 1;
5026 /* Identify block as a variable. */
5027 *vspace = 'V';
5028 /* Record variable's number and value. */
5029 memcpy (vspace + 1, &n, sizeof (n));
5030 val = get_trace_state_variable_value (n);
5031 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
5032 trace_debug ("Variable %d recorded", n);
5033 return 0;
5036 #ifndef IN_PROCESS_AGENT
5038 /* Callback for traceframe_walk_blocks, used to find a given block
5039 type in a traceframe. */
5041 static int
5042 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
5044 char *wantedp = (char *) data;
5046 if (*wantedp == blocktype)
5047 return 1;
5049 return 0;
5052 /* Walk over all traceframe blocks of the traceframe buffer starting
5053 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
5054 block found, passing in DATA unmodified. If CALLBACK returns true,
5055 this returns a pointer to where the block is found. Returns NULL
5056 if no callback call returned true, indicating that all blocks have
5057 been walked. */
5059 static unsigned char *
5060 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
5061 int tfnum,
5062 int (*callback) (char blocktype,
5063 unsigned char *dataptr,
5064 void *data),
5065 void *data)
5067 unsigned char *dataptr;
5069 if (datasize == 0)
5071 trace_debug ("traceframe %d has no data", tfnum);
5072 return NULL;
5075 /* Iterate through a traceframe's blocks, looking for a block of the
5076 requested type. */
5077 for (dataptr = database;
5078 dataptr < database + datasize;
5079 /* nothing */)
5081 char blocktype;
5082 unsigned short mlen;
5084 if (dataptr == trace_buffer_wrap)
5086 /* Adjust to reflect wrapping part of the frame around to
5087 the beginning. */
5088 datasize = dataptr - database;
5089 dataptr = database = trace_buffer_lo;
5092 blocktype = *dataptr++;
5094 if ((*callback) (blocktype, dataptr, data))
5095 return dataptr;
5097 switch (blocktype)
5099 case 'R':
5100 /* Skip over the registers block. */
5101 dataptr += current_target_desc ()->registers_size;
5102 break;
5103 case 'M':
5104 /* Skip over the memory block. */
5105 dataptr += sizeof (CORE_ADDR);
5106 memcpy (&mlen, dataptr, sizeof (mlen));
5107 dataptr += (sizeof (mlen) + mlen);
5108 break;
5109 case 'V':
5110 /* Skip over the TSV block. */
5111 dataptr += (sizeof (int) + sizeof (LONGEST));
5112 break;
5113 case 'S':
5114 /* Skip over the static trace data block. */
5115 memcpy (&mlen, dataptr, sizeof (mlen));
5116 dataptr += (sizeof (mlen) + mlen);
5117 break;
5118 default:
5119 trace_debug ("traceframe %d has unknown block type 0x%x",
5120 tfnum, blocktype);
5121 return NULL;
5125 return NULL;
5128 /* Look for the block of type TYPE_WANTED in the traceframe starting
5129 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
5130 number. */
5132 static unsigned char *
5133 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
5134 int tfnum, char type_wanted)
5136 return traceframe_walk_blocks (database, datasize, tfnum,
5137 match_blocktype, &type_wanted);
5140 static unsigned char *
5141 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
5143 unsigned char *regblock;
5145 regblock = traceframe_find_block_type (tframe->data,
5146 tframe->data_size,
5147 tfnum, 'R');
5149 if (regblock == NULL)
5150 trace_debug ("traceframe %d has no register data", tfnum);
5152 return regblock;
5155 /* Get registers from a traceframe. */
5158 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
5160 unsigned char *dataptr;
5161 struct tracepoint *tpoint;
5162 struct traceframe *tframe;
5164 tframe = find_traceframe (tfnum);
5166 if (tframe == NULL)
5168 trace_debug ("traceframe %d not found", tfnum);
5169 return 1;
5172 dataptr = traceframe_find_regblock (tframe, tfnum);
5173 if (dataptr == NULL)
5175 /* Mark registers unavailable. */
5176 supply_regblock (regcache, NULL);
5178 /* We can generally guess at a PC, although this will be
5179 misleading for while-stepping frames and multi-location
5180 tracepoints. */
5181 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
5182 if (tpoint != NULL)
5183 regcache_write_pc (regcache, tpoint->address);
5185 else
5186 supply_regblock (regcache, dataptr);
5188 return 0;
5191 static CORE_ADDR
5192 traceframe_get_pc (struct traceframe *tframe)
5194 struct regcache regcache;
5195 unsigned char *dataptr;
5196 const struct target_desc *tdesc = current_target_desc ();
5198 dataptr = traceframe_find_regblock (tframe, -1);
5199 if (dataptr == NULL)
5200 return 0;
5202 init_register_cache (&regcache, tdesc, dataptr);
5203 return regcache_read_pc (&regcache);
5206 /* Read a requested block of memory from a trace frame. */
5209 traceframe_read_mem (int tfnum, CORE_ADDR addr,
5210 unsigned char *buf, ULONGEST length,
5211 ULONGEST *nbytes)
5213 struct traceframe *tframe;
5214 unsigned char *database, *dataptr;
5215 unsigned int datasize;
5216 CORE_ADDR maddr;
5217 unsigned short mlen;
5219 trace_debug ("traceframe_read_mem");
5221 tframe = find_traceframe (tfnum);
5223 if (!tframe)
5225 trace_debug ("traceframe %d not found", tfnum);
5226 return 1;
5229 datasize = tframe->data_size;
5230 database = dataptr = &tframe->data[0];
5232 /* Iterate through a traceframe's blocks, looking for memory. */
5233 while ((dataptr = traceframe_find_block_type (dataptr,
5234 datasize
5235 - (dataptr - database),
5236 tfnum, 'M')) != NULL)
5238 memcpy (&maddr, dataptr, sizeof (maddr));
5239 dataptr += sizeof (maddr);
5240 memcpy (&mlen, dataptr, sizeof (mlen));
5241 dataptr += sizeof (mlen);
5242 trace_debug ("traceframe %d has %d bytes at %s",
5243 tfnum, mlen, paddress (maddr));
5245 /* If the block includes the first part of the desired range,
5246 return as much it has; GDB will re-request the remainder,
5247 which might be in a different block of this trace frame. */
5248 if (maddr <= addr && addr < (maddr + mlen))
5250 ULONGEST amt = (maddr + mlen) - addr;
5251 if (amt > length)
5252 amt = length;
5254 memcpy (buf, dataptr + (addr - maddr), amt);
5255 *nbytes = amt;
5256 return 0;
5259 /* Skip over this block. */
5260 dataptr += mlen;
5263 trace_debug ("traceframe %d has no memory data for the desired region",
5264 tfnum);
5266 *nbytes = 0;
5267 return 0;
5270 static int
5271 traceframe_read_tsv (int tsvnum, LONGEST *val)
5273 client_state &cs = get_client_state ();
5274 int tfnum;
5275 struct traceframe *tframe;
5276 unsigned char *database, *dataptr;
5277 unsigned int datasize;
5278 int vnum;
5279 int found = 0;
5281 trace_debug ("traceframe_read_tsv");
5283 tfnum = cs.current_traceframe;
5285 if (tfnum < 0)
5287 trace_debug ("no current traceframe");
5288 return 1;
5291 tframe = find_traceframe (tfnum);
5293 if (tframe == NULL)
5295 trace_debug ("traceframe %d not found", tfnum);
5296 return 1;
5299 datasize = tframe->data_size;
5300 database = dataptr = &tframe->data[0];
5302 /* Iterate through a traceframe's blocks, looking for the last
5303 matched tsv. */
5304 while ((dataptr = traceframe_find_block_type (dataptr,
5305 datasize
5306 - (dataptr - database),
5307 tfnum, 'V')) != NULL)
5309 memcpy (&vnum, dataptr, sizeof (vnum));
5310 dataptr += sizeof (vnum);
5312 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
5314 /* Check that this is the variable we want. */
5315 if (tsvnum == vnum)
5317 memcpy (val, dataptr, sizeof (*val));
5318 found = 1;
5321 /* Skip over this block. */
5322 dataptr += sizeof (LONGEST);
5325 if (!found)
5326 trace_debug ("traceframe %d has no data for variable %d",
5327 tfnum, tsvnum);
5328 return !found;
5331 /* Read a requested block of static tracepoint data from a trace
5332 frame. */
5335 traceframe_read_sdata (int tfnum, ULONGEST offset,
5336 unsigned char *buf, ULONGEST length,
5337 ULONGEST *nbytes)
5339 struct traceframe *tframe;
5340 unsigned char *database, *dataptr;
5341 unsigned int datasize;
5342 unsigned short mlen;
5344 trace_debug ("traceframe_read_sdata");
5346 tframe = find_traceframe (tfnum);
5348 if (!tframe)
5350 trace_debug ("traceframe %d not found", tfnum);
5351 return 1;
5354 datasize = tframe->data_size;
5355 database = &tframe->data[0];
5357 /* Iterate through a traceframe's blocks, looking for static
5358 tracepoint data. */
5359 dataptr = traceframe_find_block_type (database, datasize,
5360 tfnum, 'S');
5361 if (dataptr != NULL)
5363 memcpy (&mlen, dataptr, sizeof (mlen));
5364 dataptr += sizeof (mlen);
5365 if (offset < mlen)
5367 if (offset + length > mlen)
5368 length = mlen - offset;
5370 memcpy (buf, dataptr, length);
5371 *nbytes = length;
5373 else
5374 *nbytes = 0;
5375 return 0;
5378 trace_debug ("traceframe %d has no static trace data", tfnum);
5380 *nbytes = 0;
5381 return 0;
5384 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
5385 object. DATA is pointer to a string holding the traceframe-info
5386 object being built. */
5388 static int
5389 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
5391 std::string *buffer = (std::string *) data;
5393 switch (blocktype)
5395 case 'M':
5397 unsigned short mlen;
5398 CORE_ADDR maddr;
5400 memcpy (&maddr, dataptr, sizeof (maddr));
5401 dataptr += sizeof (maddr);
5402 memcpy (&mlen, dataptr, sizeof (mlen));
5403 dataptr += sizeof (mlen);
5404 string_xml_appendf (*buffer,
5405 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
5406 paddress (maddr), phex_nz (mlen, sizeof (mlen)));
5407 break;
5409 case 'V':
5411 int vnum;
5413 memcpy (&vnum, dataptr, sizeof (vnum));
5414 string_xml_appendf (*buffer, "<tvar id=\"%d\"/>\n", vnum);
5415 break;
5417 case 'R':
5418 case 'S':
5420 break;
5422 default:
5423 warning ("Unhandled trace block type (%d) '%c ' "
5424 "while building trace frame info.",
5425 blocktype, blocktype);
5426 break;
5429 return 0;
5432 /* Build a traceframe-info object for traceframe number TFNUM into
5433 BUFFER. */
5436 traceframe_read_info (int tfnum, std::string *buffer)
5438 struct traceframe *tframe;
5440 trace_debug ("traceframe_read_info");
5442 tframe = find_traceframe (tfnum);
5444 if (!tframe)
5446 trace_debug ("traceframe %d not found", tfnum);
5447 return 1;
5450 *buffer += "<traceframe-info>\n";
5451 traceframe_walk_blocks (tframe->data, tframe->data_size,
5452 tfnum, build_traceframe_info_xml, buffer);
5453 *buffer += "</traceframe-info>\n";
5454 return 0;
5457 /* Return the first fast tracepoint whose jump pad contains PC. */
5459 static struct tracepoint *
5460 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5462 struct tracepoint *tpoint;
5464 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5465 if (tpoint->type == fast_tracepoint)
5466 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5467 return tpoint;
5469 return NULL;
5472 /* Return the first fast tracepoint whose trampoline contains PC. */
5474 static struct tracepoint *
5475 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5477 struct tracepoint *tpoint;
5479 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5481 if (tpoint->type == fast_tracepoint
5482 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5483 return tpoint;
5486 return NULL;
5489 /* Return GDBserver's tracepoint that matches the IP Agent's
5490 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5491 address space. */
5493 static struct tracepoint *
5494 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5496 struct tracepoint *tpoint;
5498 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5499 if (tpoint->type == fast_tracepoint)
5500 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5501 return tpoint;
5503 return NULL;
5506 #endif
5508 /* The type of the object that is used to synchronize fast tracepoint
5509 collection. */
5511 typedef struct collecting_t
5513 /* The fast tracepoint number currently collecting. */
5514 uintptr_t tpoint;
5516 /* A number that GDBserver can use to identify the thread that is
5517 presently holding the collect lock. This need not (and usually
5518 is not) the thread id, as getting the current thread ID usually
5519 requires a system call, which we want to avoid like the plague.
5520 Usually this is thread's TCB, found in the TLS (pseudo-)
5521 register, which is readable with a single insn on several
5522 architectures. */
5523 uintptr_t thread_area;
5524 } collecting_t;
5526 #ifndef IN_PROCESS_AGENT
5528 void
5529 force_unlock_trace_buffer (void)
5531 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5534 /* Check if the thread identified by THREAD_AREA which is stopped at
5535 STOP_PC, is presently locking the fast tracepoint collection, and
5536 if so, gather some status of said collection. Returns 0 if the
5537 thread isn't collecting or in the jump pad at all. 1, if in the
5538 jump pad (or within gdb_collect) and hasn't executed the adjusted
5539 original insn yet (can set a breakpoint there and run to it). 2,
5540 if presently executing the adjusted original insn --- in which
5541 case, if we want to move the thread out of the jump pad, we need to
5542 single-step it until this function returns 0. */
5544 fast_tpoint_collect_result
5545 fast_tracepoint_collecting (CORE_ADDR thread_area,
5546 CORE_ADDR stop_pc,
5547 struct fast_tpoint_collect_status *status)
5549 CORE_ADDR ipa_collecting;
5550 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5551 CORE_ADDR ipa_gdb_trampoline_buffer;
5552 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5553 struct tracepoint *tpoint;
5554 int needs_breakpoint;
5556 /* The thread THREAD_AREA is either:
5558 0. not collecting at all, not within the jump pad, or within
5559 gdb_collect or one of its callees.
5561 1. in the jump pad and haven't reached gdb_collect
5563 2. within gdb_collect (out of the jump pad) (collect is set)
5565 3. we're in the jump pad, after gdb_collect having returned,
5566 possibly executing the adjusted insns.
5568 For cases 1 and 3, `collecting' may or not be set. The jump pad
5569 doesn't have any complicated jump logic, so we can tell if the
5570 thread is executing the adjust original insn or not by just
5571 matching STOP_PC with known jump pad addresses. If we it isn't
5572 yet executing the original insn, set a breakpoint there, and let
5573 the thread run to it, so to quickly step over a possible (many
5574 insns) gdb_collect call. Otherwise, or when the breakpoint is
5575 hit, only a few (small number of) insns are left to be executed
5576 in the jump pad. Single-step the thread until it leaves the
5577 jump pad. */
5579 again:
5580 tpoint = NULL;
5581 needs_breakpoint = 0;
5582 trace_debug ("fast_tracepoint_collecting");
5584 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5585 &ipa_gdb_jump_pad_buffer))
5587 internal_error ("error extracting `gdb_jump_pad_buffer'");
5589 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5590 &ipa_gdb_jump_pad_buffer_end))
5592 internal_error ("error extracting `gdb_jump_pad_buffer_end'");
5595 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5596 &ipa_gdb_trampoline_buffer))
5598 internal_error ("error extracting `gdb_trampoline_buffer'");
5600 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5601 &ipa_gdb_trampoline_buffer_end))
5603 internal_error ("error extracting `gdb_trampoline_buffer_end'");
5606 if (ipa_gdb_jump_pad_buffer <= stop_pc
5607 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5609 /* We can tell which tracepoint(s) the thread is collecting by
5610 matching the jump pad address back to the tracepoint. */
5611 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5612 if (tpoint == NULL)
5614 warning ("in jump pad, but no matching tpoint?");
5615 return fast_tpoint_collect_result::not_collecting;
5617 else
5619 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5620 "adj_insn(%s, %s)",
5621 tpoint->number, paddress (tpoint->address),
5622 paddress (tpoint->jump_pad),
5623 paddress (tpoint->jump_pad_end),
5624 paddress (tpoint->adjusted_insn_addr),
5625 paddress (tpoint->adjusted_insn_addr_end));
5628 /* Definitely in the jump pad. May or may not need
5629 fast-exit-jump-pad breakpoint. */
5630 if (tpoint->jump_pad <= stop_pc
5631 && stop_pc < tpoint->adjusted_insn_addr)
5632 needs_breakpoint = 1;
5634 else if (ipa_gdb_trampoline_buffer <= stop_pc
5635 && stop_pc < ipa_gdb_trampoline_buffer_end)
5637 /* We can tell which tracepoint(s) the thread is collecting by
5638 matching the trampoline address back to the tracepoint. */
5639 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5640 if (tpoint == NULL)
5642 warning ("in trampoline, but no matching tpoint?");
5643 return fast_tpoint_collect_result::not_collecting;
5645 else
5647 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5648 tpoint->number, paddress (tpoint->address),
5649 paddress (tpoint->trampoline),
5650 paddress (tpoint->trampoline_end));
5653 /* Have not reached jump pad yet, but treat the trampoline as a
5654 part of the jump pad that is before the adjusted original
5655 instruction. */
5656 needs_breakpoint = 1;
5658 else
5660 collecting_t ipa_collecting_obj;
5662 /* If `collecting' is set/locked, then the THREAD_AREA thread
5663 may or not be the one holding the lock. We have to read the
5664 lock to find out. */
5666 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5667 &ipa_collecting))
5669 trace_debug ("fast_tracepoint_collecting:"
5670 " failed reading 'collecting' in the inferior");
5671 return fast_tpoint_collect_result::not_collecting;
5674 if (!ipa_collecting)
5676 trace_debug ("fast_tracepoint_collecting: not collecting"
5677 " (and nobody is).");
5678 return fast_tpoint_collect_result::not_collecting;
5681 /* Some thread is collecting. Check which. */
5682 if (read_inferior_memory (ipa_collecting,
5683 (unsigned char *) &ipa_collecting_obj,
5684 sizeof (ipa_collecting_obj)) != 0)
5685 goto again;
5687 if (ipa_collecting_obj.thread_area != thread_area)
5689 trace_debug ("fast_tracepoint_collecting: not collecting "
5690 "(another thread is)");
5691 return fast_tpoint_collect_result::not_collecting;
5694 tpoint
5695 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5696 if (tpoint == NULL)
5698 warning ("fast_tracepoint_collecting: collecting, "
5699 "but tpoint %s not found?",
5700 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5701 return fast_tpoint_collect_result::not_collecting;
5704 /* The thread is within `gdb_collect', skip over the rest of
5705 fast tracepoint collection quickly using a breakpoint. */
5706 needs_breakpoint = 1;
5709 /* The caller wants a bit of status detail. */
5710 if (status != NULL)
5712 status->tpoint_num = tpoint->number;
5713 status->tpoint_addr = tpoint->address;
5714 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5715 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5718 if (needs_breakpoint)
5720 /* Hasn't executed the original instruction yet. Set breakpoint
5721 there, and wait till it's hit, then single-step until exiting
5722 the jump pad. */
5724 trace_debug ("\
5725 fast_tracepoint_collecting, returning continue-until-break at %s",
5726 paddress (tpoint->adjusted_insn_addr));
5728 return fast_tpoint_collect_result::before_insn; /* continue */
5730 else
5732 /* Just single-step until exiting the jump pad. */
5734 trace_debug ("fast_tracepoint_collecting, returning "
5735 "need-single-step (%s-%s)",
5736 paddress (tpoint->adjusted_insn_addr),
5737 paddress (tpoint->adjusted_insn_addr_end));
5739 return fast_tpoint_collect_result::at_insn; /* single-step */
5743 #endif
5745 #ifdef IN_PROCESS_AGENT
5747 /* The global fast tracepoint collect lock. Points to a collecting_t
5748 object built on the stack by the jump pad, if presently locked;
5749 NULL if it isn't locked. Note that this lock *must* be set while
5750 executing any *function other than the jump pad. See
5751 fast_tracepoint_collecting. */
5752 extern "C" {
5753 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5756 /* This is needed for -Wmissing-declarations. */
5757 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5758 unsigned char *regs);
5760 /* This routine, called from the jump pad (in asm) is designed to be
5761 called from the jump pads of fast tracepoints, thus it is on the
5762 critical path. */
5764 IP_AGENT_EXPORT_FUNC void
5765 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5767 struct fast_tracepoint_ctx ctx;
5768 const struct target_desc *ipa_tdesc;
5770 /* Don't do anything until the trace run is completely set up. */
5771 if (!tracing)
5772 return;
5774 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5775 ctx.base.type = fast_tracepoint;
5776 ctx.regs = regs;
5777 ctx.regcache_initted = 0;
5778 /* Wrap the regblock in a register cache (in the stack, we don't
5779 want to malloc here). */
5780 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5781 if (ctx.regspace == NULL)
5783 trace_debug ("Trace buffer block allocation failed, skipping");
5784 return;
5787 for (ctx.tpoint = tpoint;
5788 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5789 ctx.tpoint = ctx.tpoint->next)
5791 if (!ctx.tpoint->enabled)
5792 continue;
5794 /* Multiple tracepoints of different types, such as fast tracepoint and
5795 static tracepoint, can be set at the same address. */
5796 if (ctx.tpoint->type != tpoint->type)
5797 continue;
5799 /* Test the condition if present, and collect if true. */
5800 if (ctx.tpoint->cond == NULL
5801 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5802 ctx.tpoint))
5804 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5805 ctx.tpoint->address, ctx.tpoint);
5807 /* Note that this will cause original insns to be written back
5808 to where we jumped from, but that's OK because we're jumping
5809 back to the next whole instruction. This will go badly if
5810 instruction restoration is not atomic though. */
5811 if (stopping_tracepoint
5812 || trace_buffer_is_full
5813 || expr_eval_result != expr_eval_no_error)
5815 stop_tracing ();
5816 break;
5819 else
5821 /* If there was a condition and it evaluated to false, the only
5822 way we would stop tracing is if there was an error during
5823 condition expression evaluation. */
5824 if (expr_eval_result != expr_eval_no_error)
5826 stop_tracing ();
5827 break;
5833 /* These global variables points to the corresponding functions. This is
5834 necessary on powerpc64, where asking for function symbol address from gdb
5835 results in returning the actual code pointer, instead of the descriptor
5836 pointer. */
5838 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5839 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5840 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5841 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5843 extern "C" {
5844 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5845 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5846 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5847 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5848 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5849 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5852 #endif
5854 #ifndef IN_PROCESS_AGENT
5856 CORE_ADDR
5857 get_raw_reg_func_addr (void)
5859 CORE_ADDR res;
5860 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5862 error ("error extracting get_raw_reg_ptr");
5863 return 0;
5865 return res;
5868 CORE_ADDR
5869 get_get_tsv_func_addr (void)
5871 CORE_ADDR res;
5872 if (read_inferior_data_pointer (
5873 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5875 error ("error extracting get_trace_state_variable_value_ptr");
5876 return 0;
5878 return res;
5881 CORE_ADDR
5882 get_set_tsv_func_addr (void)
5884 CORE_ADDR res;
5885 if (read_inferior_data_pointer (
5886 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5888 error ("error extracting set_trace_state_variable_value_ptr");
5889 return 0;
5891 return res;
5894 static void
5895 compile_tracepoint_condition (struct tracepoint *tpoint,
5896 CORE_ADDR *jump_entry)
5898 CORE_ADDR entry_point = *jump_entry;
5899 enum eval_result_type err;
5901 trace_debug ("Starting condition compilation for tracepoint %d\n",
5902 tpoint->number);
5904 /* Initialize the global pointer to the code being built. */
5905 current_insn_ptr = *jump_entry;
5907 emit_prologue ();
5909 err = compile_bytecodes (tpoint->cond);
5911 if (err == expr_eval_no_error)
5913 emit_epilogue ();
5915 /* Record the beginning of the compiled code. */
5916 tpoint->compiled_cond = entry_point;
5918 trace_debug ("Condition compilation for tracepoint %d complete\n",
5919 tpoint->number);
5921 else
5923 /* Leave the unfinished code in situ, but don't point to it. */
5925 tpoint->compiled_cond = 0;
5927 trace_debug ("Condition compilation for tracepoint %d failed, "
5928 "error code %d",
5929 tpoint->number, err);
5932 /* Update the code pointer passed in. Note that we do this even if
5933 the compile fails, so that we can look at the partial results
5934 instead of letting them be overwritten. */
5935 *jump_entry = current_insn_ptr;
5937 /* Leave a gap, to aid dump decipherment. */
5938 *jump_entry += 16;
5941 /* The base pointer of the IPA's heap. This is the only memory the
5942 IPA is allowed to use. The IPA should _not_ call the inferior's
5943 `malloc' during operation. That'd be slow, and, most importantly,
5944 it may not be safe. We may be collecting a tracepoint in a signal
5945 handler, for example. */
5946 static CORE_ADDR target_tp_heap;
5948 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5949 to 8 bytes. */
5951 static CORE_ADDR
5952 target_malloc (ULONGEST size)
5954 CORE_ADDR ptr;
5956 if (target_tp_heap == 0)
5958 /* We have the pointer *address*, need what it points to. */
5959 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5960 &target_tp_heap))
5962 internal_error ("couldn't get target heap head pointer");
5966 ptr = target_tp_heap;
5967 target_tp_heap += size;
5969 /* Pad to 8-byte alignment. */
5970 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5972 return ptr;
5975 static CORE_ADDR
5976 download_agent_expr (struct agent_expr *expr)
5978 CORE_ADDR expr_addr;
5979 CORE_ADDR expr_bytes;
5981 expr_addr = target_malloc (sizeof (*expr));
5982 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5984 expr_bytes = target_malloc (expr->length);
5985 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
5986 expr_bytes);
5987 target_write_memory (expr_bytes, expr->bytes, expr->length);
5989 return expr_addr;
5992 /* Align V up to N bits. */
5993 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5995 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
5997 static void
5998 download_tracepoint_1 (struct tracepoint *tpoint)
6000 struct tracepoint target_tracepoint;
6001 CORE_ADDR tpptr = 0;
6003 gdb_assert (tpoint->type == fast_tracepoint
6004 || tpoint->type == static_tracepoint);
6006 if (tpoint->cond != NULL && target_emit_ops () != NULL)
6008 CORE_ADDR jentry, jump_entry;
6010 jentry = jump_entry = get_jump_space_head ();
6012 if (tpoint->cond != NULL)
6014 /* Pad to 8-byte alignment. (needed?) */
6015 /* Actually this should be left for the target to
6016 decide. */
6017 jentry = UALIGN (jentry, 8);
6019 compile_tracepoint_condition (tpoint, &jentry);
6022 /* Pad to 8-byte alignment. */
6023 jentry = UALIGN (jentry, 8);
6024 claim_jump_space (jentry - jump_entry);
6027 target_tracepoint = *tpoint;
6029 tpptr = target_malloc (sizeof (*tpoint));
6030 tpoint->obj_addr_on_target = tpptr;
6032 /* Write the whole object. We'll fix up its pointers in a bit.
6033 Assume no next for now. This is fixed up above on the next
6034 iteration, if there's any. */
6035 target_tracepoint.next = NULL;
6036 /* Need to clear this here too, since we're downloading the
6037 tracepoints before clearing our own copy. */
6038 target_tracepoint.hit_count = 0;
6040 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
6041 sizeof (target_tracepoint));
6043 if (tpoint->cond)
6044 write_inferior_data_pointer (tpptr
6045 + offsetof (struct tracepoint, cond),
6046 download_agent_expr (tpoint->cond));
6048 if (tpoint->numactions)
6050 int i;
6051 CORE_ADDR actions_array;
6053 /* The pointers array. */
6054 actions_array
6055 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
6056 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
6057 actions),
6058 actions_array);
6060 /* Now for each pointer, download the action. */
6061 for (i = 0; i < tpoint->numactions; i++)
6063 struct tracepoint_action *action = tpoint->actions[i];
6064 CORE_ADDR ipa_action = tracepoint_action_download (action);
6066 if (ipa_action != 0)
6067 write_inferior_data_pointer (actions_array
6068 + i * sizeof (*tpoint->actions),
6069 ipa_action);
6074 #define IPA_PROTO_FAST_TRACE_FLAG 0
6075 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
6076 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
6077 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
6078 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
6080 /* Send a command to agent to download and install tracepoint TPOINT. */
6082 static int
6083 tracepoint_send_agent (struct tracepoint *tpoint)
6085 char buf[IPA_CMD_BUF_SIZE];
6086 char *p;
6087 int i, ret;
6089 p = buf;
6090 strcpy (p, "FastTrace:");
6091 p += 10;
6093 COPY_FIELD_TO_BUF (p, tpoint, number);
6094 COPY_FIELD_TO_BUF (p, tpoint, address);
6095 COPY_FIELD_TO_BUF (p, tpoint, type);
6096 COPY_FIELD_TO_BUF (p, tpoint, enabled);
6097 COPY_FIELD_TO_BUF (p, tpoint, step_count);
6098 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
6099 COPY_FIELD_TO_BUF (p, tpoint, numactions);
6100 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
6101 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
6102 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
6103 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
6105 /* condition */
6106 p = agent_expr_send (p, tpoint->cond);
6108 /* tracepoint_action */
6109 for (i = 0; i < tpoint->numactions; i++)
6111 struct tracepoint_action *action = tpoint->actions[i];
6113 p[0] = action->type;
6114 p = tracepoint_action_send (&p[1], action);
6117 get_jump_space_head ();
6118 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
6119 agent can use jump pad from it. */
6120 if (tpoint->type == fast_tracepoint)
6122 memcpy (p, &gdb_jump_pad_head, 8);
6123 p += 8;
6126 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
6127 if (ret)
6128 return ret;
6130 if (!startswith (buf, "OK"))
6131 return 1;
6133 /* The value of tracepoint's target address is stored in BUF. */
6134 memcpy (&tpoint->obj_addr_on_target,
6135 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
6137 if (tpoint->type == fast_tracepoint)
6139 unsigned char *insn
6140 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
6141 int fjump_size;
6143 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
6144 (unsigned int) tpoint->obj_addr_on_target,
6145 (unsigned int) gdb_jump_pad_head);
6147 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
6149 /* This has been done in agent. We should also set up record for it. */
6150 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
6151 /* Wire it in. */
6152 tpoint->handle
6153 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
6156 return 0;
6159 static void
6160 download_tracepoint (struct tracepoint *tpoint)
6162 struct tracepoint *tp, *tp_prev;
6164 if (tpoint->type != fast_tracepoint
6165 && tpoint->type != static_tracepoint)
6166 return;
6168 download_tracepoint_1 (tpoint);
6170 /* Find the previous entry of TPOINT, which is fast tracepoint or
6171 static tracepoint. */
6172 tp_prev = NULL;
6173 for (tp = tracepoints; tp != tpoint; tp = tp->next)
6175 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
6176 tp_prev = tp;
6179 if (tp_prev)
6181 CORE_ADDR tp_prev_target_next_addr;
6183 /* Insert TPOINT after TP_PREV in IPA. */
6184 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
6185 + offsetof (struct tracepoint, next),
6186 &tp_prev_target_next_addr))
6188 internal_error ("error reading `tp_prev->next'");
6191 /* tpoint->next = tp_prev->next */
6192 write_inferior_data_pointer (tpoint->obj_addr_on_target
6193 + offsetof (struct tracepoint, next),
6194 tp_prev_target_next_addr);
6195 /* tp_prev->next = tpoint */
6196 write_inferior_data_pointer (tp_prev->obj_addr_on_target
6197 + offsetof (struct tracepoint, next),
6198 tpoint->obj_addr_on_target);
6200 else
6201 /* First object in list, set the head pointer in the
6202 inferior. */
6203 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
6204 tpoint->obj_addr_on_target);
6208 static void
6209 download_trace_state_variables (void)
6211 CORE_ADDR ptr = 0, prev_ptr = 0;
6212 struct trace_state_variable *tsv;
6214 /* Start out empty. */
6215 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
6217 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
6219 struct trace_state_variable target_tsv;
6221 /* TSV's with a getter have been initialized equally in both the
6222 inferior and GDBserver. Skip them. */
6223 if (tsv->getter != NULL)
6224 continue;
6226 target_tsv = *tsv;
6228 prev_ptr = ptr;
6229 ptr = target_malloc (sizeof (*tsv));
6231 if (tsv == trace_state_variables)
6233 /* First object in list, set the head pointer in the
6234 inferior. */
6236 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
6237 ptr);
6239 else
6241 write_inferior_data_pointer (prev_ptr
6242 + offsetof (struct trace_state_variable,
6243 next),
6244 ptr);
6247 /* Write the whole object. We'll fix up its pointers in a bit.
6248 Assume no next, fixup when needed. */
6249 target_tsv.next = NULL;
6251 target_write_memory (ptr, (unsigned char *) &target_tsv,
6252 sizeof (target_tsv));
6254 if (tsv->name != NULL)
6256 size_t size = strlen (tsv->name) + 1;
6257 CORE_ADDR name_addr = target_malloc (size);
6258 target_write_memory (name_addr,
6259 (unsigned char *) tsv->name, size);
6260 write_inferior_data_pointer (ptr
6261 + offsetof (struct trace_state_variable,
6262 name),
6263 name_addr);
6266 gdb_assert (tsv->getter == NULL);
6269 if (prev_ptr != 0)
6271 /* Fixup the next pointer in the last item in the list. */
6272 write_inferior_data_pointer (prev_ptr
6273 + offsetof (struct trace_state_variable,
6274 next), 0);
6278 /* Upload complete trace frames out of the IP Agent's trace buffer
6279 into GDBserver's trace buffer. This always uploads either all or
6280 no trace frames. This is the counter part of
6281 `trace_alloc_trace_buffer'. See its description of the atomic
6282 syncing mechanism. */
6284 static void
6285 upload_fast_traceframes (void)
6287 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
6288 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
6289 CORE_ADDR tf;
6290 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
6291 unsigned int curr_tbctrl_idx;
6292 unsigned int ipa_trace_buffer_ctrl_curr;
6293 unsigned int ipa_trace_buffer_ctrl_curr_old;
6294 CORE_ADDR ipa_trace_buffer_ctrl_addr;
6295 struct breakpoint *about_to_request_buffer_space_bkpt;
6296 CORE_ADDR ipa_trace_buffer_lo;
6297 CORE_ADDR ipa_trace_buffer_hi;
6299 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6300 &ipa_traceframe_read_count_racy))
6302 /* This will happen in most targets if the current thread is
6303 running. */
6304 return;
6307 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6308 &ipa_traceframe_write_count_racy))
6309 return;
6311 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
6312 ipa_traceframe_write_count_racy
6313 - ipa_traceframe_read_count_racy,
6314 ipa_traceframe_write_count_racy,
6315 ipa_traceframe_read_count_racy);
6317 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
6318 return;
6320 about_to_request_buffer_space_bkpt
6321 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
6322 NULL);
6324 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6325 &ipa_trace_buffer_ctrl_curr))
6326 return;
6328 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
6330 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
6333 unsigned int prev, counter;
6335 /* Update the token, with new counters, and the GDBserver stamp
6336 bit. Always reuse the current TBC index. */
6337 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6338 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6340 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
6341 | (prev << 12)
6342 | counter
6343 | curr_tbctrl_idx);
6346 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6347 ipa_trace_buffer_ctrl_curr))
6348 return;
6350 trace_debug ("Lib: Committed %08x -> %08x",
6351 ipa_trace_buffer_ctrl_curr_old,
6352 ipa_trace_buffer_ctrl_curr);
6354 /* Re-read these, now that we've installed the
6355 `about_to_request_buffer_space' breakpoint/lock. A thread could
6356 have finished a traceframe between the last read of these
6357 counters and setting the breakpoint above. If we start
6358 uploading, we never want to leave this function with
6359 traceframe_read_count != 0, otherwise, GDBserver could end up
6360 incrementing the counter tokens more than once (due to event loop
6361 nesting), which would break the IP agent's "effective" detection
6362 (see trace_alloc_trace_buffer). */
6363 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6364 &ipa_traceframe_read_count))
6365 return;
6366 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6367 &ipa_traceframe_write_count))
6368 return;
6370 if (debug_threads)
6372 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
6373 ipa_traceframe_write_count - ipa_traceframe_read_count,
6374 ipa_traceframe_write_count, ipa_traceframe_read_count);
6376 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
6377 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
6378 trace_debug ("note that ipa_traceframe_count's parts changed");
6381 /* Get the address of the current TBC object (the IP agent has an
6382 array of 3 such objects). The index is stored in the TBC
6383 token. */
6384 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
6385 ipa_trace_buffer_ctrl_addr
6386 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
6388 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
6389 (unsigned char *) &ipa_trace_buffer_ctrl,
6390 sizeof (struct ipa_trace_buffer_control)))
6391 return;
6393 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
6394 &ipa_trace_buffer_lo))
6395 return;
6396 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
6397 &ipa_trace_buffer_hi))
6398 return;
6400 /* Offsets are easier to grok for debugging than raw addresses,
6401 especially for the small trace buffer sizes that are useful for
6402 testing. */
6403 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6404 "endfree=%d wrap=%d hi=%d",
6405 curr_tbctrl_idx,
6406 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6407 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6408 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6409 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6410 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6412 /* Note that the IPA's buffer is always circular. */
6414 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6416 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6417 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6419 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6420 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6421 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6422 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6423 : 0))
6425 tf = IPA_FIRST_TRACEFRAME ();
6427 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6429 struct tracepoint *tpoint;
6430 struct traceframe *tframe;
6431 unsigned char *block;
6432 struct traceframe ipa_tframe;
6434 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6435 offsetof (struct traceframe, data)))
6436 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6438 if (ipa_tframe.tpnum == 0)
6440 internal_error ("Uploading: No (more) fast traceframes, but"
6441 " ipa_traceframe_count == %u??\n",
6442 ipa_traceframe_write_count
6443 - ipa_traceframe_read_count);
6446 /* Note that this will be incorrect for multi-location
6447 tracepoints... */
6448 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6450 tframe = add_traceframe (tpoint);
6451 if (tframe == NULL)
6453 trace_buffer_is_full = 1;
6454 trace_debug ("Uploading: trace buffer is full");
6456 else
6458 /* Copy the whole set of blocks in one go for now. FIXME:
6459 split this in smaller blocks. */
6460 block = add_traceframe_block (tframe, tpoint,
6461 ipa_tframe.data_size);
6462 if (block != NULL)
6464 if (read_inferior_memory (tf
6465 + offsetof (struct traceframe, data),
6466 block, ipa_tframe.data_size))
6467 error ("Uploading: Couldn't read traceframe data at %s\n",
6468 paddress (tf + offsetof (struct traceframe, data)));
6471 trace_debug ("Uploading: traceframe didn't fit");
6472 finish_traceframe (tframe);
6475 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6477 /* If we freed the traceframe that wrapped around, go back
6478 to the non-wrap case. */
6479 if (tf < ipa_trace_buffer_ctrl.start)
6481 trace_debug ("Lib: Discarding past the wraparound");
6482 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6484 ipa_trace_buffer_ctrl.start = tf;
6485 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6486 ++ipa_traceframe_read_count;
6488 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6489 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6491 trace_debug ("Lib: buffer is fully empty. "
6492 "Trace buffer [%d] start=%d free=%d endfree=%d",
6493 curr_tbctrl_idx,
6494 (int) (ipa_trace_buffer_ctrl.start
6495 - ipa_trace_buffer_lo),
6496 (int) (ipa_trace_buffer_ctrl.free
6497 - ipa_trace_buffer_lo),
6498 (int) (ipa_trace_buffer_ctrl.end_free
6499 - ipa_trace_buffer_lo));
6501 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6502 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6503 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6504 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6507 trace_debug ("Uploaded a traceframe\n"
6508 "Lib: Trace buffer [%d] start=%d free=%d "
6509 "endfree=%d wrap=%d hi=%d",
6510 curr_tbctrl_idx,
6511 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6512 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6513 (int) (ipa_trace_buffer_ctrl.end_free
6514 - ipa_trace_buffer_lo),
6515 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6516 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6519 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6520 (unsigned char *) &ipa_trace_buffer_ctrl,
6521 sizeof (struct ipa_trace_buffer_control)))
6522 return;
6524 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6525 ipa_traceframe_read_count);
6527 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6529 target_pause_all (true);
6531 delete_breakpoint (about_to_request_buffer_space_bkpt);
6532 about_to_request_buffer_space_bkpt = NULL;
6534 target_unpause_all (true);
6536 if (trace_buffer_is_full)
6537 stop_tracing ();
6539 #endif
6541 #ifdef IN_PROCESS_AGENT
6543 IP_AGENT_EXPORT_VAR int ust_loaded;
6544 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6546 #ifdef HAVE_UST
6548 /* Static tracepoints. */
6550 /* UST puts a "struct tracepoint" in the global namespace, which
6551 conflicts with our tracepoint. Arguably, being a library, it
6552 shouldn't take ownership of such a generic name. We work around it
6553 here. */
6554 #define tracepoint ust_tracepoint
6555 #include <ust/ust.h>
6556 #undef tracepoint
6558 extern int serialize_to_text (char *outbuf, int bufsize,
6559 const char *fmt, va_list ap);
6561 #define GDB_PROBE_NAME "gdb"
6563 /* We dynamically search for the UST symbols instead of linking them
6564 in. This lets the user decide if the application uses static
6565 tracepoints, instead of always pulling libust.so in. This vector
6566 holds pointers to all functions we care about. */
6568 static struct
6570 int (*serialize_to_text) (char *outbuf, int bufsize,
6571 const char *fmt, va_list ap);
6573 int (*ltt_probe_register) (struct ltt_available_probe *pdata);
6574 int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
6576 int (*ltt_marker_connect) (const char *channel, const char *mname,
6577 const char *pname);
6578 int (*ltt_marker_disconnect) (const char *channel, const char *mname,
6579 const char *pname);
6581 void (*marker_iter_start) (struct marker_iter *iter);
6582 void (*marker_iter_next) (struct marker_iter *iter);
6583 void (*marker_iter_stop) (struct marker_iter *iter);
6584 void (*marker_iter_reset) (struct marker_iter *iter);
6585 } ust_ops;
6587 #include <dlfcn.h>
6589 /* Cast through typeof to catch incompatible API changes. Since UST
6590 only builds with gcc, we can freely use gcc extensions here
6591 too. */
6592 #define GET_UST_SYM(SYM) \
6593 do \
6595 if (ust_ops.SYM == NULL) \
6596 ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM); \
6597 if (ust_ops.SYM == NULL) \
6598 return 0; \
6599 } while (0)
6601 #define USTF(SYM) ust_ops.SYM
6603 /* Get pointers to all libust.so functions we care about. */
6605 static int
6606 dlsym_ust (void)
6608 GET_UST_SYM (serialize_to_text);
6610 GET_UST_SYM (ltt_probe_register);
6611 GET_UST_SYM (ltt_probe_unregister);
6612 GET_UST_SYM (ltt_marker_connect);
6613 GET_UST_SYM (ltt_marker_disconnect);
6615 GET_UST_SYM (marker_iter_start);
6616 GET_UST_SYM (marker_iter_next);
6617 GET_UST_SYM (marker_iter_stop);
6618 GET_UST_SYM (marker_iter_reset);
6620 ust_loaded = 1;
6621 return 1;
6624 /* Given an UST marker, return the matching gdb static tracepoint.
6625 The match is done by address. */
6627 static struct tracepoint *
6628 ust_marker_to_static_tracepoint (const struct marker *mdata)
6630 struct tracepoint *tpoint;
6632 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
6634 if (tpoint->type != static_tracepoint)
6635 continue;
6637 if (tpoint->address == (uintptr_t) mdata->location)
6638 return tpoint;
6641 return NULL;
6644 /* The probe function we install on lttng/ust markers. Whenever a
6645 probed ust marker is hit, this function is called. This is similar
6646 to gdb_collect, only for static tracepoints, instead of fast
6647 tracepoints. */
6649 static void
6650 gdb_probe (const struct marker *mdata, void *probe_private,
6651 struct registers *regs, void *call_private,
6652 const char *fmt, va_list *args)
6654 struct tracepoint *tpoint;
6655 struct static_tracepoint_ctx ctx;
6656 const struct target_desc *ipa_tdesc;
6658 /* Don't do anything until the trace run is completely set up. */
6659 if (!tracing)
6661 trace_debug ("gdb_probe: not tracing\n");
6662 return;
6665 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
6666 ctx.base.type = static_tracepoint;
6667 ctx.regcache_initted = 0;
6668 ctx.regs = regs;
6669 ctx.fmt = fmt;
6670 ctx.args = args;
6672 /* Wrap the regblock in a register cache (in the stack, we don't
6673 want to malloc here). */
6674 ctx.regspace = alloca (ipa_tdesc->registers_size);
6675 if (ctx.regspace == NULL)
6677 trace_debug ("Trace buffer block allocation failed, skipping");
6678 return;
6681 tpoint = ust_marker_to_static_tracepoint (mdata);
6682 if (tpoint == NULL)
6684 trace_debug ("gdb_probe: marker not known: "
6685 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6686 mdata->location, mdata->channel,
6687 mdata->name, mdata->format);
6688 return;
6691 if (!tpoint->enabled)
6693 trace_debug ("gdb_probe: tracepoint disabled");
6694 return;
6697 ctx.tpoint = tpoint;
6699 trace_debug ("gdb_probe: collecting marker: "
6700 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6701 mdata->location, mdata->channel,
6702 mdata->name, mdata->format);
6704 /* Test the condition if present, and collect if true. */
6705 if (tpoint->cond == NULL
6706 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6707 tpoint))
6709 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6710 tpoint->address, tpoint);
6712 if (stopping_tracepoint
6713 || trace_buffer_is_full
6714 || expr_eval_result != expr_eval_no_error)
6715 stop_tracing ();
6717 else
6719 /* If there was a condition and it evaluated to false, the only
6720 way we would stop tracing is if there was an error during
6721 condition expression evaluation. */
6722 if (expr_eval_result != expr_eval_no_error)
6723 stop_tracing ();
6727 /* Called if the gdb static tracepoint requested collecting "$_sdata",
6728 static tracepoint string data. This is a string passed to the
6729 tracing library by the user, at the time of the tracepoint marker
6730 call. E.g., in the UST marker call:
6732 trace_mark (ust, bar33, "str %s", "FOOBAZ");
6734 the collected data is "str FOOBAZ".
6737 static void
6738 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
6739 struct traceframe *tframe)
6741 struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
6742 unsigned char *bufspace;
6743 int size;
6744 va_list copy;
6745 unsigned short blocklen;
6747 if (umd == NULL)
6749 trace_debug ("Wanted to collect static trace data, "
6750 "but there's no static trace data");
6751 return;
6754 va_copy (copy, *umd->args);
6755 size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
6756 va_end (copy);
6758 trace_debug ("Want to collect ust data");
6760 /* 'S' + size + string */
6761 bufspace = add_traceframe_block (tframe, umd->tpoint,
6762 1 + sizeof (blocklen) + size + 1);
6763 if (bufspace == NULL)
6765 trace_debug ("Trace buffer block allocation failed, skipping");
6766 return;
6769 /* Identify a static trace data block. */
6770 *bufspace = 'S';
6772 blocklen = size + 1;
6773 memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
6775 va_copy (copy, *umd->args);
6776 USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
6777 size + 1, umd->fmt, copy);
6778 va_end (copy);
6780 trace_debug ("Storing static tracepoint data in regblock: %s",
6781 bufspace + 1 + sizeof (blocklen));
6784 /* The probe to register with lttng/ust. */
6785 static struct ltt_available_probe gdb_ust_probe =
6787 GDB_PROBE_NAME,
6788 NULL,
6789 gdb_probe,
6792 #endif /* HAVE_UST */
6793 #endif /* IN_PROCESS_AGENT */
6795 #ifndef IN_PROCESS_AGENT
6797 /* Ask the in-process agent to run a command. Since we don't want to
6798 have to handle the IPA hitting breakpoints while running the
6799 command, we pause all threads, remove all breakpoints, and then set
6800 the helper thread re-running. We communicate with the helper
6801 thread by means of direct memory xfering, and a socket for
6802 synchronization. */
6804 static int
6805 run_inferior_command (char *cmd, int len)
6807 int err = -1;
6808 int pid = current_ptid.pid ();
6810 trace_debug ("run_inferior_command: running: %s", cmd);
6812 target_pause_all (false);
6813 uninsert_all_breakpoints ();
6815 err = agent_run_command (pid, cmd, len);
6817 reinsert_all_breakpoints ();
6818 target_unpause_all (false);
6820 return err;
6823 #else /* !IN_PROCESS_AGENT */
6825 #include <sys/socket.h>
6826 #include <sys/un.h>
6828 #ifndef UNIX_PATH_MAX
6829 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6830 #endif
6832 /* Where we put the socked used for synchronization. */
6833 #define SOCK_DIR P_tmpdir
6835 /* Thread ID of the helper thread. GDBserver reads this to know which
6836 is the help thread. This is an LWP id on Linux. */
6837 extern "C" {
6838 IP_AGENT_EXPORT_VAR int helper_thread_id;
6841 static int
6842 init_named_socket (const char *name)
6844 int result, fd;
6845 struct sockaddr_un addr;
6847 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6848 if (result == -1)
6850 warning ("socket creation failed: %s", safe_strerror (errno));
6851 return -1;
6854 addr.sun_family = AF_UNIX;
6856 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6858 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6859 return -1;
6862 strcpy (addr.sun_path, name);
6864 result = access (name, F_OK);
6865 if (result == 0)
6867 /* File exists. */
6868 result = unlink (name);
6869 if (result == -1)
6871 warning ("unlink failed: %s", safe_strerror (errno));
6872 close (fd);
6873 return -1;
6875 warning ("socket %s already exists; overwriting", name);
6878 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6879 if (result == -1)
6881 warning ("bind failed: %s", safe_strerror (errno));
6882 close (fd);
6883 return -1;
6886 result = listen (fd, 1);
6887 if (result == -1)
6889 warning ("listen: %s", safe_strerror (errno));
6890 close (fd);
6891 return -1;
6894 return fd;
6897 static char agent_socket_name[UNIX_PATH_MAX];
6899 static int
6900 gdb_agent_socket_init (void)
6902 int result, fd;
6904 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6905 SOCK_DIR, getpid ());
6906 if (result >= UNIX_PATH_MAX)
6908 trace_debug ("string overflow allocating socket name");
6909 return -1;
6912 fd = init_named_socket (agent_socket_name);
6913 if (fd < 0)
6914 warning ("Error initializing named socket (%s) for communication with the "
6915 "ust helper thread. Check that directory exists and that it "
6916 "is writable.", agent_socket_name);
6918 return fd;
6921 #ifdef HAVE_UST
6923 /* The next marker to be returned on a qTsSTM command. */
6924 static const struct marker *next_st;
6926 /* Returns the first known marker. */
6928 struct marker *
6929 first_marker (void)
6931 struct marker_iter iter;
6933 USTF(marker_iter_reset) (&iter);
6934 USTF(marker_iter_start) (&iter);
6936 return iter.marker;
6939 /* Returns the marker following M. */
6941 const struct marker *
6942 next_marker (const struct marker *m)
6944 struct marker_iter iter;
6946 USTF(marker_iter_reset) (&iter);
6947 USTF(marker_iter_start) (&iter);
6949 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
6951 if (iter.marker == m)
6953 USTF(marker_iter_next) (&iter);
6954 return iter.marker;
6958 return NULL;
6961 /* Return an hexstr version of the STR C string, fit for sending to
6962 GDB. */
6964 static char *
6965 cstr_to_hexstr (const char *str)
6967 int len = strlen (str);
6968 char *hexstr = xmalloc (len * 2 + 1);
6969 bin2hex ((gdb_byte *) str, hexstr, len);
6970 return hexstr;
6973 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
6974 packets. */
6976 static void
6977 response_ust_marker (char *packet, const struct marker *st)
6979 char *strid, *format, *tmp;
6981 next_st = next_marker (st);
6983 tmp = xmalloc (strlen (st->channel) + 1 +
6984 strlen (st->name) + 1);
6985 sprintf (tmp, "%s/%s", st->channel, st->name);
6987 strid = cstr_to_hexstr (tmp);
6988 free (tmp);
6990 format = cstr_to_hexstr (st->format);
6992 sprintf (packet, "m%s:%s:%s",
6993 paddress ((uintptr_t) st->location),
6994 strid,
6995 format);
6997 free (strid);
6998 free (format);
7001 /* Return the first static tracepoint, and initialize the state
7002 machine that will iterate through all the static tracepoints. */
7004 static void
7005 cmd_qtfstm (char *packet)
7007 trace_debug ("Returning first trace state variable definition");
7009 if (first_marker ())
7010 response_ust_marker (packet, first_marker ());
7011 else
7012 strcpy (packet, "l");
7015 /* Return additional trace state variable definitions. */
7017 static void
7018 cmd_qtsstm (char *packet)
7020 trace_debug ("Returning static tracepoint");
7022 if (next_st)
7023 response_ust_marker (packet, next_st);
7024 else
7025 strcpy (packet, "l");
7028 /* Disconnect the GDB probe from a marker at a given address. */
7030 static void
7031 unprobe_marker_at (char *packet)
7033 char *p = packet;
7034 ULONGEST address;
7035 struct marker_iter iter;
7037 p += sizeof ("unprobe_marker_at:") - 1;
7039 p = unpack_varlen_hex (p, &address);
7041 USTF(marker_iter_reset) (&iter);
7042 USTF(marker_iter_start) (&iter);
7043 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7044 if ((uintptr_t ) iter.marker->location == address)
7046 int result;
7048 result = USTF(ltt_marker_disconnect) (iter.marker->channel,
7049 iter.marker->name,
7050 GDB_PROBE_NAME);
7051 if (result < 0)
7052 warning ("could not disable marker %s/%s",
7053 iter.marker->channel, iter.marker->name);
7054 break;
7058 /* Connect the GDB probe to a marker at a given address. */
7060 static int
7061 probe_marker_at (char *packet)
7063 char *p = packet;
7064 ULONGEST address;
7065 struct marker_iter iter;
7066 struct marker *m;
7068 p += sizeof ("probe_marker_at:") - 1;
7070 p = unpack_varlen_hex (p, &address);
7072 USTF(marker_iter_reset) (&iter);
7074 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7075 m != NULL;
7076 USTF(marker_iter_next) (&iter), m = iter.marker)
7077 if ((uintptr_t ) m->location == address)
7079 int result;
7081 trace_debug ("found marker for address. "
7082 "ltt_marker_connect (marker = %s/%s)",
7083 m->channel, m->name);
7085 result = USTF(ltt_marker_connect) (m->channel, m->name,
7086 GDB_PROBE_NAME);
7087 if (result && result != -EEXIST)
7088 trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
7089 m->channel, m->name, -result);
7091 if (result < 0)
7093 sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
7094 m->channel, m->name);
7095 return -1;
7098 strcpy (packet, "OK");
7099 return 0;
7102 sprintf (packet, "E.no marker found at 0x%s", paddress (address));
7103 return -1;
7106 static int
7107 cmd_qtstmat (char *packet)
7109 char *p = packet;
7110 ULONGEST address;
7111 struct marker_iter iter;
7112 struct marker *m;
7114 p += sizeof ("qTSTMat:") - 1;
7116 p = unpack_varlen_hex (p, &address);
7118 USTF(marker_iter_reset) (&iter);
7120 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7121 m != NULL;
7122 USTF(marker_iter_next) (&iter), m = iter.marker)
7123 if ((uintptr_t ) m->location == address)
7125 response_ust_marker (packet, m);
7126 return 0;
7129 strcpy (packet, "l");
7130 return -1;
7133 static void
7134 gdb_ust_init (void)
7136 if (!dlsym_ust ())
7137 return;
7139 USTF(ltt_probe_register) (&gdb_ust_probe);
7142 #endif /* HAVE_UST */
7144 #include <sys/syscall.h>
7146 static void
7147 gdb_agent_remove_socket (void)
7149 unlink (agent_socket_name);
7152 /* Helper thread of agent. */
7154 static void *
7155 gdb_agent_helper_thread (void *arg)
7157 int listen_fd;
7159 atexit (gdb_agent_remove_socket);
7161 while (1)
7163 listen_fd = gdb_agent_socket_init ();
7165 if (helper_thread_id == 0)
7166 helper_thread_id = syscall (SYS_gettid);
7168 if (listen_fd == -1)
7170 warning ("could not create sync socket");
7171 break;
7174 while (1)
7176 socklen_t tmp;
7177 struct sockaddr_un sockaddr;
7178 int fd;
7179 char buf[1];
7180 int ret;
7181 int stop_loop = 0;
7183 tmp = sizeof (sockaddr);
7187 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
7189 /* It seems an ERESTARTSYS can escape out of accept. */
7190 while (fd == -512 || (fd == -1 && errno == EINTR));
7192 if (fd < 0)
7194 warning ("Accept returned %d, error: %s",
7195 fd, safe_strerror (errno));
7196 break;
7201 ret = read (fd, buf, 1);
7202 } while (ret == -1 && errno == EINTR);
7204 if (ret == -1)
7206 warning ("reading socket (fd=%d) failed with %s",
7207 fd, safe_strerror (errno));
7208 close (fd);
7209 break;
7212 if (cmd_buf[0])
7214 if (startswith (cmd_buf, "close"))
7216 stop_loop = 1;
7218 #ifdef HAVE_UST
7219 else if (strcmp ("qTfSTM", cmd_buf) == 0)
7221 cmd_qtfstm (cmd_buf);
7223 else if (strcmp ("qTsSTM", cmd_buf) == 0)
7225 cmd_qtsstm (cmd_buf);
7227 else if (startswith (cmd_buf, "unprobe_marker_at:"))
7229 unprobe_marker_at (cmd_buf);
7231 else if (startswith (cmd_buf, "probe_marker_at:"))
7233 probe_marker_at (cmd_buf);
7235 else if (startswith (cmd_buf, "qTSTMat:"))
7237 cmd_qtstmat (cmd_buf);
7239 #endif /* HAVE_UST */
7242 /* Fix compiler's warning: ignoring return value of 'write'. */
7243 ret = write (fd, buf, 1);
7244 close (fd);
7246 if (stop_loop)
7248 close (listen_fd);
7249 unlink (agent_socket_name);
7251 /* Sleep endlessly to wait the whole inferior stops. This
7252 thread can not exit because GDB or GDBserver may still need
7253 'current_thread' (representing this thread) to access
7254 inferior memory. Otherwise, this thread exits earlier than
7255 other threads, and 'current_thread' is set to NULL. */
7256 while (1)
7257 sleep (10);
7262 return NULL;
7265 #include <signal.h>
7266 #include <pthread.h>
7268 extern "C" {
7269 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
7272 static void
7273 gdb_agent_init (void)
7275 int res;
7276 pthread_t thread;
7277 sigset_t new_mask;
7278 sigset_t orig_mask;
7280 /* We want the helper thread to be as transparent as possible, so
7281 have it inherit an all-signals-blocked mask. */
7283 sigfillset (&new_mask);
7284 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
7285 if (res)
7286 perror_with_name ("pthread_sigmask (1)");
7288 res = pthread_create (&thread,
7289 NULL,
7290 gdb_agent_helper_thread,
7291 NULL);
7293 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
7294 if (res)
7295 perror_with_name ("pthread_sigmask (2)");
7297 while (helper_thread_id == 0)
7298 usleep (1);
7300 #ifdef HAVE_UST
7301 gdb_ust_init ();
7302 #endif
7305 #include <sys/mman.h>
7307 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
7308 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
7309 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
7310 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
7311 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
7312 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
7314 /* Record the result of getting buffer space for fast tracepoint
7315 trampolines. Any error message is copied, since caller may not be
7316 using persistent storage. */
7318 void
7319 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
7321 gdb_trampoline_buffer = (char *) (uintptr_t) begin;
7322 gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
7323 if (errmsg)
7324 strncpy (gdb_trampoline_buffer_error, errmsg, 99);
7325 else
7326 strcpy (gdb_trampoline_buffer_error, "no buffer passed");
7329 static void __attribute__ ((constructor))
7330 initialize_tracepoint_ftlib (void)
7332 initialize_tracepoint ();
7334 gdb_agent_init ();
7337 #ifndef HAVE_GETAUXVAL
7338 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
7339 found, 0 is returned. This function is provided if glibc is too old. */
7341 unsigned long
7342 getauxval (unsigned long type)
7344 unsigned long data[2];
7345 FILE *f = fopen ("/proc/self/auxv", "r");
7346 unsigned long value = 0;
7348 if (f == NULL)
7349 return 0;
7351 while (fread (data, sizeof (data), 1, f) > 0)
7353 if (data[0] == type)
7355 value = data[1];
7356 break;
7360 fclose (f);
7361 return value;
7363 #endif
7365 #endif /* IN_PROCESS_AGENT */
7367 /* Return a timestamp, expressed as microseconds of the usual Unix
7368 time. (As the result is a 64-bit number, it will not overflow any
7369 time soon.) */
7371 static LONGEST
7372 get_timestamp (void)
7374 using namespace std::chrono;
7376 steady_clock::time_point now = steady_clock::now ();
7377 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
7380 void
7381 initialize_tracepoint (void)
7383 /* Start with the default size. */
7384 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
7386 /* Wire trace state variable 1 to be the timestamp. This will be
7387 uploaded to GDB upon connection and become one of its trace state
7388 variables. (In case you're wondering, if GDB already has a trace
7389 variable numbered 1, it will be renumbered.) */
7390 create_trace_state_variable (1, 0);
7391 set_trace_state_variable_name (1, "trace_timestamp");
7392 set_trace_state_variable_getter (1, get_timestamp);
7394 #ifdef IN_PROCESS_AGENT
7396 int pagesize;
7397 size_t jump_pad_size;
7399 pagesize = sysconf (_SC_PAGE_SIZE);
7400 if (pagesize == -1)
7401 perror_with_name ("sysconf");
7403 #define SCRATCH_BUFFER_NPAGES 20
7405 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
7407 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
7408 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
7409 if (gdb_jump_pad_buffer == NULL)
7410 perror_with_name ("mmap");
7411 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
7414 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
7416 /* It's not a fatal error for something to go wrong with trampoline
7417 buffer setup, but it can be mysterious, so create a channel to
7418 report back on what went wrong, using a fixed size since we may
7419 not be able to allocate space later when the problem occurs. */
7420 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
7422 strcpy (gdb_trampoline_buffer_error, "No errors reported");
7424 initialize_low_tracepoint ();
7425 #endif