Automatic date update in version.in
[binutils-gdb.git] / gdbserver / tracepoint.cc
blob18b2b0b3d779e0347f1ce4ce1b1e5d84a7934e1f
1 /* Tracepoint code for remote server for GDB.
2 Copyright (C) 2009-2022 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
348 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
350 memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
351 return 0;
354 /* Call this in the functions where GDBserver places a breakpoint, so
355 that the compiler doesn't try to be clever and skip calling the
356 function at all. This is necessary, even if we tell the compiler
357 to not inline said functions. */
359 #if defined(__GNUC__)
360 # define UNKNOWN_SIDE_EFFECTS() asm ("")
361 #else
362 # define UNKNOWN_SIDE_EFFECTS() do {} while (0)
363 #endif
365 /* This is needed for -Wmissing-declarations. */
366 IP_AGENT_EXPORT_FUNC void stop_tracing (void);
368 IP_AGENT_EXPORT_FUNC void
369 stop_tracing (void)
371 /* GDBserver places breakpoint here. */
372 UNKNOWN_SIDE_EFFECTS();
375 /* This is needed for -Wmissing-declarations. */
376 IP_AGENT_EXPORT_FUNC void flush_trace_buffer (void);
378 IP_AGENT_EXPORT_FUNC void
379 flush_trace_buffer (void)
381 /* GDBserver places breakpoint here. */
382 UNKNOWN_SIDE_EFFECTS();
385 #endif
387 #ifndef IN_PROCESS_AGENT
388 static int
389 tracepoint_handler (CORE_ADDR address)
391 trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
392 paddress (address));
393 return 0;
396 /* Breakpoint at "stop_tracing" in the inferior lib. */
397 static struct breakpoint *stop_tracing_bkpt;
398 static int stop_tracing_handler (CORE_ADDR);
400 /* Breakpoint at "flush_trace_buffer" in the inferior lib. */
401 static struct breakpoint *flush_trace_buffer_bkpt;
402 static int flush_trace_buffer_handler (CORE_ADDR);
404 static void download_trace_state_variables (void);
405 static void upload_fast_traceframes (void);
407 static int run_inferior_command (char *cmd, int len);
409 static int
410 read_inferior_integer (CORE_ADDR symaddr, int *val)
412 return read_inferior_memory (symaddr, (unsigned char *) val,
413 sizeof (*val));
416 struct tracepoint;
417 static int tracepoint_send_agent (struct tracepoint *tpoint);
419 static int
420 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
422 return read_inferior_memory (symaddr, (unsigned char *) val,
423 sizeof (*val));
426 static int
427 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
429 void *pval = (void *) (uintptr_t) val;
430 int ret;
432 ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
433 *val = (uintptr_t) pval;
434 return ret;
437 static int
438 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
440 void *pval = (void *) (uintptr_t) val;
441 return target_write_memory (symaddr,
442 (unsigned char *) &pval, sizeof (pval));
445 static int
446 write_inferior_integer (CORE_ADDR symaddr, int val)
448 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
451 static int
452 write_inferior_int8 (CORE_ADDR symaddr, int8_t val)
454 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
457 static int
458 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
460 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
463 static CORE_ADDR target_malloc (ULONGEST size);
465 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD) \
466 do { \
467 memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
468 BUF += sizeof ((OBJ)->FIELD); \
469 } while (0)
471 #endif
473 /* Base action. Concrete actions inherit this. */
475 struct tracepoint_action
477 char type;
480 /* An 'M' (collect memory) action. */
481 struct collect_memory_action
483 struct tracepoint_action base;
485 ULONGEST addr;
486 ULONGEST len;
487 int32_t basereg;
490 /* An 'R' (collect registers) action. */
492 struct collect_registers_action
494 struct tracepoint_action base;
497 /* An 'X' (evaluate expression) action. */
499 struct eval_expr_action
501 struct tracepoint_action base;
503 struct agent_expr *expr;
506 /* An 'L' (collect static trace data) action. */
507 struct collect_static_trace_data_action
509 struct tracepoint_action base;
512 #ifndef IN_PROCESS_AGENT
513 static CORE_ADDR
514 m_tracepoint_action_download (const struct tracepoint_action *action)
516 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_memory_action));
518 target_write_memory (ipa_action, (unsigned char *) action,
519 sizeof (struct collect_memory_action));
521 return ipa_action;
523 static char *
524 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
526 struct collect_memory_action *maction
527 = (struct collect_memory_action *) action;
529 COPY_FIELD_TO_BUF (buffer, maction, addr);
530 COPY_FIELD_TO_BUF (buffer, maction, len);
531 COPY_FIELD_TO_BUF (buffer, maction, basereg);
533 return buffer;
536 static CORE_ADDR
537 r_tracepoint_action_download (const struct tracepoint_action *action)
539 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_registers_action));
541 target_write_memory (ipa_action, (unsigned char *) action,
542 sizeof (struct collect_registers_action));
544 return ipa_action;
547 static char *
548 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
550 return buffer;
553 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
555 static CORE_ADDR
556 x_tracepoint_action_download (const struct tracepoint_action *action)
558 CORE_ADDR ipa_action = target_malloc (sizeof (struct eval_expr_action));
559 CORE_ADDR expr;
561 target_write_memory (ipa_action, (unsigned char *) action,
562 sizeof (struct eval_expr_action));
563 expr = download_agent_expr (((struct eval_expr_action *) action)->expr);
564 write_inferior_data_pointer (ipa_action
565 + offsetof (struct eval_expr_action, expr),
566 expr);
568 return ipa_action;
571 /* Copy agent expression AEXPR to buffer pointed by P. If AEXPR is NULL,
572 copy 0 to P. Return updated header of buffer. */
574 static char *
575 agent_expr_send (char *p, const struct agent_expr *aexpr)
577 /* Copy the length of condition first, and then copy its
578 content. */
579 if (aexpr == NULL)
581 memset (p, 0, 4);
582 p += 4;
584 else
586 memcpy (p, &aexpr->length, 4);
587 p +=4;
589 memcpy (p, aexpr->bytes, aexpr->length);
590 p += aexpr->length;
592 return p;
595 static char *
596 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
598 struct eval_expr_action *eaction = (struct eval_expr_action *) action;
600 return agent_expr_send (buffer, eaction->expr);
603 static CORE_ADDR
604 l_tracepoint_action_download (const struct tracepoint_action *action)
606 CORE_ADDR ipa_action
607 = target_malloc (sizeof (struct collect_static_trace_data_action));
609 target_write_memory (ipa_action, (unsigned char *) action,
610 sizeof (struct collect_static_trace_data_action));
612 return ipa_action;
615 static char *
616 l_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
618 return buffer;
621 static char *
622 tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
624 switch (action->type)
626 case 'M':
627 return m_tracepoint_action_send (buffer, action);
628 case 'R':
629 return r_tracepoint_action_send (buffer, action);
630 case 'X':
631 return x_tracepoint_action_send (buffer, action);
632 case 'L':
633 return l_tracepoint_action_send (buffer, action);
635 error ("Unknown trace action '%c'.", action->type);
638 static CORE_ADDR
639 tracepoint_action_download (const struct tracepoint_action *action)
641 switch (action->type)
643 case 'M':
644 return m_tracepoint_action_download (action);
645 case 'R':
646 return r_tracepoint_action_download (action);
647 case 'X':
648 return x_tracepoint_action_download (action);
649 case 'L':
650 return l_tracepoint_action_download (action);
652 error ("Unknown trace action '%c'.", action->type);
654 #endif
656 /* This structure describes a piece of the source-level definition of
657 the tracepoint. The contents are not interpreted by the target,
658 but preserved verbatim for uploading upon reconnection. */
660 struct source_string
662 /* The type of string, such as "cond" for a conditional. */
663 char *type;
665 /* The source-level string itself. For the sake of target
666 debugging, we store it in plaintext, even though it is always
667 transmitted in hex. */
668 char *str;
670 /* Link to the next one in the list. We link them in the order
671 received, in case some make up an ordered list of commands or
672 some such. */
673 struct source_string *next;
676 enum tracepoint_type
678 /* Trap based tracepoint. */
679 trap_tracepoint,
681 /* A fast tracepoint implemented with a jump instead of a trap. */
682 fast_tracepoint,
684 /* A static tracepoint, implemented by a program call into a tracing
685 library. */
686 static_tracepoint
689 struct tracepoint_hit_ctx;
691 typedef enum eval_result_type (*condfn) (unsigned char *,
692 ULONGEST *);
694 /* The definition of a tracepoint. */
696 /* Tracepoints may have multiple locations, each at a different
697 address. This can occur with optimizations, template
698 instantiation, etc. Since the locations may be in different
699 scopes, the conditions and actions may be different for each
700 location. Our target version of tracepoints is more like GDB's
701 notion of "breakpoint locations", but we have almost nothing that
702 is not per-location, so we bother having two kinds of objects. The
703 key consequence is that numbers are not unique, and that it takes
704 both number and address to identify a tracepoint uniquely. */
706 struct tracepoint
708 /* The number of the tracepoint, as specified by GDB. Several
709 tracepoint objects here may share a number. */
710 uint32_t number;
712 /* Address at which the tracepoint is supposed to trigger. Several
713 tracepoints may share an address. */
714 CORE_ADDR address;
716 /* Tracepoint type. */
717 enum tracepoint_type type;
719 /* True if the tracepoint is currently enabled. */
720 int8_t enabled;
722 /* The number of single steps that will be performed after each
723 tracepoint hit. */
724 uint64_t step_count;
726 /* The number of times the tracepoint may be hit before it will
727 terminate the entire tracing run. */
728 uint64_t pass_count;
730 /* Pointer to the agent expression that is the tracepoint's
731 conditional, or NULL if the tracepoint is unconditional. */
732 struct agent_expr *cond;
734 /* The list of actions to take when the tracepoint triggers. */
735 uint32_t numactions;
736 struct tracepoint_action **actions;
738 /* Count of the times we've hit this tracepoint during the run.
739 Note that while-stepping steps are not counted as "hits". */
740 uint64_t hit_count;
742 /* Cached sum of the sizes of traceframes created by this point. */
743 uint64_t traceframe_usage;
745 CORE_ADDR compiled_cond;
747 /* Link to the next tracepoint in the list. */
748 struct tracepoint *next;
750 #ifndef IN_PROCESS_AGENT
751 /* The list of actions to take when the tracepoint triggers, in
752 string/packet form. */
753 char **actions_str;
755 /* The collection of strings that describe the tracepoint as it was
756 entered into GDB. These are not used by the target, but are
757 reported back to GDB upon reconnection. */
758 struct source_string *source_strings;
760 /* The number of bytes displaced by fast tracepoints. It may subsume
761 multiple instructions, for multi-byte fast tracepoints. This
762 field is only valid for fast tracepoints. */
763 uint32_t orig_size;
765 /* Only for fast tracepoints. */
766 CORE_ADDR obj_addr_on_target;
768 /* Address range where the original instruction under a fast
769 tracepoint was relocated to. (_end is actually one byte past
770 the end). */
771 CORE_ADDR adjusted_insn_addr;
772 CORE_ADDR adjusted_insn_addr_end;
774 /* The address range of the piece of the jump pad buffer that was
775 assigned to this fast tracepoint. (_end is actually one byte
776 past the end).*/
777 CORE_ADDR jump_pad;
778 CORE_ADDR jump_pad_end;
780 /* The address range of the piece of the trampoline buffer that was
781 assigned to this fast tracepoint. (_end is actually one byte
782 past the end). */
783 CORE_ADDR trampoline;
784 CORE_ADDR trampoline_end;
786 /* The list of actions to take while in a stepping loop. These
787 fields are only valid for patch-based tracepoints. */
788 int num_step_actions;
789 struct tracepoint_action **step_actions;
790 /* Same, but in string/packet form. */
791 char **step_actions_str;
793 /* Handle returned by the breakpoint or tracepoint module when we
794 inserted the trap or jump, or hooked into a static tracepoint.
795 NULL if we haven't inserted it yet. */
796 void *handle;
797 #endif
801 #ifndef IN_PROCESS_AGENT
803 /* Given `while-stepping', a thread may be collecting data for more
804 than one tracepoint simultaneously. On the other hand, the same
805 tracepoint with a while-stepping action may be hit by more than one
806 thread simultaneously (but not quite, each thread could be handling
807 a different step). Each thread holds a list of these objects,
808 representing the current step of each while-stepping action being
809 collected. */
811 struct wstep_state
813 struct wstep_state *next;
815 /* The tracepoint number. */
816 int tp_number;
817 /* The tracepoint's address. */
818 CORE_ADDR tp_address;
820 /* The number of the current step in this 'while-stepping'
821 action. */
822 long current_step;
825 #endif
827 EXTERN_C_PUSH
829 /* The linked list of all tracepoints. Marked explicitly as used as
830 the in-process library doesn't use it for the fast tracepoints
831 support. */
832 IP_AGENT_EXPORT_VAR struct tracepoint *tracepoints;
834 /* The first tracepoint to exceed its pass count. */
836 IP_AGENT_EXPORT_VAR struct tracepoint *stopping_tracepoint;
838 /* True if the trace buffer is full or otherwise no longer usable. */
840 IP_AGENT_EXPORT_VAR int trace_buffer_is_full;
842 /* The first error that occurred during expression evaluation. */
844 /* Stored as an int to avoid the IPA ABI being dependent on whatever
845 the compiler decides to use for the enum's underlying type. Holds
846 enum eval_result_type values. */
847 IP_AGENT_EXPORT_VAR int expr_eval_result = expr_eval_no_error;
849 EXTERN_C_POP
851 #ifndef IN_PROCESS_AGENT
853 /* Pointer to the last tracepoint in the list, new tracepoints are
854 linked in at the end. */
856 static struct tracepoint *last_tracepoint;
858 static const char * const eval_result_names[] =
860 "terror:in the attic", /* this should never be reported */
861 "terror:empty expression",
862 "terror:empty stack",
863 "terror:stack overflow",
864 "terror:stack underflow",
865 "terror:unhandled opcode",
866 "terror:unrecognized opcode",
867 "terror:divide by zero"
870 #endif
872 /* The tracepoint in which the error occurred. */
874 EXTERN_C_PUSH
875 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
876 EXTERN_C_POP
878 struct trace_state_variable
880 /* This is the name of the variable as used in GDB. The target
881 doesn't use the name, but needs to have it for saving and
882 reconnection purposes. */
883 char *name;
885 /* This number identifies the variable uniquely. Numbers may be
886 assigned either by the target (in the case of builtin variables),
887 or by GDB, and are presumed unique during the course of a trace
888 experiment. */
889 int number;
891 /* The variable's initial value, a 64-bit signed integer always. */
892 LONGEST initial_value;
894 /* The variable's value, a 64-bit signed integer always. */
895 LONGEST value;
897 /* Pointer to a getter function, used to supply computed values. */
898 LONGEST (*getter) (void);
900 /* Link to the next variable. */
901 struct trace_state_variable *next;
904 /* Linked list of all trace state variables. */
906 #ifdef IN_PROCESS_AGENT
907 static struct trace_state_variable *alloced_trace_state_variables;
908 #endif
910 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
912 /* The results of tracing go into a fixed-size space known as the
913 "trace buffer". Because usage follows a limited number of
914 patterns, we manage it ourselves rather than with malloc. Basic
915 rules are that we create only one trace frame at a time, each is
916 variable in size, they are never moved once created, and we only
917 discard if we are doing a circular buffer, and then only the oldest
918 ones. Each trace frame includes its own size, so we don't need to
919 link them together, and the trace frame number is relative to the
920 first one, so we don't need to record numbers. A trace frame also
921 records the number of the tracepoint that created it. The data
922 itself is a series of blocks, each introduced by a single character
923 and with a defined format. Each type of block has enough
924 type/length info to allow scanners to jump quickly from one block
925 to the next without reading each byte in the block. */
927 /* Trace buffer management would be simple - advance a free pointer
928 from beginning to end, then stop - were it not for the circular
929 buffer option, which is a useful way to prevent a trace run from
930 stopping prematurely because the buffer filled up. In the circular
931 case, the location of the first trace frame (trace_buffer_start)
932 moves as old trace frames are discarded. Also, since we grow trace
933 frames incrementally as actions are performed, we wrap around to
934 the beginning of the trace buffer. This is per-block, so each
935 block within a trace frame remains contiguous. Things get messy
936 when the wrapped-around trace frame is the one being discarded; the
937 free space ends up in two parts at opposite ends of the buffer. */
939 #ifndef ATTR_PACKED
940 # if defined(__GNUC__)
941 # define ATTR_PACKED __attribute__ ((packed))
942 # else
943 # define ATTR_PACKED /* nothing */
944 # endif
945 #endif
947 /* The data collected at a tracepoint hit. This object should be as
948 small as possible, since there may be a great many of them. We do
949 not need to keep a frame number, because they are all sequential
950 and there are no deletions; so the Nth frame in the buffer is
951 always frame number N. */
953 struct traceframe
955 /* Number of the tracepoint that collected this traceframe. A value
956 of 0 indicates the current end of the trace buffer. We make this
957 a 16-bit field because it's never going to happen that GDB's
958 numbering of tracepoints reaches 32,000. */
959 int tpnum : 16;
961 /* The size of the data in this trace frame. We limit this to 32
962 bits, even on a 64-bit target, because it's just implausible that
963 one is validly going to collect 4 gigabytes of data at a single
964 tracepoint hit. */
965 unsigned int data_size : 32;
967 /* The base of the trace data, which is contiguous from this point. */
968 unsigned char data[0];
970 } ATTR_PACKED;
972 /* The size of the EOB marker, in bytes. A traceframe with zeroed
973 fields (and no data) marks the end of trace data. */
974 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
976 /* This flag is true if the trace buffer is circular, meaning that
977 when it fills, the oldest trace frames are discarded in order to
978 make room. */
980 #ifndef IN_PROCESS_AGENT
981 static int circular_trace_buffer;
982 #endif
984 /* Size of the trace buffer. */
986 static LONGEST trace_buffer_size;
988 EXTERN_C_PUSH
990 /* Pointer to the block of memory that traceframes all go into. */
992 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
994 /* Pointer to the end of the trace buffer, more precisely to the byte
995 after the end of the buffer. */
997 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
999 EXTERN_C_POP
1001 /* Control structure holding the read/write/etc. pointers into the
1002 trace buffer. We need more than one of these to implement a
1003 transaction-like mechanism to guarantees that both GDBserver and the
1004 in-process agent can try to change the trace buffer
1005 simultaneously. */
1007 struct trace_buffer_control
1009 /* Pointer to the first trace frame in the buffer. In the
1010 non-circular case, this is equal to trace_buffer_lo, otherwise it
1011 moves around in the buffer. */
1012 unsigned char *start;
1014 /* Pointer to the free part of the trace buffer. Note that we clear
1015 several bytes at and after this pointer, so that traceframe
1016 scans/searches terminate properly. */
1017 unsigned char *free;
1019 /* Pointer to the byte after the end of the free part. Note that
1020 this may be smaller than trace_buffer_free in the circular case,
1021 and means that the free part is in two pieces. Initially it is
1022 equal to trace_buffer_hi, then is generally equivalent to
1023 trace_buffer_start. */
1024 unsigned char *end_free;
1026 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
1027 this is the point at which the trace data breaks, and resumes at
1028 trace_buffer_lo. */
1029 unsigned char *wrap;
1032 /* Same as above, to be used by GDBserver when updating the in-process
1033 agent. */
1034 struct ipa_trace_buffer_control
1036 uintptr_t start;
1037 uintptr_t free;
1038 uintptr_t end_free;
1039 uintptr_t wrap;
1043 /* We have possibly both GDBserver and an inferior thread accessing
1044 the same IPA trace buffer memory. The IPA is the producer (tries
1045 to put new frames in the buffer), while GDBserver occasionally
1046 consumes them, that is, flushes the IPA's buffer into its own
1047 buffer. Both sides need to update the trace buffer control
1048 pointers (current head, tail, etc.). We can't use a global lock to
1049 synchronize the accesses, as otherwise we could deadlock GDBserver
1050 (if the thread holding the lock stops for a signal, say). So
1051 instead of that, we use a transaction scheme where GDBserver writes
1052 always prevail over the IPAs writes, and, we have the IPA detect
1053 the commit failure/overwrite, and retry the whole attempt. This is
1054 mainly implemented by having a global token object that represents
1055 who wrote last to the buffer control structure. We need to freeze
1056 any inferior writing to the buffer while GDBserver touches memory,
1057 so that the inferior can correctly detect that GDBserver had been
1058 there, otherwise, it could mistakingly think its commit was
1059 successful; that's implemented by simply having GDBserver set a
1060 breakpoint the inferior hits if it is the critical region.
1062 There are three cycling trace buffer control structure copies
1063 (buffer head, tail, etc.), with the token object including an index
1064 indicating which is current live copy. The IPA tentatively builds
1065 an updated copy in a non-current control structure, while GDBserver
1066 always clobbers the current version directly. The IPA then tries
1067 to atomically "commit" its version; if GDBserver clobbered the
1068 structure meanwhile, that will fail, and the IPA restarts the
1069 allocation process.
1071 Listing the step in further detail, we have:
1073 In-process agent (producer):
1075 - passes by `about_to_request_buffer_space' breakpoint/lock
1077 - reads current token, extracts current trace buffer control index,
1078 and starts tentatively updating the rightmost one (0->1, 1->2,
1079 2->0). Note that only one inferior thread is executing this code
1080 at any given time, due to an outer lock in the jump pads.
1082 - updates counters, and tries to commit the token.
1084 - passes by second `about_to_request_buffer_space' breakpoint/lock,
1085 leaving the sync region.
1087 - checks if the update was effective.
1089 - if trace buffer was found full, hits flush_trace_buffer
1090 breakpoint, and restarts later afterwards.
1092 GDBserver (consumer):
1094 - sets `about_to_request_buffer_space' breakpoint/lock.
1096 - updates the token unconditionally, using the current buffer
1097 control index, since it knows that the IP agent always writes to
1098 the rightmost, and due to the breakpoint, at most one IP thread
1099 can try to update the trace buffer concurrently to GDBserver, so
1100 there will be no danger of trace buffer control index wrap making
1101 the IPA write to the same index as GDBserver.
1103 - flushes the IP agent's trace buffer completely, and updates the
1104 current trace buffer control structure. GDBserver *always* wins.
1106 - removes the `about_to_request_buffer_space' breakpoint.
1108 The token is stored in the `trace_buffer_ctrl_curr' variable.
1109 Internally, it's bits are defined as:
1111 |-------------+-----+-------------+--------+-------------+--------------|
1112 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1113 |-------------+-----+-------------+--------+-------------+--------------|
1114 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1115 |-------------+-----+-------------+--------+-------------+--------------|
1117 GSB - GDBserver Stamp Bit
1118 PC - Previous Counter
1119 CC - Current Counter
1120 TBCI - Trace Buffer Control Index
1123 An IPA update of `trace_buffer_ctrl_curr' does:
1125 - read CC from the current token, save as PC.
1126 - updates pointers
1127 - atomically tries to write PC+1,CC
1129 A GDBserver update of `trace_buffer_ctrl_curr' does:
1131 - reads PC and CC from the current token.
1132 - updates pointers
1133 - writes GSB,PC,CC
1136 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1137 for the counters described below. The cleared bits are used to
1138 hold the index of the items of the `trace_buffer_ctrl' array that
1139 is "current". */
1140 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1142 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1143 counter, and the `current' counter. */
1145 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1146 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1148 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1149 always stamps this bit as set. */
1150 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1152 #ifdef IN_PROCESS_AGENT
1153 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1154 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1156 # define TRACE_BUFFER_CTRL_CURR \
1157 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1159 #else
1161 /* The GDBserver side agent only needs one instance of this object, as
1162 it doesn't need to sync with itself. Define it as array anyway so
1163 that the rest of the code base doesn't need to care for the
1164 difference. */
1165 static trace_buffer_control trace_buffer_ctrl[1];
1166 # define TRACE_BUFFER_CTRL_CURR 0
1167 #endif
1169 /* These are convenience macros used to access the current trace
1170 buffer control in effect. */
1171 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1172 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1173 #define trace_buffer_end_free \
1174 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1175 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1178 /* Macro that returns a pointer to the first traceframe in the buffer. */
1180 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1182 /* Macro that returns a pointer to the next traceframe in the buffer.
1183 If the computed location is beyond the wraparound point, subtract
1184 the offset of the wraparound. */
1186 #define NEXT_TRACEFRAME_1(TF) \
1187 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1189 #define NEXT_TRACEFRAME(TF) \
1190 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1191 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1192 ? (trace_buffer_wrap - trace_buffer_lo) \
1193 : 0)))
1195 /* The difference between these counters represents the total number
1196 of complete traceframes present in the trace buffer. The IP agent
1197 writes to the write count, GDBserver writes to read count. */
1199 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1200 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1202 /* Convenience macro. */
1204 #define traceframe_count \
1205 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1207 /* The count of all traceframes created in the current run, including
1208 ones that were discarded to make room. */
1210 IP_AGENT_EXPORT_VAR int traceframes_created;
1212 #ifndef IN_PROCESS_AGENT
1214 /* Read-only regions are address ranges whose contents don't change,
1215 and so can be read from target memory even while looking at a trace
1216 frame. Without these, disassembly for instance will likely fail,
1217 because the program code is not usually collected into a trace
1218 frame. This data structure does not need to be very complicated or
1219 particularly efficient, it's only going to be used occasionally,
1220 and only by some commands. */
1222 struct readonly_region
1224 /* The bounds of the region. */
1225 CORE_ADDR start, end;
1227 /* Link to the next one. */
1228 struct readonly_region *next;
1231 /* Linked list of readonly regions. This list stays in effect from
1232 one tstart to the next. */
1234 static struct readonly_region *readonly_regions;
1236 #endif
1238 /* The global that controls tracing overall. */
1240 IP_AGENT_EXPORT_VAR int tracing;
1242 #ifndef IN_PROCESS_AGENT
1244 /* Controls whether tracing should continue after GDB disconnects. */
1246 int disconnected_tracing;
1248 /* The reason for the last tracing run to have stopped. We initialize
1249 to a distinct string so that GDB can distinguish between "stopped
1250 after running" and "stopped because never run" cases. */
1252 static const char *tracing_stop_reason = "tnotrun";
1254 static int tracing_stop_tpnum;
1256 /* 64-bit timestamps for the trace run's start and finish, expressed
1257 in microseconds from the Unix epoch. */
1259 static LONGEST tracing_start_time;
1260 static LONGEST tracing_stop_time;
1262 /* The (optional) user-supplied name of the user that started the run.
1263 This is an arbitrary string, and may be NULL. */
1265 static char *tracing_user_name;
1267 /* Optional user-supplied text describing the run. This is
1268 an arbitrary string, and may be NULL. */
1270 static char *tracing_notes;
1272 /* Optional user-supplied text explaining a tstop command. This is an
1273 arbitrary string, and may be NULL. */
1275 static char *tracing_stop_note;
1277 #endif
1279 /* Functions local to this file. */
1281 /* Base "class" for tracepoint type specific data to be passed down to
1282 collect_data_at_tracepoint. */
1283 struct tracepoint_hit_ctx
1285 enum tracepoint_type type;
1288 #ifdef IN_PROCESS_AGENT
1290 /* Fast/jump tracepoint specific data to be passed down to
1291 collect_data_at_tracepoint. */
1292 struct fast_tracepoint_ctx
1294 struct tracepoint_hit_ctx base;
1296 struct regcache regcache;
1297 int regcache_initted;
1298 unsigned char *regspace;
1300 unsigned char *regs;
1301 struct tracepoint *tpoint;
1304 /* Static tracepoint specific data to be passed down to
1305 collect_data_at_tracepoint. */
1306 struct static_tracepoint_ctx
1308 struct tracepoint_hit_ctx base;
1310 /* The regcache corresponding to the registers state at the time of
1311 the tracepoint hit. Initialized lazily, from REGS. */
1312 struct regcache regcache;
1313 int regcache_initted;
1315 /* The buffer space REGCACHE above uses. We use a separate buffer
1316 instead of letting the regcache malloc for both signal safety and
1317 performance reasons; this is allocated on the stack instead. */
1318 unsigned char *regspace;
1320 /* The register buffer as passed on by lttng/ust. */
1321 struct registers *regs;
1323 /* The "printf" formatter and the args the user passed to the marker
1324 call. We use this to be able to collect "static trace data"
1325 ($_sdata). */
1326 const char *fmt;
1327 va_list *args;
1329 /* The GDB tracepoint matching the probed marker that was "hit". */
1330 struct tracepoint *tpoint;
1333 #else
1335 /* Static tracepoint specific data to be passed down to
1336 collect_data_at_tracepoint. */
1337 struct trap_tracepoint_ctx
1339 struct tracepoint_hit_ctx base;
1341 struct regcache *regcache;
1344 #endif
1346 #ifndef IN_PROCESS_AGENT
1347 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1348 static int traceframe_read_tsv (int num, LONGEST *val);
1349 #endif
1351 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1352 struct tracepoint *tpoint);
1354 #ifndef IN_PROCESS_AGENT
1355 static void clear_readonly_regions (void);
1356 static void clear_installed_tracepoints (void);
1357 #endif
1359 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1360 CORE_ADDR stop_pc,
1361 struct tracepoint *tpoint);
1362 #ifndef IN_PROCESS_AGENT
1363 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1364 CORE_ADDR stop_pc,
1365 struct tracepoint *tpoint, int current_step);
1366 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1367 CORE_ADDR *jump_entry);
1368 #endif
1369 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1370 CORE_ADDR stop_pc,
1371 struct tracepoint *tpoint,
1372 struct traceframe *tframe,
1373 struct tracepoint_action *taction);
1375 #ifndef IN_PROCESS_AGENT
1376 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1378 static void install_tracepoint (struct tracepoint *, char *own_buf);
1379 static void download_tracepoint (struct tracepoint *);
1380 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1381 static void clone_fast_tracepoint (struct tracepoint *to,
1382 const struct tracepoint *from);
1383 #endif
1385 static LONGEST get_timestamp (void);
1387 #if defined(__GNUC__)
1388 # define memory_barrier() asm volatile ("" : : : "memory")
1389 #else
1390 # define memory_barrier() do {} while (0)
1391 #endif
1393 /* We only build the IPA if this builtin is supported, and there are
1394 no uses of this in GDBserver itself, so we're safe in defining this
1395 unconditionally. */
1396 #define cmpxchg(mem, oldval, newval) \
1397 __sync_val_compare_and_swap (mem, oldval, newval)
1399 /* Record that an error occurred during expression evaluation. */
1401 static void
1402 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1403 enum eval_result_type rtype)
1405 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1406 tpoint->number, paddress (tpoint->address), which, rtype);
1408 #ifdef IN_PROCESS_AGENT
1409 /* Only record the first error we get. */
1410 if (cmpxchg (&expr_eval_result,
1411 expr_eval_no_error,
1412 rtype) != expr_eval_no_error)
1413 return;
1414 #else
1415 if (expr_eval_result != expr_eval_no_error)
1416 return;
1417 #endif
1419 error_tracepoint = tpoint;
1422 /* Trace buffer management. */
1424 static void
1425 clear_trace_buffer (void)
1427 trace_buffer_start = trace_buffer_lo;
1428 trace_buffer_free = trace_buffer_lo;
1429 trace_buffer_end_free = trace_buffer_hi;
1430 trace_buffer_wrap = trace_buffer_hi;
1431 /* A traceframe with zeroed fields marks the end of trace data. */
1432 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1433 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1434 traceframe_read_count = traceframe_write_count = 0;
1435 traceframes_created = 0;
1438 #ifndef IN_PROCESS_AGENT
1440 static void
1441 clear_inferior_trace_buffer (void)
1443 CORE_ADDR ipa_trace_buffer_lo;
1444 CORE_ADDR ipa_trace_buffer_hi;
1445 struct traceframe ipa_traceframe = { 0 };
1446 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1448 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1449 &ipa_trace_buffer_lo);
1450 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1451 &ipa_trace_buffer_hi);
1453 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1454 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1455 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1456 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1458 /* A traceframe with zeroed fields marks the end of trace data. */
1459 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1460 (unsigned char *) &ipa_trace_buffer_ctrl,
1461 sizeof (ipa_trace_buffer_ctrl));
1463 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1465 /* A traceframe with zeroed fields marks the end of trace data. */
1466 target_write_memory (ipa_trace_buffer_lo,
1467 (unsigned char *) &ipa_traceframe,
1468 sizeof (ipa_traceframe));
1470 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1471 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1472 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1475 #endif
1477 static void
1478 init_trace_buffer (LONGEST bufsize)
1480 size_t alloc_size;
1482 trace_buffer_size = bufsize;
1484 /* Make sure to internally allocate at least space for the EOB
1485 marker. */
1486 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1487 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1488 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1490 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1492 clear_trace_buffer ();
1495 #ifdef IN_PROCESS_AGENT
1497 /* This is needed for -Wmissing-declarations. */
1498 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1500 IP_AGENT_EXPORT_FUNC void
1501 about_to_request_buffer_space (void)
1503 /* GDBserver places breakpoint here while it goes about to flush
1504 data at random times. */
1505 UNKNOWN_SIDE_EFFECTS();
1508 #endif
1510 /* Carve out a piece of the trace buffer, returning NULL in case of
1511 failure. */
1513 static void *
1514 trace_buffer_alloc (size_t amt)
1516 unsigned char *rslt;
1517 struct trace_buffer_control *tbctrl;
1518 unsigned int curr;
1519 #ifdef IN_PROCESS_AGENT
1520 unsigned int prev, prev_filtered;
1521 unsigned int commit_count;
1522 unsigned int commit;
1523 unsigned int readout;
1524 #else
1525 struct traceframe *oldest;
1526 unsigned char *new_start;
1527 #endif
1529 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1530 (long) amt, (long) sizeof (struct traceframe));
1532 /* Account for the EOB marker. */
1533 amt += TRACEFRAME_EOB_MARKER_SIZE;
1535 #ifdef IN_PROCESS_AGENT
1536 again:
1537 memory_barrier ();
1539 /* Read the current token and extract the index to try to write to,
1540 storing it in CURR. */
1541 prev = trace_buffer_ctrl_curr;
1542 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1543 curr = prev_filtered + 1;
1544 if (curr > 2)
1545 curr = 0;
1547 about_to_request_buffer_space ();
1549 /* Start out with a copy of the current state. GDBserver may be
1550 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1551 be able to commit anyway if that happens. */
1552 trace_buffer_ctrl[curr]
1553 = trace_buffer_ctrl[prev_filtered];
1554 trace_debug ("trying curr=%u", curr);
1555 #else
1556 /* The GDBserver's agent doesn't need all that syncing, and always
1557 updates TCB 0 (there's only one, mind you). */
1558 curr = 0;
1559 #endif
1560 tbctrl = &trace_buffer_ctrl[curr];
1562 /* Offsets are easier to grok for debugging than raw addresses,
1563 especially for the small trace buffer sizes that are useful for
1564 testing. */
1565 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1566 curr,
1567 (int) (tbctrl->start - trace_buffer_lo),
1568 (int) (tbctrl->free - trace_buffer_lo),
1569 (int) (tbctrl->end_free - trace_buffer_lo),
1570 (int) (tbctrl->wrap - trace_buffer_lo),
1571 (int) (trace_buffer_hi - trace_buffer_lo));
1573 /* The algorithm here is to keep trying to get a contiguous block of
1574 the requested size, possibly discarding older traceframes to free
1575 up space. Since free space might come in one or two pieces,
1576 depending on whether discarded traceframes wrapped around at the
1577 high end of the buffer, we test both pieces after each
1578 discard. */
1579 while (1)
1581 /* First, if we have two free parts, try the upper one first. */
1582 if (tbctrl->end_free < tbctrl->free)
1584 if (tbctrl->free + amt <= trace_buffer_hi)
1585 /* We have enough in the upper part. */
1586 break;
1587 else
1589 /* Our high part of free space wasn't enough. Give up
1590 on it for now, set wraparound. We will recover the
1591 space later, if/when the wrapped-around traceframe is
1592 discarded. */
1593 trace_debug ("Upper part too small, setting wraparound");
1594 tbctrl->wrap = tbctrl->free;
1595 tbctrl->free = trace_buffer_lo;
1599 /* The normal case. */
1600 if (tbctrl->free + amt <= tbctrl->end_free)
1601 break;
1603 #ifdef IN_PROCESS_AGENT
1604 /* The IP Agent's buffer is always circular. It isn't used
1605 currently, but `circular_trace_buffer' could represent
1606 GDBserver's mode. If we didn't find space, ask GDBserver to
1607 flush. */
1609 flush_trace_buffer ();
1610 memory_barrier ();
1611 if (tracing)
1613 trace_debug ("gdbserver flushed buffer, retrying");
1614 goto again;
1617 /* GDBserver cancelled the tracing. Bail out as well. */
1618 return NULL;
1619 #else
1620 /* If we're here, then neither part is big enough, and
1621 non-circular trace buffers are now full. */
1622 if (!circular_trace_buffer)
1624 trace_debug ("Not enough space in the trace buffer");
1625 return NULL;
1628 trace_debug ("Need more space in the trace buffer");
1630 /* If we have a circular buffer, we can try discarding the
1631 oldest traceframe and see if that helps. */
1632 oldest = FIRST_TRACEFRAME ();
1633 if (oldest->tpnum == 0)
1635 /* Not good; we have no traceframes to free. Perhaps we're
1636 asking for a block that is larger than the buffer? In
1637 any case, give up. */
1638 trace_debug ("No traceframes to discard");
1639 return NULL;
1642 /* We don't run this code in the in-process agent currently.
1643 E.g., we could leave the in-process agent in autonomous
1644 circular mode if we only have fast tracepoints. If we do
1645 that, then this bit becomes racy with GDBserver, which also
1646 writes to this counter. */
1647 --traceframe_write_count;
1649 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1650 /* If we freed the traceframe that wrapped around, go back
1651 to the non-wrap case. */
1652 if (new_start < tbctrl->start)
1654 trace_debug ("Discarding past the wraparound");
1655 tbctrl->wrap = trace_buffer_hi;
1657 tbctrl->start = new_start;
1658 tbctrl->end_free = tbctrl->start;
1660 trace_debug ("Discarded a traceframe\n"
1661 "Trace buffer [%d], start=%d free=%d "
1662 "endfree=%d wrap=%d hi=%d",
1663 curr,
1664 (int) (tbctrl->start - trace_buffer_lo),
1665 (int) (tbctrl->free - trace_buffer_lo),
1666 (int) (tbctrl->end_free - trace_buffer_lo),
1667 (int) (tbctrl->wrap - trace_buffer_lo),
1668 (int) (trace_buffer_hi - trace_buffer_lo));
1670 /* Now go back around the loop. The discard might have resulted
1671 in either one or two pieces of free space, so we want to try
1672 both before freeing any more traceframes. */
1673 #endif
1676 /* If we get here, we know we can provide the asked-for space. */
1678 rslt = tbctrl->free;
1680 /* Adjust the request back down, now that we know we have space for
1681 the marker, but don't commit to AMT yet, we may still need to
1682 restart the operation if GDBserver touches the trace buffer
1683 (obviously only important in the in-process agent's version). */
1684 tbctrl->free += (amt - sizeof (struct traceframe));
1686 /* Or not. If GDBserver changed the trace buffer behind our back,
1687 we get to restart a new allocation attempt. */
1689 #ifdef IN_PROCESS_AGENT
1690 /* Build the tentative token. */
1691 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1692 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1693 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1694 | commit_count
1695 | curr);
1697 /* Try to commit it. */
1698 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1699 if (readout != prev)
1701 trace_debug ("GDBserver has touched the trace buffer, restarting."
1702 " (prev=%08x, commit=%08x, readout=%08x)",
1703 prev, commit, readout);
1704 goto again;
1707 /* Hold your horses here. Even if that change was committed,
1708 GDBserver could come in, and clobber it. We need to hold to be
1709 able to tell if GDBserver clobbers before or after we committed
1710 the change. Whenever GDBserver goes about touching the IPA
1711 buffer, it sets a breakpoint in this routine, so we have a sync
1712 point here. */
1713 about_to_request_buffer_space ();
1715 /* Check if the change has been effective, even if GDBserver stopped
1716 us at the breakpoint. */
1719 unsigned int refetch;
1721 memory_barrier ();
1723 refetch = trace_buffer_ctrl_curr;
1725 if (refetch == commit
1726 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1728 /* effective */
1729 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1730 "readout=%08x, refetch=%08x)",
1731 prev, commit, readout, refetch);
1733 else
1735 trace_debug ("GDBserver has touched the trace buffer, not effective."
1736 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1737 prev, commit, readout, refetch);
1738 goto again;
1741 #endif
1743 /* We have a new piece of the trace buffer. Hurray! */
1745 /* Add an EOB marker just past this allocation. */
1746 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1747 ((struct traceframe *) tbctrl->free)->data_size = 0;
1749 /* Adjust the request back down, now that we know we have space for
1750 the marker. */
1751 amt -= sizeof (struct traceframe);
1753 if (debug_threads)
1755 trace_debug ("Allocated %d bytes", (int) amt);
1756 trace_debug ("Trace buffer [%d] start=%d free=%d "
1757 "endfree=%d wrap=%d hi=%d",
1758 curr,
1759 (int) (tbctrl->start - trace_buffer_lo),
1760 (int) (tbctrl->free - trace_buffer_lo),
1761 (int) (tbctrl->end_free - trace_buffer_lo),
1762 (int) (tbctrl->wrap - trace_buffer_lo),
1763 (int) (trace_buffer_hi - trace_buffer_lo));
1766 return rslt;
1769 #ifndef IN_PROCESS_AGENT
1771 /* Return the total free space. This is not necessarily the largest
1772 block we can allocate, because of the two-part case. */
1774 static int
1775 free_space (void)
1777 if (trace_buffer_free <= trace_buffer_end_free)
1778 return trace_buffer_end_free - trace_buffer_free;
1779 else
1780 return ((trace_buffer_end_free - trace_buffer_lo)
1781 + (trace_buffer_hi - trace_buffer_free));
1784 /* An 'S' in continuation packets indicates remainder are for
1785 while-stepping. */
1787 static int seen_step_action_flag;
1789 /* Create a tracepoint (location) with given number and address. Add this
1790 new tracepoint to list and sort this list. */
1792 static struct tracepoint *
1793 add_tracepoint (int num, CORE_ADDR addr)
1795 struct tracepoint *tpoint, **tp_next;
1797 tpoint = XNEW (struct tracepoint);
1798 tpoint->number = num;
1799 tpoint->address = addr;
1800 tpoint->numactions = 0;
1801 tpoint->actions = NULL;
1802 tpoint->actions_str = NULL;
1803 tpoint->cond = NULL;
1804 tpoint->num_step_actions = 0;
1805 tpoint->step_actions = NULL;
1806 tpoint->step_actions_str = NULL;
1807 /* Start all off as regular (slow) tracepoints. */
1808 tpoint->type = trap_tracepoint;
1809 tpoint->orig_size = -1;
1810 tpoint->source_strings = NULL;
1811 tpoint->compiled_cond = 0;
1812 tpoint->handle = NULL;
1813 tpoint->next = NULL;
1815 /* Find a place to insert this tracepoint into list in order to keep
1816 the tracepoint list still in the ascending order. There may be
1817 multiple tracepoints at the same address as TPOINT's, and this
1818 guarantees TPOINT is inserted after all the tracepoints which are
1819 set at the same address. For example, fast tracepoints A, B, C are
1820 set at the same address, and D is to be insert at the same place as
1821 well,
1823 -->| A |--> | B |-->| C |->...
1825 One jump pad was created for tracepoint A, B, and C, and the target
1826 address of A is referenced/used in jump pad. So jump pad will let
1827 inferior jump to A. If D is inserted in front of A, like this,
1829 -->| D |-->| A |--> | B |-->| C |->...
1831 without updating jump pad, D is not reachable during collect, which
1832 is wrong. As we can see, the order of B, C and D doesn't matter, but
1833 A should always be the `first' one. */
1834 for (tp_next = &tracepoints;
1835 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1836 tp_next = &(*tp_next)->next)
1838 tpoint->next = *tp_next;
1839 *tp_next = tpoint;
1840 last_tracepoint = tpoint;
1842 seen_step_action_flag = 0;
1844 return tpoint;
1847 #ifndef IN_PROCESS_AGENT
1849 /* Return the tracepoint with the given number and address, or NULL. */
1851 static struct tracepoint *
1852 find_tracepoint (int id, CORE_ADDR addr)
1854 struct tracepoint *tpoint;
1856 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1857 if (tpoint->number == id && tpoint->address == addr)
1858 return tpoint;
1860 return NULL;
1863 /* Remove TPOINT from global list. */
1865 static void
1866 remove_tracepoint (struct tracepoint *tpoint)
1868 struct tracepoint *tp, *tp_prev;
1870 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1871 tp_prev = tp, tp = tp->next)
1874 if (tp)
1876 if (tp_prev)
1877 tp_prev->next = tp->next;
1878 else
1879 tracepoints = tp->next;
1881 xfree (tp);
1885 /* There may be several tracepoints with the same number (because they
1886 are "locations", in GDB parlance); return the next one after the
1887 given tracepoint, or search from the beginning of the list if the
1888 first argument is NULL. */
1890 static struct tracepoint *
1891 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1893 struct tracepoint *tpoint;
1895 if (prev_tp)
1896 tpoint = prev_tp->next;
1897 else
1898 tpoint = tracepoints;
1899 for (; tpoint; tpoint = tpoint->next)
1900 if (tpoint->number == num)
1901 return tpoint;
1903 return NULL;
1906 #endif
1908 /* Append another action to perform when the tracepoint triggers. */
1910 static void
1911 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1913 const char *act;
1915 if (*packet == 'S')
1917 seen_step_action_flag = 1;
1918 ++packet;
1921 act = packet;
1923 while (*act)
1925 const char *act_start = act;
1926 struct tracepoint_action *action = NULL;
1928 switch (*act)
1930 case 'M':
1932 struct collect_memory_action *maction =
1933 XNEW (struct collect_memory_action);
1934 ULONGEST basereg;
1935 int is_neg;
1937 maction->base.type = *act;
1938 action = &maction->base;
1940 ++act;
1941 is_neg = (*act == '-');
1942 if (*act == '-')
1943 ++act;
1944 act = unpack_varlen_hex (act, &basereg);
1945 ++act;
1946 act = unpack_varlen_hex (act, &maction->addr);
1947 ++act;
1948 act = unpack_varlen_hex (act, &maction->len);
1949 maction->basereg = (is_neg
1950 ? - (int) basereg
1951 : (int) basereg);
1952 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1953 pulongest (maction->len),
1954 paddress (maction->addr), maction->basereg);
1955 break;
1957 case 'R':
1959 struct collect_registers_action *raction =
1960 XNEW (struct collect_registers_action);
1962 raction->base.type = *act;
1963 action = &raction->base;
1965 trace_debug ("Want to collect registers");
1966 ++act;
1967 /* skip past hex digits of mask for now */
1968 while (isxdigit(*act))
1969 ++act;
1970 break;
1972 case 'L':
1974 struct collect_static_trace_data_action *raction =
1975 XNEW (struct collect_static_trace_data_action);
1977 raction->base.type = *act;
1978 action = &raction->base;
1980 trace_debug ("Want to collect static trace data");
1981 ++act;
1982 break;
1984 case 'S':
1985 trace_debug ("Unexpected step action, ignoring");
1986 ++act;
1987 break;
1988 case 'X':
1990 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1992 xaction->base.type = *act;
1993 action = &xaction->base;
1995 trace_debug ("Want to evaluate expression");
1996 xaction->expr = gdb_parse_agent_expr (&act);
1997 break;
1999 default:
2000 trace_debug ("unknown trace action '%c', ignoring...", *act);
2001 break;
2002 case '-':
2003 break;
2006 if (action == NULL)
2007 break;
2009 if (seen_step_action_flag)
2011 tpoint->num_step_actions++;
2013 tpoint->step_actions
2014 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
2015 tpoint->num_step_actions);
2016 tpoint->step_actions_str
2017 = XRESIZEVEC (char *, tpoint->step_actions_str,
2018 tpoint->num_step_actions);
2019 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
2020 tpoint->step_actions_str[tpoint->num_step_actions - 1]
2021 = savestring (act_start, act - act_start);
2023 else
2025 tpoint->numactions++;
2026 tpoint->actions
2027 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
2028 tpoint->numactions);
2029 tpoint->actions_str
2030 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
2031 tpoint->actions[tpoint->numactions - 1] = action;
2032 tpoint->actions_str[tpoint->numactions - 1]
2033 = savestring (act_start, act - act_start);
2038 #endif
2040 /* Find or create a trace state variable with the given number. */
2042 static struct trace_state_variable *
2043 get_trace_state_variable (int num)
2045 struct trace_state_variable *tsv;
2047 #ifdef IN_PROCESS_AGENT
2048 /* Search for an existing variable. */
2049 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
2050 if (tsv->number == num)
2051 return tsv;
2052 #endif
2054 /* Search for an existing variable. */
2055 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
2056 if (tsv->number == num)
2057 return tsv;
2059 return NULL;
2062 /* Find or create a trace state variable with the given number. */
2064 static struct trace_state_variable *
2065 create_trace_state_variable (int num, int gdb)
2067 struct trace_state_variable *tsv;
2069 tsv = get_trace_state_variable (num);
2070 if (tsv != NULL)
2071 return tsv;
2073 /* Create a new variable. */
2074 tsv = XNEW (struct trace_state_variable);
2075 tsv->number = num;
2076 tsv->initial_value = 0;
2077 tsv->value = 0;
2078 tsv->getter = NULL;
2079 tsv->name = NULL;
2080 #ifdef IN_PROCESS_AGENT
2081 if (!gdb)
2083 tsv->next = alloced_trace_state_variables;
2084 alloced_trace_state_variables = tsv;
2086 else
2087 #endif
2089 tsv->next = trace_state_variables;
2090 trace_state_variables = tsv;
2092 return tsv;
2095 /* This is needed for -Wmissing-declarations. */
2096 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
2098 IP_AGENT_EXPORT_FUNC LONGEST
2099 get_trace_state_variable_value (int num)
2101 struct trace_state_variable *tsv;
2103 tsv = get_trace_state_variable (num);
2105 if (!tsv)
2107 trace_debug ("No trace state variable %d, skipping value get", num);
2108 return 0;
2111 /* Call a getter function if we have one. While it's tempting to
2112 set up something to only call the getter once per tracepoint hit,
2113 it could run afoul of thread races. Better to let the getter
2114 handle it directly, if necessary to worry about it. */
2115 if (tsv->getter)
2116 tsv->value = (tsv->getter) ();
2118 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2119 num, plongest (tsv->value));
2121 return tsv->value;
2124 /* This is needed for -Wmissing-declarations. */
2125 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
2126 LONGEST val);
2128 IP_AGENT_EXPORT_FUNC void
2129 set_trace_state_variable_value (int num, LONGEST val)
2131 struct trace_state_variable *tsv;
2133 tsv = get_trace_state_variable (num);
2135 if (!tsv)
2137 trace_debug ("No trace state variable %d, skipping value set", num);
2138 return;
2141 tsv->value = val;
2144 LONGEST
2145 agent_get_trace_state_variable_value (int num)
2147 return get_trace_state_variable_value (num);
2150 void
2151 agent_set_trace_state_variable_value (int num, LONGEST val)
2153 set_trace_state_variable_value (num, val);
2156 static void
2157 set_trace_state_variable_name (int num, const char *name)
2159 struct trace_state_variable *tsv;
2161 tsv = get_trace_state_variable (num);
2163 if (!tsv)
2165 trace_debug ("No trace state variable %d, skipping name set", num);
2166 return;
2169 tsv->name = (char *) name;
2172 static void
2173 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2175 struct trace_state_variable *tsv;
2177 tsv = get_trace_state_variable (num);
2179 if (!tsv)
2181 trace_debug ("No trace state variable %d, skipping getter set", num);
2182 return;
2185 tsv->getter = getter;
2188 /* Add a raw traceframe for the given tracepoint. */
2190 static struct traceframe *
2191 add_traceframe (struct tracepoint *tpoint)
2193 struct traceframe *tframe;
2195 tframe
2196 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2198 if (tframe == NULL)
2199 return NULL;
2201 tframe->tpnum = tpoint->number;
2202 tframe->data_size = 0;
2204 return tframe;
2207 /* Add a block to the traceframe currently being worked on. */
2209 static unsigned char *
2210 add_traceframe_block (struct traceframe *tframe,
2211 struct tracepoint *tpoint, int amt)
2213 unsigned char *block;
2215 if (!tframe)
2216 return NULL;
2218 block = (unsigned char *) trace_buffer_alloc (amt);
2220 if (!block)
2221 return NULL;
2223 gdb_assert (tframe->tpnum == tpoint->number);
2225 tframe->data_size += amt;
2226 tpoint->traceframe_usage += amt;
2228 return block;
2231 /* Flag that the current traceframe is finished. */
2233 static void
2234 finish_traceframe (struct traceframe *tframe)
2236 ++traceframe_write_count;
2237 ++traceframes_created;
2240 #ifndef IN_PROCESS_AGENT
2242 /* Given a traceframe number NUM, find the NUMth traceframe in the
2243 buffer. */
2245 static struct traceframe *
2246 find_traceframe (int num)
2248 struct traceframe *tframe;
2249 int tfnum = 0;
2251 for (tframe = FIRST_TRACEFRAME ();
2252 tframe->tpnum != 0;
2253 tframe = NEXT_TRACEFRAME (tframe))
2255 if (tfnum == num)
2256 return tframe;
2257 ++tfnum;
2260 return NULL;
2263 static CORE_ADDR
2264 get_traceframe_address (struct traceframe *tframe)
2266 CORE_ADDR addr;
2267 struct tracepoint *tpoint;
2269 addr = traceframe_get_pc (tframe);
2271 if (addr)
2272 return addr;
2274 /* Fallback strategy, will be incorrect for while-stepping frames
2275 and multi-location tracepoints. */
2276 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2277 return tpoint->address;
2280 /* Search for the next traceframe whose address is inside or outside
2281 the given range. */
2283 static struct traceframe *
2284 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2285 int *tfnump)
2287 client_state &cs = get_client_state ();
2288 struct traceframe *tframe;
2289 CORE_ADDR tfaddr;
2291 *tfnump = cs.current_traceframe + 1;
2292 tframe = find_traceframe (*tfnump);
2293 /* The search is not supposed to wrap around. */
2294 if (!tframe)
2296 *tfnump = -1;
2297 return NULL;
2300 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2302 tfaddr = get_traceframe_address (tframe);
2303 if (inside_p
2304 ? (lo <= tfaddr && tfaddr <= hi)
2305 : (lo > tfaddr || tfaddr > hi))
2306 return tframe;
2307 ++*tfnump;
2310 *tfnump = -1;
2311 return NULL;
2314 /* Search for the next traceframe recorded by the given tracepoint.
2315 Note that for multi-location tracepoints, this will find whatever
2316 location appears first. */
2318 static struct traceframe *
2319 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2321 client_state &cs = get_client_state ();
2322 struct traceframe *tframe;
2324 *tfnump = cs.current_traceframe + 1;
2325 tframe = find_traceframe (*tfnump);
2326 /* The search is not supposed to wrap around. */
2327 if (!tframe)
2329 *tfnump = -1;
2330 return NULL;
2333 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2335 if (tframe->tpnum == num)
2336 return tframe;
2337 ++*tfnump;
2340 *tfnump = -1;
2341 return NULL;
2344 #endif
2346 #ifndef IN_PROCESS_AGENT
2348 /* Clear all past trace state. */
2350 static void
2351 cmd_qtinit (char *packet)
2353 client_state &cs = get_client_state ();
2354 struct trace_state_variable *tsv, *prev, *next;
2356 /* Can't do this command without a pid attached. */
2357 if (current_thread == NULL)
2359 write_enn (packet);
2360 return;
2363 /* Make sure we don't try to read from a trace frame. */
2364 cs.current_traceframe = -1;
2366 stop_tracing ();
2368 trace_debug ("Initializing the trace");
2370 clear_installed_tracepoints ();
2371 clear_readonly_regions ();
2373 tracepoints = NULL;
2374 last_tracepoint = NULL;
2376 /* Clear out any leftover trace state variables. Ones with target
2377 defined getters should be kept however. */
2378 prev = NULL;
2379 tsv = trace_state_variables;
2380 while (tsv)
2382 trace_debug ("Looking at var %d", tsv->number);
2383 if (tsv->getter == NULL)
2385 next = tsv->next;
2386 if (prev)
2387 prev->next = next;
2388 else
2389 trace_state_variables = next;
2390 trace_debug ("Deleting var %d", tsv->number);
2391 free (tsv);
2392 tsv = next;
2394 else
2396 prev = tsv;
2397 tsv = tsv->next;
2401 clear_trace_buffer ();
2402 clear_inferior_trace_buffer ();
2404 write_ok (packet);
2407 /* Unprobe the UST marker at ADDRESS. */
2409 static void
2410 unprobe_marker_at (CORE_ADDR address)
2412 char cmd[IPA_CMD_BUF_SIZE];
2414 sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
2415 run_inferior_command (cmd, strlen (cmd) + 1);
2418 /* Restore the program to its pre-tracing state. This routine may be called
2419 in error situations, so it needs to be careful about only restoring
2420 from known-valid bits. */
2422 static void
2423 clear_installed_tracepoints (void)
2425 struct tracepoint *tpoint;
2426 struct tracepoint *prev_stpoint;
2428 target_pause_all (true);
2430 prev_stpoint = NULL;
2432 /* Restore any bytes overwritten by tracepoints. */
2433 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2435 /* Catch the case where we might try to remove a tracepoint that
2436 was never actually installed. */
2437 if (tpoint->handle == NULL)
2439 trace_debug ("Tracepoint %d at 0x%s was "
2440 "never installed, nothing to clear",
2441 tpoint->number, paddress (tpoint->address));
2442 continue;
2445 switch (tpoint->type)
2447 case trap_tracepoint:
2449 struct breakpoint *bp
2450 = (struct breakpoint *) tpoint->handle;
2452 delete_breakpoint (bp);
2454 break;
2455 case fast_tracepoint:
2457 struct fast_tracepoint_jump *jump
2458 = (struct fast_tracepoint_jump *) tpoint->handle;
2460 delete_fast_tracepoint_jump (jump);
2462 break;
2463 case static_tracepoint:
2464 if (prev_stpoint != NULL
2465 && prev_stpoint->address == tpoint->address)
2466 /* Nothing to do. We already unprobed a tracepoint set at
2467 this marker address (and there can only be one probe
2468 per marker). */
2470 else
2472 unprobe_marker_at (tpoint->address);
2473 prev_stpoint = tpoint;
2475 break;
2478 tpoint->handle = NULL;
2481 target_unpause_all (true);
2484 /* Parse a packet that defines a tracepoint. */
2486 static void
2487 cmd_qtdp (char *own_buf)
2489 int tppacket;
2490 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2491 int trail_hyphen = 0;
2492 ULONGEST num;
2493 ULONGEST addr;
2494 ULONGEST count;
2495 struct tracepoint *tpoint;
2496 const char *packet = own_buf;
2498 packet += strlen ("QTDP:");
2500 /* A hyphen at the beginning marks a packet specifying actions for a
2501 tracepoint already supplied. */
2502 tppacket = 1;
2503 if (*packet == '-')
2505 tppacket = 0;
2506 ++packet;
2508 packet = unpack_varlen_hex (packet, &num);
2509 ++packet; /* skip a colon */
2510 packet = unpack_varlen_hex (packet, &addr);
2511 ++packet; /* skip a colon */
2513 /* See if we already have this tracepoint. */
2514 tpoint = find_tracepoint (num, addr);
2516 if (tppacket)
2518 /* Duplicate tracepoints are never allowed. */
2519 if (tpoint)
2521 trace_debug ("Tracepoint error: tracepoint %d"
2522 " at 0x%s already exists",
2523 (int) num, paddress (addr));
2524 write_enn (own_buf);
2525 return;
2528 tpoint = add_tracepoint (num, addr);
2530 tpoint->enabled = (*packet == 'E');
2531 ++packet; /* skip 'E' */
2532 ++packet; /* skip a colon */
2533 packet = unpack_varlen_hex (packet, &count);
2534 tpoint->step_count = count;
2535 ++packet; /* skip a colon */
2536 packet = unpack_varlen_hex (packet, &count);
2537 tpoint->pass_count = count;
2538 /* See if we have any of the additional optional fields. */
2539 while (*packet == ':')
2541 ++packet;
2542 if (*packet == 'F')
2544 tpoint->type = fast_tracepoint;
2545 ++packet;
2546 packet = unpack_varlen_hex (packet, &count);
2547 tpoint->orig_size = count;
2549 else if (*packet == 'S')
2551 tpoint->type = static_tracepoint;
2552 ++packet;
2554 else if (*packet == 'X')
2556 tpoint->cond = gdb_parse_agent_expr (&packet);
2558 else if (*packet == '-')
2559 break;
2560 else if (*packet == '\0')
2561 break;
2562 else
2563 trace_debug ("Unknown optional tracepoint field");
2565 if (*packet == '-')
2567 trail_hyphen = 1;
2568 trace_debug ("Also has actions\n");
2571 trace_debug ("Defined %stracepoint %d at 0x%s, "
2572 "enabled %d step %" PRIu64 " pass %" PRIu64,
2573 tpoint->type == fast_tracepoint ? "fast "
2574 : tpoint->type == static_tracepoint ? "static " : "",
2575 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2576 tpoint->step_count, tpoint->pass_count);
2578 else if (tpoint)
2579 add_tracepoint_action (tpoint, packet);
2580 else
2582 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2583 (int) num, paddress (addr));
2584 write_enn (own_buf);
2585 return;
2588 /* Install tracepoint during tracing only once for each tracepoint location.
2589 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2590 determine the last QTDP packet for one tracepoint location by checking
2591 trailing hyphen in QTDP packet. */
2592 if (tracing && !trail_hyphen)
2594 struct tracepoint *tp = NULL;
2596 /* Pause all threads temporarily while we patch tracepoints. */
2597 target_pause_all (false);
2599 /* download_tracepoint will update global `tracepoints'
2600 list, so it is unsafe to leave threads in jump pad. */
2601 target_stabilize_threads ();
2603 /* Freeze threads. */
2604 target_pause_all (true);
2607 if (tpoint->type != trap_tracepoint)
2609 /* Find another fast or static tracepoint at the same address. */
2610 for (tp = tracepoints; tp; tp = tp->next)
2612 if (tp->address == tpoint->address && tp->type == tpoint->type
2613 && tp->number != tpoint->number)
2614 break;
2617 /* TPOINT is installed at the same address as TP. */
2618 if (tp)
2620 if (tpoint->type == fast_tracepoint)
2621 clone_fast_tracepoint (tpoint, tp);
2622 else if (tpoint->type == static_tracepoint)
2623 tpoint->handle = (void *) -1;
2627 if (use_agent && tpoint->type == fast_tracepoint
2628 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2630 /* Download and install fast tracepoint by agent. */
2631 if (tracepoint_send_agent (tpoint) == 0)
2632 write_ok (own_buf);
2633 else
2635 write_enn (own_buf);
2636 remove_tracepoint (tpoint);
2639 else
2641 download_tracepoint (tpoint);
2643 if (tpoint->type == trap_tracepoint || tp == NULL)
2645 install_tracepoint (tpoint, own_buf);
2646 if (strcmp (own_buf, "OK") != 0)
2647 remove_tracepoint (tpoint);
2649 else
2650 write_ok (own_buf);
2653 target_unpause_all (true);
2654 return;
2657 write_ok (own_buf);
2660 static void
2661 cmd_qtdpsrc (char *own_buf)
2663 ULONGEST num, addr, start, slen;
2664 struct tracepoint *tpoint;
2665 const char *packet = own_buf;
2666 const char *saved;
2667 char *srctype, *src;
2668 size_t nbytes;
2669 struct source_string *last, *newlast;
2671 packet += strlen ("QTDPsrc:");
2673 packet = unpack_varlen_hex (packet, &num);
2674 ++packet; /* skip a colon */
2675 packet = unpack_varlen_hex (packet, &addr);
2676 ++packet; /* skip a colon */
2678 /* See if we already have this tracepoint. */
2679 tpoint = find_tracepoint (num, addr);
2681 if (!tpoint)
2683 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2684 (int) num, paddress (addr));
2685 write_enn (own_buf);
2686 return;
2689 saved = packet;
2690 packet = strchr (packet, ':');
2691 srctype = (char *) xmalloc (packet - saved + 1);
2692 memcpy (srctype, saved, packet - saved);
2693 srctype[packet - saved] = '\0';
2694 ++packet;
2695 packet = unpack_varlen_hex (packet, &start);
2696 ++packet; /* skip a colon */
2697 packet = unpack_varlen_hex (packet, &slen);
2698 ++packet; /* skip a colon */
2699 src = (char *) xmalloc (slen + 1);
2700 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2701 src[nbytes] = '\0';
2703 newlast = XNEW (struct source_string);
2704 newlast->type = srctype;
2705 newlast->str = src;
2706 newlast->next = NULL;
2707 /* Always add a source string to the end of the list;
2708 this keeps sequences of actions/commands in the right
2709 order. */
2710 if (tpoint->source_strings)
2712 for (last = tpoint->source_strings; last->next; last = last->next)
2714 last->next = newlast;
2716 else
2717 tpoint->source_strings = newlast;
2719 write_ok (own_buf);
2722 static void
2723 cmd_qtdv (char *own_buf)
2725 ULONGEST num, val, builtin;
2726 char *varname;
2727 size_t nbytes;
2728 struct trace_state_variable *tsv;
2729 const char *packet = own_buf;
2731 packet += strlen ("QTDV:");
2733 packet = unpack_varlen_hex (packet, &num);
2734 ++packet; /* skip a colon */
2735 packet = unpack_varlen_hex (packet, &val);
2736 ++packet; /* skip a colon */
2737 packet = unpack_varlen_hex (packet, &builtin);
2738 ++packet; /* skip a colon */
2740 nbytes = strlen (packet) / 2;
2741 varname = (char *) xmalloc (nbytes + 1);
2742 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2743 varname[nbytes] = '\0';
2745 tsv = create_trace_state_variable (num, 1);
2746 tsv->initial_value = (LONGEST) val;
2747 tsv->name = varname;
2749 set_trace_state_variable_value (num, (LONGEST) val);
2751 write_ok (own_buf);
2754 static void
2755 cmd_qtenable_disable (char *own_buf, int enable)
2757 const char *packet = own_buf;
2758 ULONGEST num, addr;
2759 struct tracepoint *tp;
2761 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2762 packet = unpack_varlen_hex (packet, &num);
2763 ++packet; /* skip a colon */
2764 packet = unpack_varlen_hex (packet, &addr);
2766 tp = find_tracepoint (num, addr);
2768 if (tp)
2770 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2772 trace_debug ("Tracepoint %d at 0x%s is already %s",
2773 (int) num, paddress (addr),
2774 enable ? "enabled" : "disabled");
2775 write_ok (own_buf);
2776 return;
2779 trace_debug ("%s tracepoint %d at 0x%s",
2780 enable ? "Enabling" : "Disabling",
2781 (int) num, paddress (addr));
2783 tp->enabled = enable;
2785 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
2787 int offset = offsetof (struct tracepoint, enabled);
2788 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2790 int ret = write_inferior_int8 (obj_addr, enable);
2791 if (ret)
2793 trace_debug ("Cannot write enabled flag into "
2794 "inferior process memory");
2795 write_enn (own_buf);
2796 return;
2800 write_ok (own_buf);
2802 else
2804 trace_debug ("Tracepoint %d at 0x%s not found",
2805 (int) num, paddress (addr));
2806 write_enn (own_buf);
2810 static void
2811 cmd_qtv (char *own_buf)
2813 client_state &cs = get_client_state ();
2814 ULONGEST num;
2815 LONGEST val = 0;
2816 int err;
2817 char *packet = own_buf;
2819 packet += strlen ("qTV:");
2820 unpack_varlen_hex (packet, &num);
2822 if (cs.current_traceframe >= 0)
2824 err = traceframe_read_tsv ((int) num, &val);
2825 if (err)
2827 strcpy (own_buf, "U");
2828 return;
2831 /* Only make tsv's be undefined before the first trace run. After a
2832 trace run is over, the user might want to see the last value of
2833 the tsv, and it might not be available in a traceframe. */
2834 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2836 strcpy (own_buf, "U");
2837 return;
2839 else
2840 val = get_trace_state_variable_value (num);
2842 sprintf (own_buf, "V%s", phex_nz (val, 0));
2845 /* Clear out the list of readonly regions. */
2847 static void
2848 clear_readonly_regions (void)
2850 struct readonly_region *roreg;
2852 while (readonly_regions)
2854 roreg = readonly_regions;
2855 readonly_regions = readonly_regions->next;
2856 free (roreg);
2860 /* Parse the collection of address ranges whose contents GDB believes
2861 to be unchanging and so can be read directly from target memory
2862 even while looking at a traceframe. */
2864 static void
2865 cmd_qtro (char *own_buf)
2867 ULONGEST start, end;
2868 struct readonly_region *roreg;
2869 const char *packet = own_buf;
2871 trace_debug ("Want to mark readonly regions");
2873 clear_readonly_regions ();
2875 packet += strlen ("QTro");
2877 while (*packet == ':')
2879 ++packet; /* skip a colon */
2880 packet = unpack_varlen_hex (packet, &start);
2881 ++packet; /* skip a comma */
2882 packet = unpack_varlen_hex (packet, &end);
2884 roreg = XNEW (struct readonly_region);
2885 roreg->start = start;
2886 roreg->end = end;
2887 roreg->next = readonly_regions;
2888 readonly_regions = roreg;
2889 trace_debug ("Added readonly region from 0x%s to 0x%s",
2890 paddress (roreg->start), paddress (roreg->end));
2893 write_ok (own_buf);
2896 /* Test to see if the given range is in our list of readonly ranges.
2897 We only test for being entirely within a range, GDB is not going to
2898 send a single memory packet that spans multiple regions. */
2901 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2903 struct readonly_region *roreg;
2905 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2906 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2907 return 1;
2909 return 0;
2912 static CORE_ADDR gdb_jump_pad_head;
2914 /* Return the address of the next free jump space. */
2916 static CORE_ADDR
2917 get_jump_space_head (void)
2919 if (gdb_jump_pad_head == 0)
2921 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2922 &gdb_jump_pad_head))
2924 internal_error (__FILE__, __LINE__,
2925 "error extracting jump_pad_buffer");
2929 return gdb_jump_pad_head;
2932 /* Reserve USED bytes from the jump space. */
2934 static void
2935 claim_jump_space (ULONGEST used)
2937 trace_debug ("claim_jump_space reserves %s bytes at %s",
2938 pulongest (used), paddress (gdb_jump_pad_head));
2939 gdb_jump_pad_head += used;
2942 static CORE_ADDR trampoline_buffer_head = 0;
2943 static CORE_ADDR trampoline_buffer_tail;
2945 /* Reserve USED bytes from the trampoline buffer and return the
2946 address of the start of the reserved space in TRAMPOLINE. Returns
2947 non-zero if the space is successfully claimed. */
2950 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2952 if (!trampoline_buffer_head)
2954 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2955 &trampoline_buffer_tail))
2957 internal_error (__FILE__, __LINE__,
2958 "error extracting trampoline_buffer");
2961 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2962 &trampoline_buffer_head))
2964 internal_error (__FILE__, __LINE__,
2965 "error extracting trampoline_buffer_end");
2969 /* Start claiming space from the top of the trampoline space. If
2970 the space is located at the bottom of the virtual address space,
2971 this reduces the possibility that corruption will occur if a null
2972 pointer is used to write to memory. */
2973 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2975 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2976 pulongest (used));
2977 return 0;
2980 trampoline_buffer_head -= used;
2982 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2983 pulongest (used), paddress (trampoline_buffer_head));
2985 *trampoline = trampoline_buffer_head;
2986 return 1;
2989 /* Returns non-zero if there is space allocated for use in trampolines
2990 for fast tracepoints. */
2993 have_fast_tracepoint_trampoline_buffer (char *buf)
2995 CORE_ADDR trampoline_end, errbuf;
2997 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2998 &trampoline_end))
3000 internal_error (__FILE__, __LINE__,
3001 "error extracting trampoline_buffer_end");
3004 if (buf)
3006 buf[0] = '\0';
3007 strcpy (buf, "was claiming");
3008 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
3009 &errbuf))
3011 internal_error (__FILE__, __LINE__,
3012 "error extracting errbuf");
3015 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
3018 return trampoline_end != 0;
3021 /* Ask the IPA to probe the marker at ADDRESS. Returns -1 if running
3022 the command fails, or 0 otherwise. If the command ran
3023 successfully, but probing the marker failed, ERROUT will be filled
3024 with the error to reply to GDB, and -1 is also returned. This
3025 allows directly passing IPA errors to GDB. */
3027 static int
3028 probe_marker_at (CORE_ADDR address, char *errout)
3030 char cmd[IPA_CMD_BUF_SIZE];
3031 int err;
3033 sprintf (cmd, "probe_marker_at:%s", paddress (address));
3034 err = run_inferior_command (cmd, strlen (cmd) + 1);
3036 if (err == 0)
3038 if (*cmd == 'E')
3040 strcpy (errout, cmd);
3041 return -1;
3045 return err;
3048 static void
3049 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
3051 to->jump_pad = from->jump_pad;
3052 to->jump_pad_end = from->jump_pad_end;
3053 to->trampoline = from->trampoline;
3054 to->trampoline_end = from->trampoline_end;
3055 to->adjusted_insn_addr = from->adjusted_insn_addr;
3056 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
3057 to->handle = from->handle;
3059 gdb_assert (from->handle);
3060 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
3063 #define MAX_JUMP_SIZE 20
3065 /* Install fast tracepoint. Return 0 if successful, otherwise return
3066 non-zero. */
3068 static int
3069 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
3071 CORE_ADDR jentry, jump_entry;
3072 CORE_ADDR trampoline;
3073 CORE_ADDR collect;
3074 ULONGEST trampoline_size;
3075 int err = 0;
3076 /* The jump to the jump pad of the last fast tracepoint
3077 installed. */
3078 unsigned char fjump[MAX_JUMP_SIZE];
3079 ULONGEST fjump_size;
3081 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
3083 trace_debug ("Requested a fast tracepoint on an instruction "
3084 "that is of less than the minimum length.");
3085 return 0;
3088 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
3089 &collect))
3091 error ("error extracting gdb_collect_ptr");
3092 return 1;
3095 jentry = jump_entry = get_jump_space_head ();
3097 trampoline = 0;
3098 trampoline_size = 0;
3100 /* Install the jump pad. */
3101 err = target_install_fast_tracepoint_jump_pad
3102 (tpoint->obj_addr_on_target, tpoint->address, collect,
3103 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
3104 &trampoline, &trampoline_size, fjump, &fjump_size,
3105 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
3107 if (err)
3108 return 1;
3110 /* Wire it in. */
3111 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
3112 fjump_size);
3114 if (tpoint->handle != NULL)
3116 tpoint->jump_pad = jump_entry;
3117 tpoint->jump_pad_end = jentry;
3118 tpoint->trampoline = trampoline;
3119 tpoint->trampoline_end = trampoline + trampoline_size;
3121 /* Pad to 8-byte alignment. */
3122 jentry = ((jentry + 7) & ~0x7);
3123 claim_jump_space (jentry - jump_entry);
3126 return 0;
3130 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
3132 static void
3133 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
3135 tpoint->handle = NULL;
3136 *own_buf = '\0';
3138 if (tpoint->type == trap_tracepoint)
3140 /* Tracepoints are installed as memory breakpoints. Just go
3141 ahead and install the trap. The breakpoints module
3142 handles duplicated breakpoints, and the memory read
3143 routine handles un-patching traps from memory reads. */
3144 tpoint->handle = set_breakpoint_at (tpoint->address,
3145 tracepoint_handler);
3147 else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
3149 if (!agent_loaded_p ())
3151 trace_debug ("Requested a %s tracepoint, but fast "
3152 "tracepoints aren't supported.",
3153 tpoint->type == static_tracepoint ? "static" : "fast");
3154 write_e_ipa_not_loaded (own_buf);
3155 return;
3157 if (tpoint->type == static_tracepoint
3158 && !in_process_agent_supports_ust ())
3160 trace_debug ("Requested a static tracepoint, but static "
3161 "tracepoints are not supported.");
3162 write_e_ust_not_loaded (own_buf);
3163 return;
3166 if (tpoint->type == fast_tracepoint)
3167 install_fast_tracepoint (tpoint, own_buf);
3168 else
3170 if (probe_marker_at (tpoint->address, own_buf) == 0)
3171 tpoint->handle = (void *) -1;
3175 else
3176 internal_error (__FILE__, __LINE__, "Unknown tracepoint type");
3178 if (tpoint->handle == NULL)
3180 if (*own_buf == '\0')
3181 write_enn (own_buf);
3183 else
3184 write_ok (own_buf);
3187 static void download_tracepoint_1 (struct tracepoint *tpoint);
3189 static void
3190 cmd_qtstart (char *packet)
3192 struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
3193 CORE_ADDR tpptr = 0, prev_tpptr = 0;
3195 trace_debug ("Starting the trace");
3197 /* Pause all threads temporarily while we patch tracepoints. */
3198 target_pause_all (false);
3200 /* Get threads out of jump pads. Safe to do here, since this is a
3201 top level command. And, required to do here, since we're
3202 deleting/rewriting jump pads. */
3204 target_stabilize_threads ();
3206 /* Freeze threads. */
3207 target_pause_all (true);
3209 /* Sync the fast tracepoints list in the inferior ftlib. */
3210 if (agent_loaded_p ())
3211 download_trace_state_variables ();
3213 /* No previous fast tpoint yet. */
3214 prev_ftpoint = NULL;
3216 /* No previous static tpoint yet. */
3217 prev_stpoint = NULL;
3219 *packet = '\0';
3221 if (agent_loaded_p ())
3223 /* Tell IPA about the correct tdesc. */
3224 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
3225 target_get_ipa_tdesc_idx ()))
3226 error ("Error setting ipa_tdesc_idx variable in lib");
3229 /* Start out empty. */
3230 if (agent_loaded_p ())
3231 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
3233 /* Download and install tracepoints. */
3234 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3236 /* Ensure all the hit counts start at zero. */
3237 tpoint->hit_count = 0;
3238 tpoint->traceframe_usage = 0;
3240 if (tpoint->type == trap_tracepoint)
3242 /* Tracepoints are installed as memory breakpoints. Just go
3243 ahead and install the trap. The breakpoints module
3244 handles duplicated breakpoints, and the memory read
3245 routine handles un-patching traps from memory reads. */
3246 tpoint->handle = set_breakpoint_at (tpoint->address,
3247 tracepoint_handler);
3249 else if (tpoint->type == fast_tracepoint
3250 || tpoint->type == static_tracepoint)
3252 if (maybe_write_ipa_not_loaded (packet))
3254 trace_debug ("Requested a %s tracepoint, but fast "
3255 "tracepoints aren't supported.",
3256 tpoint->type == static_tracepoint
3257 ? "static" : "fast");
3258 break;
3261 if (tpoint->type == fast_tracepoint)
3263 int use_agent_p
3264 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3266 if (prev_ftpoint != NULL
3267 && prev_ftpoint->address == tpoint->address)
3269 if (use_agent_p)
3270 tracepoint_send_agent (tpoint);
3271 else
3272 download_tracepoint_1 (tpoint);
3274 clone_fast_tracepoint (tpoint, prev_ftpoint);
3276 else
3278 /* Tracepoint is installed successfully? */
3279 int installed = 0;
3281 /* Download and install fast tracepoint by agent. */
3282 if (use_agent_p)
3283 installed = !tracepoint_send_agent (tpoint);
3284 else
3286 download_tracepoint_1 (tpoint);
3287 installed = !install_fast_tracepoint (tpoint, packet);
3290 if (installed)
3291 prev_ftpoint = tpoint;
3294 else
3296 if (!in_process_agent_supports_ust ())
3298 trace_debug ("Requested a static tracepoint, but static "
3299 "tracepoints are not supported.");
3300 break;
3303 download_tracepoint_1 (tpoint);
3304 /* Can only probe a given marker once. */
3305 if (prev_stpoint != NULL
3306 && prev_stpoint->address == tpoint->address)
3307 tpoint->handle = (void *) -1;
3308 else
3310 if (probe_marker_at (tpoint->address, packet) == 0)
3312 tpoint->handle = (void *) -1;
3314 /* So that we can handle multiple static tracepoints
3315 at the same address easily. */
3316 prev_stpoint = tpoint;
3321 prev_tpptr = tpptr;
3322 tpptr = tpoint->obj_addr_on_target;
3324 if (tpoint == tracepoints)
3325 /* First object in list, set the head pointer in the
3326 inferior. */
3327 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3328 else
3329 write_inferior_data_pointer (prev_tpptr
3330 + offsetof (struct tracepoint, next),
3331 tpptr);
3334 /* Any failure in the inner loop is sufficient cause to give
3335 up. */
3336 if (tpoint->handle == NULL)
3337 break;
3340 /* Any error in tracepoint insertion is unacceptable; better to
3341 address the problem now, than end up with a useless or misleading
3342 trace run. */
3343 if (tpoint != NULL)
3345 clear_installed_tracepoints ();
3346 if (*packet == '\0')
3347 write_enn (packet);
3348 target_unpause_all (true);
3349 return;
3352 stopping_tracepoint = NULL;
3353 trace_buffer_is_full = 0;
3354 expr_eval_result = expr_eval_no_error;
3355 error_tracepoint = NULL;
3356 tracing_start_time = get_timestamp ();
3358 /* Tracing is now active, hits will now start being logged. */
3359 tracing = 1;
3361 if (agent_loaded_p ())
3363 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3365 internal_error (__FILE__, __LINE__,
3366 "Error setting tracing variable in lib");
3369 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3372 internal_error (__FILE__, __LINE__,
3373 "Error clearing stopping_tracepoint variable"
3374 " in lib");
3377 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3379 internal_error (__FILE__, __LINE__,
3380 "Error clearing trace_buffer_is_full variable"
3381 " in lib");
3384 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3385 stop_tracing_handler);
3386 if (stop_tracing_bkpt == NULL)
3387 error ("Error setting stop_tracing breakpoint");
3389 flush_trace_buffer_bkpt
3390 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3391 flush_trace_buffer_handler);
3392 if (flush_trace_buffer_bkpt == NULL)
3393 error ("Error setting flush_trace_buffer breakpoint");
3396 target_unpause_all (true);
3398 write_ok (packet);
3401 /* End a tracing run, filling in a stop reason to report back to GDB,
3402 and removing the tracepoints from the code. */
3404 void
3405 stop_tracing (void)
3407 if (!tracing)
3409 trace_debug ("Tracing is already off, ignoring");
3410 return;
3413 trace_debug ("Stopping the trace");
3415 /* Pause all threads before removing fast jumps from memory,
3416 breakpoints, and touching IPA state variables (inferior memory).
3417 Some thread may hit the internal tracing breakpoints, or be
3418 collecting this moment, but that's ok, we don't release the
3419 tpoint object's memory or the jump pads here (we only do that
3420 when we're sure we can move all threads out of the jump pads).
3421 We can't now, since we may be getting here due to the inferior
3422 agent calling us. */
3423 target_pause_all (true);
3425 /* Stop logging. Tracepoints can still be hit, but they will not be
3426 recorded. */
3427 tracing = 0;
3428 if (agent_loaded_p ())
3430 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3432 internal_error (__FILE__, __LINE__,
3433 "Error clearing tracing variable in lib");
3437 tracing_stop_time = get_timestamp ();
3438 tracing_stop_reason = "t???";
3439 tracing_stop_tpnum = 0;
3440 if (stopping_tracepoint)
3442 trace_debug ("Stopping the trace because "
3443 "tracepoint %d was hit %" PRIu64 " times",
3444 stopping_tracepoint->number,
3445 stopping_tracepoint->pass_count);
3446 tracing_stop_reason = "tpasscount";
3447 tracing_stop_tpnum = stopping_tracepoint->number;
3449 else if (trace_buffer_is_full)
3451 trace_debug ("Stopping the trace because the trace buffer is full");
3452 tracing_stop_reason = "tfull";
3454 else if (expr_eval_result != expr_eval_no_error)
3456 trace_debug ("Stopping the trace because of an expression eval error");
3457 tracing_stop_reason = eval_result_names[expr_eval_result];
3458 tracing_stop_tpnum = error_tracepoint->number;
3460 #ifndef IN_PROCESS_AGENT
3461 else if (!gdb_connected ())
3463 trace_debug ("Stopping the trace because GDB disconnected");
3464 tracing_stop_reason = "tdisconnected";
3466 #endif
3467 else
3469 trace_debug ("Stopping the trace because of a tstop command");
3470 tracing_stop_reason = "tstop";
3473 stopping_tracepoint = NULL;
3474 error_tracepoint = NULL;
3476 /* Clear out the tracepoints. */
3477 clear_installed_tracepoints ();
3479 if (agent_loaded_p ())
3481 /* Pull in fast tracepoint trace frames from the inferior lib
3482 buffer into our buffer, even if our buffer is already full,
3483 because we want to present the full number of created frames
3484 in addition to what fit in the trace buffer. */
3485 upload_fast_traceframes ();
3488 if (stop_tracing_bkpt != NULL)
3490 delete_breakpoint (stop_tracing_bkpt);
3491 stop_tracing_bkpt = NULL;
3494 if (flush_trace_buffer_bkpt != NULL)
3496 delete_breakpoint (flush_trace_buffer_bkpt);
3497 flush_trace_buffer_bkpt = NULL;
3500 target_unpause_all (true);
3503 static int
3504 stop_tracing_handler (CORE_ADDR addr)
3506 trace_debug ("lib hit stop_tracing");
3508 /* Don't actually handle it here. When we stop tracing we remove
3509 breakpoints from the inferior, and that is not allowed in a
3510 breakpoint handler (as the caller is walking the breakpoint
3511 list). */
3512 return 0;
3515 static int
3516 flush_trace_buffer_handler (CORE_ADDR addr)
3518 trace_debug ("lib hit flush_trace_buffer");
3519 return 0;
3522 static void
3523 cmd_qtstop (char *packet)
3525 stop_tracing ();
3526 write_ok (packet);
3529 static void
3530 cmd_qtdisconnected (char *own_buf)
3532 ULONGEST setting;
3533 char *packet = own_buf;
3535 packet += strlen ("QTDisconnected:");
3537 unpack_varlen_hex (packet, &setting);
3539 write_ok (own_buf);
3541 disconnected_tracing = setting;
3544 static void
3545 cmd_qtframe (char *own_buf)
3547 client_state &cs = get_client_state ();
3548 ULONGEST frame, pc, lo, hi, num;
3549 int tfnum, tpnum;
3550 struct traceframe *tframe;
3551 const char *packet = own_buf;
3553 packet += strlen ("QTFrame:");
3555 if (startswith (packet, "pc:"))
3557 packet += strlen ("pc:");
3558 unpack_varlen_hex (packet, &pc);
3559 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3560 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3562 else if (startswith (packet, "range:"))
3564 packet += strlen ("range:");
3565 packet = unpack_varlen_hex (packet, &lo);
3566 ++packet;
3567 unpack_varlen_hex (packet, &hi);
3568 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3569 paddress (lo), paddress (hi));
3570 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3572 else if (startswith (packet, "outside:"))
3574 packet += strlen ("outside:");
3575 packet = unpack_varlen_hex (packet, &lo);
3576 ++packet;
3577 unpack_varlen_hex (packet, &hi);
3578 trace_debug ("Want to find next traceframe "
3579 "outside the range 0x%s to 0x%s",
3580 paddress (lo), paddress (hi));
3581 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3583 else if (startswith (packet, "tdp:"))
3585 packet += strlen ("tdp:");
3586 unpack_varlen_hex (packet, &num);
3587 tpnum = (int) num;
3588 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3589 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3591 else
3593 unpack_varlen_hex (packet, &frame);
3594 tfnum = (int) frame;
3595 if (tfnum == -1)
3597 trace_debug ("Want to stop looking at traceframes");
3598 cs.current_traceframe = -1;
3599 write_ok (own_buf);
3600 return;
3602 trace_debug ("Want to look at traceframe %d", tfnum);
3603 tframe = find_traceframe (tfnum);
3606 if (tframe)
3608 cs.current_traceframe = tfnum;
3609 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3611 else
3612 sprintf (own_buf, "F-1");
3615 static void
3616 cmd_qtstatus (char *packet)
3618 char *stop_reason_rsp = NULL;
3619 char *buf1, *buf2, *buf3;
3620 const char *str;
3621 int slen;
3623 /* Translate the plain text of the notes back into hex for
3624 transmission. */
3626 str = (tracing_user_name ? tracing_user_name : "");
3627 slen = strlen (str);
3628 buf1 = (char *) alloca (slen * 2 + 1);
3629 bin2hex ((gdb_byte *) str, buf1, slen);
3631 str = (tracing_notes ? tracing_notes : "");
3632 slen = strlen (str);
3633 buf2 = (char *) alloca (slen * 2 + 1);
3634 bin2hex ((gdb_byte *) str, buf2, slen);
3636 str = (tracing_stop_note ? tracing_stop_note : "");
3637 slen = strlen (str);
3638 buf3 = (char *) alloca (slen * 2 + 1);
3639 bin2hex ((gdb_byte *) str, buf3, slen);
3641 trace_debug ("Returning trace status as %d, stop reason %s",
3642 tracing, tracing_stop_reason);
3644 if (agent_loaded_p ())
3646 target_pause_all (true);
3648 upload_fast_traceframes ();
3650 target_unpause_all (true);
3653 stop_reason_rsp = (char *) tracing_stop_reason;
3655 /* The user visible error string in terror needs to be hex encoded.
3656 We leave it as plain string in `tracing_stop_reason' to ease
3657 debugging. */
3658 if (startswith (stop_reason_rsp, "terror:"))
3660 const char *result_name;
3661 int hexstr_len;
3662 char *p;
3664 result_name = stop_reason_rsp + strlen ("terror:");
3665 hexstr_len = strlen (result_name) * 2;
3666 p = stop_reason_rsp
3667 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3668 strcpy (p, "terror:");
3669 p += strlen (p);
3670 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3673 /* If this was a forced stop, include any stop note that was supplied. */
3674 if (strcmp (stop_reason_rsp, "tstop") == 0)
3676 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3677 strcpy (stop_reason_rsp, "tstop:");
3678 strcat (stop_reason_rsp, buf3);
3681 sprintf (packet,
3682 "T%d;"
3683 "%s:%x;"
3684 "tframes:%x;tcreated:%x;"
3685 "tfree:%x;tsize:%s;"
3686 "circular:%d;"
3687 "disconn:%d;"
3688 "starttime:%s;stoptime:%s;"
3689 "username:%s;notes:%s:",
3690 tracing ? 1 : 0,
3691 stop_reason_rsp, tracing_stop_tpnum,
3692 traceframe_count, traceframes_created,
3693 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3694 circular_trace_buffer,
3695 disconnected_tracing,
3696 phex_nz (tracing_start_time, sizeof (tracing_start_time)),
3697 phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
3698 buf1, buf2);
3701 static void
3702 cmd_qtp (char *own_buf)
3704 ULONGEST num, addr;
3705 struct tracepoint *tpoint;
3706 const char *packet = own_buf;
3708 packet += strlen ("qTP:");
3710 packet = unpack_varlen_hex (packet, &num);
3711 ++packet; /* skip a colon */
3712 packet = unpack_varlen_hex (packet, &addr);
3714 /* See if we already have this tracepoint. */
3715 tpoint = find_tracepoint (num, addr);
3717 if (!tpoint)
3719 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3720 (int) num, paddress (addr));
3721 write_enn (own_buf);
3722 return;
3725 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3726 tpoint->traceframe_usage);
3729 /* State variables to help return all the tracepoint bits. */
3730 static struct tracepoint *cur_tpoint;
3731 static unsigned int cur_action;
3732 static unsigned int cur_step_action;
3733 static struct source_string *cur_source_string;
3734 static struct trace_state_variable *cur_tsv;
3736 /* Compose a response that is an imitation of the syntax by which the
3737 tracepoint was originally downloaded. */
3739 static void
3740 response_tracepoint (char *packet, struct tracepoint *tpoint)
3742 char *buf;
3744 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3745 paddress (tpoint->address),
3746 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3747 tpoint->pass_count);
3748 if (tpoint->type == fast_tracepoint)
3749 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3750 else if (tpoint->type == static_tracepoint)
3751 sprintf (packet + strlen (packet), ":S");
3753 if (tpoint->cond)
3755 buf = gdb_unparse_agent_expr (tpoint->cond);
3756 sprintf (packet + strlen (packet), ":X%x,%s",
3757 tpoint->cond->length, buf);
3758 free (buf);
3762 /* Compose a response that is an imitation of the syntax by which the
3763 tracepoint action was originally downloaded (with the difference
3764 that due to the way we store the actions, this will output a packet
3765 per action, while GDB could have combined more than one action
3766 per-packet. */
3768 static void
3769 response_action (char *packet, struct tracepoint *tpoint,
3770 char *taction, int step)
3772 sprintf (packet, "%c%x:%s:%s",
3773 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3774 taction);
3777 /* Compose a response that is an imitation of the syntax by which the
3778 tracepoint source piece was originally downloaded. */
3780 static void
3781 response_source (char *packet,
3782 struct tracepoint *tpoint, struct source_string *src)
3784 char *buf;
3785 int len;
3787 len = strlen (src->str);
3788 buf = (char *) alloca (len * 2 + 1);
3789 bin2hex ((gdb_byte *) src->str, buf, len);
3791 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3792 tpoint->number, paddress (tpoint->address),
3793 src->type, 0, len, buf);
3796 /* Return the first piece of tracepoint definition, and initialize the
3797 state machine that will iterate through all the tracepoint
3798 bits. */
3800 static void
3801 cmd_qtfp (char *packet)
3803 trace_debug ("Returning first tracepoint definition piece");
3805 cur_tpoint = tracepoints;
3806 cur_action = cur_step_action = 0;
3807 cur_source_string = NULL;
3809 if (cur_tpoint)
3810 response_tracepoint (packet, cur_tpoint);
3811 else
3812 strcpy (packet, "l");
3815 /* Return additional pieces of tracepoint definition. Each action and
3816 stepping action must go into its own packet, because of packet size
3817 limits, and so we use state variables to deliver one piece at a
3818 time. */
3820 static void
3821 cmd_qtsp (char *packet)
3823 trace_debug ("Returning subsequent tracepoint definition piece");
3825 if (!cur_tpoint)
3827 /* This case would normally never occur, but be prepared for
3828 GDB misbehavior. */
3829 strcpy (packet, "l");
3831 else if (cur_action < cur_tpoint->numactions)
3833 response_action (packet, cur_tpoint,
3834 cur_tpoint->actions_str[cur_action], 0);
3835 ++cur_action;
3837 else if (cur_step_action < cur_tpoint->num_step_actions)
3839 response_action (packet, cur_tpoint,
3840 cur_tpoint->step_actions_str[cur_step_action], 1);
3841 ++cur_step_action;
3843 else if ((cur_source_string
3844 ? cur_source_string->next
3845 : cur_tpoint->source_strings))
3847 if (cur_source_string)
3848 cur_source_string = cur_source_string->next;
3849 else
3850 cur_source_string = cur_tpoint->source_strings;
3851 response_source (packet, cur_tpoint, cur_source_string);
3853 else
3855 cur_tpoint = cur_tpoint->next;
3856 cur_action = cur_step_action = 0;
3857 cur_source_string = NULL;
3858 if (cur_tpoint)
3859 response_tracepoint (packet, cur_tpoint);
3860 else
3861 strcpy (packet, "l");
3865 /* Compose a response that is an imitation of the syntax by which the
3866 trace state variable was originally downloaded. */
3868 static void
3869 response_tsv (char *packet, struct trace_state_variable *tsv)
3871 char *buf = (char *) "";
3872 int namelen;
3874 if (tsv->name)
3876 namelen = strlen (tsv->name);
3877 buf = (char *) alloca (namelen * 2 + 1);
3878 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3881 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3882 tsv->getter ? 1 : 0, buf);
3885 /* Return the first trace state variable definition, and initialize
3886 the state machine that will iterate through all the tsv bits. */
3888 static void
3889 cmd_qtfv (char *packet)
3891 trace_debug ("Returning first trace state variable definition");
3893 cur_tsv = trace_state_variables;
3895 if (cur_tsv)
3896 response_tsv (packet, cur_tsv);
3897 else
3898 strcpy (packet, "l");
3901 /* Return additional trace state variable definitions. */
3903 static void
3904 cmd_qtsv (char *packet)
3906 trace_debug ("Returning additional trace state variable definition");
3908 if (cur_tsv)
3910 cur_tsv = cur_tsv->next;
3911 if (cur_tsv)
3912 response_tsv (packet, cur_tsv);
3913 else
3914 strcpy (packet, "l");
3916 else
3917 strcpy (packet, "l");
3920 /* Return the first static tracepoint marker, and initialize the state
3921 machine that will iterate through all the static tracepoints
3922 markers. */
3924 static void
3925 cmd_qtfstm (char *packet)
3927 if (!maybe_write_ipa_ust_not_loaded (packet))
3928 run_inferior_command (packet, strlen (packet) + 1);
3931 /* Return additional static tracepoints markers. */
3933 static void
3934 cmd_qtsstm (char *packet)
3936 if (!maybe_write_ipa_ust_not_loaded (packet))
3937 run_inferior_command (packet, strlen (packet) + 1);
3940 /* Return the definition of the static tracepoint at a given address.
3941 Result packet is the same as qTsST's. */
3943 static void
3944 cmd_qtstmat (char *packet)
3946 if (!maybe_write_ipa_ust_not_loaded (packet))
3947 run_inferior_command (packet, strlen (packet) + 1);
3950 /* Sent the agent a command to close it. */
3952 void
3953 gdb_agent_about_to_close (int pid)
3955 char buf[IPA_CMD_BUF_SIZE];
3957 if (!maybe_write_ipa_not_loaded (buf))
3959 scoped_restore_current_thread restore_thread;
3961 /* Find any thread which belongs to process PID. */
3962 switch_to_thread (find_any_thread_of_pid (pid));
3964 strcpy (buf, "close");
3966 run_inferior_command (buf, strlen (buf) + 1);
3970 /* Return the minimum instruction size needed for fast tracepoints as a
3971 hexadecimal number. */
3973 static void
3974 cmd_qtminftpilen (char *packet)
3976 if (current_thread == NULL)
3978 /* Indicate that the minimum length is currently unknown. */
3979 strcpy (packet, "0");
3980 return;
3983 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3986 /* Respond to qTBuffer packet with a block of raw data from the trace
3987 buffer. GDB may ask for a lot, but we are allowed to reply with
3988 only as much as will fit within packet limits or whatever. */
3990 static void
3991 cmd_qtbuffer (char *own_buf)
3993 ULONGEST offset, num, tot;
3994 unsigned char *tbp;
3995 const char *packet = own_buf;
3997 packet += strlen ("qTBuffer:");
3999 packet = unpack_varlen_hex (packet, &offset);
4000 ++packet; /* skip a comma */
4001 unpack_varlen_hex (packet, &num);
4003 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
4004 (int) num, phex_nz (offset, 0));
4006 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
4008 /* If we're right at the end, reply specially that we're done. */
4009 if (offset == tot)
4011 strcpy (own_buf, "l");
4012 return;
4015 /* Object to any other out-of-bounds request. */
4016 if (offset > tot)
4018 write_enn (own_buf);
4019 return;
4022 /* Compute the pointer corresponding to the given offset, accounting
4023 for wraparound. */
4024 tbp = trace_buffer_start + offset;
4025 if (tbp >= trace_buffer_wrap)
4026 tbp -= (trace_buffer_wrap - trace_buffer_lo);
4028 /* Trim to the remaining bytes if we're close to the end. */
4029 if (num > tot - offset)
4030 num = tot - offset;
4032 /* Trim to available packet size. */
4033 if (num >= (PBUFSIZ - 16) / 2 )
4034 num = (PBUFSIZ - 16) / 2;
4036 bin2hex (tbp, own_buf, num);
4039 static void
4040 cmd_bigqtbuffer_circular (char *own_buf)
4042 ULONGEST val;
4043 char *packet = own_buf;
4045 packet += strlen ("QTBuffer:circular:");
4047 unpack_varlen_hex (packet, &val);
4048 circular_trace_buffer = val;
4049 trace_debug ("Trace buffer is now %s",
4050 circular_trace_buffer ? "circular" : "linear");
4051 write_ok (own_buf);
4054 static void
4055 cmd_bigqtbuffer_size (char *own_buf)
4057 ULONGEST val;
4058 LONGEST sval;
4059 char *packet = own_buf;
4061 /* Can't change the size during a tracing run. */
4062 if (tracing)
4064 write_enn (own_buf);
4065 return;
4068 packet += strlen ("QTBuffer:size:");
4070 /* -1 is sent as literal "-1". */
4071 if (strcmp (packet, "-1") == 0)
4072 sval = DEFAULT_TRACE_BUFFER_SIZE;
4073 else
4075 unpack_varlen_hex (packet, &val);
4076 sval = (LONGEST) val;
4079 init_trace_buffer (sval);
4080 trace_debug ("Trace buffer is now %s bytes",
4081 plongest (trace_buffer_size));
4082 write_ok (own_buf);
4085 static void
4086 cmd_qtnotes (char *own_buf)
4088 size_t nbytes;
4089 char *saved, *user, *notes, *stopnote;
4090 char *packet = own_buf;
4092 packet += strlen ("QTNotes:");
4094 while (*packet)
4096 if (startswith (packet, "user:"))
4098 packet += strlen ("user:");
4099 saved = packet;
4100 packet = strchr (packet, ';');
4101 nbytes = (packet - saved) / 2;
4102 user = (char *) xmalloc (nbytes + 1);
4103 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
4104 user[nbytes] = '\0';
4105 ++packet; /* skip the semicolon */
4106 trace_debug ("User is '%s'", user);
4107 xfree (tracing_user_name);
4108 tracing_user_name = user;
4110 else if (startswith (packet, "notes:"))
4112 packet += strlen ("notes:");
4113 saved = packet;
4114 packet = strchr (packet, ';');
4115 nbytes = (packet - saved) / 2;
4116 notes = (char *) xmalloc (nbytes + 1);
4117 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
4118 notes[nbytes] = '\0';
4119 ++packet; /* skip the semicolon */
4120 trace_debug ("Notes is '%s'", notes);
4121 xfree (tracing_notes);
4122 tracing_notes = notes;
4124 else if (startswith (packet, "tstop:"))
4126 packet += strlen ("tstop:");
4127 saved = packet;
4128 packet = strchr (packet, ';');
4129 nbytes = (packet - saved) / 2;
4130 stopnote = (char *) xmalloc (nbytes + 1);
4131 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
4132 stopnote[nbytes] = '\0';
4133 ++packet; /* skip the semicolon */
4134 trace_debug ("tstop note is '%s'", stopnote);
4135 xfree (tracing_stop_note);
4136 tracing_stop_note = stopnote;
4138 else
4139 break;
4142 write_ok (own_buf);
4146 handle_tracepoint_general_set (char *packet)
4148 if (strcmp ("QTinit", packet) == 0)
4150 cmd_qtinit (packet);
4151 return 1;
4153 else if (startswith (packet, "QTDP:"))
4155 cmd_qtdp (packet);
4156 return 1;
4158 else if (startswith (packet, "QTDPsrc:"))
4160 cmd_qtdpsrc (packet);
4161 return 1;
4163 else if (startswith (packet, "QTEnable:"))
4165 cmd_qtenable_disable (packet, 1);
4166 return 1;
4168 else if (startswith (packet, "QTDisable:"))
4170 cmd_qtenable_disable (packet, 0);
4171 return 1;
4173 else if (startswith (packet, "QTDV:"))
4175 cmd_qtdv (packet);
4176 return 1;
4178 else if (startswith (packet, "QTro:"))
4180 cmd_qtro (packet);
4181 return 1;
4183 else if (strcmp ("QTStart", packet) == 0)
4185 cmd_qtstart (packet);
4186 return 1;
4188 else if (strcmp ("QTStop", packet) == 0)
4190 cmd_qtstop (packet);
4191 return 1;
4193 else if (startswith (packet, "QTDisconnected:"))
4195 cmd_qtdisconnected (packet);
4196 return 1;
4198 else if (startswith (packet, "QTFrame:"))
4200 cmd_qtframe (packet);
4201 return 1;
4203 else if (startswith (packet, "QTBuffer:circular:"))
4205 cmd_bigqtbuffer_circular (packet);
4206 return 1;
4208 else if (startswith (packet, "QTBuffer:size:"))
4210 cmd_bigqtbuffer_size (packet);
4211 return 1;
4213 else if (startswith (packet, "QTNotes:"))
4215 cmd_qtnotes (packet);
4216 return 1;
4219 return 0;
4223 handle_tracepoint_query (char *packet)
4225 if (strcmp ("qTStatus", packet) == 0)
4227 cmd_qtstatus (packet);
4228 return 1;
4230 else if (startswith (packet, "qTP:"))
4232 cmd_qtp (packet);
4233 return 1;
4235 else if (strcmp ("qTfP", packet) == 0)
4237 cmd_qtfp (packet);
4238 return 1;
4240 else if (strcmp ("qTsP", packet) == 0)
4242 cmd_qtsp (packet);
4243 return 1;
4245 else if (strcmp ("qTfV", packet) == 0)
4247 cmd_qtfv (packet);
4248 return 1;
4250 else if (strcmp ("qTsV", packet) == 0)
4252 cmd_qtsv (packet);
4253 return 1;
4255 else if (startswith (packet, "qTV:"))
4257 cmd_qtv (packet);
4258 return 1;
4260 else if (startswith (packet, "qTBuffer:"))
4262 cmd_qtbuffer (packet);
4263 return 1;
4265 else if (strcmp ("qTfSTM", packet) == 0)
4267 cmd_qtfstm (packet);
4268 return 1;
4270 else if (strcmp ("qTsSTM", packet) == 0)
4272 cmd_qtsstm (packet);
4273 return 1;
4275 else if (startswith (packet, "qTSTMat:"))
4277 cmd_qtstmat (packet);
4278 return 1;
4280 else if (strcmp ("qTMinFTPILen", packet) == 0)
4282 cmd_qtminftpilen (packet);
4283 return 1;
4286 return 0;
4289 #endif
4290 #ifndef IN_PROCESS_AGENT
4292 /* Call this when thread TINFO has hit the tracepoint defined by
4293 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
4294 action. This adds a while-stepping collecting state item to the
4295 threads' collecting state list, so that we can keep track of
4296 multiple simultaneous while-stepping actions being collected by the
4297 same thread. This can happen in cases like:
4299 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
4300 ff0002 INSN2
4301 ff0003 INSN3 <-- TP2, collect $regs
4302 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
4303 ff0005 INSN5
4305 Notice that when instruction INSN5 is reached, the while-stepping
4306 actions of both TP1 and TP3 are still being collected, and that TP2
4307 had been collected meanwhile. The whole range of ff0001-ff0005
4308 should be single-stepped, due to at least TP1's while-stepping
4309 action covering the whole range. */
4311 static void
4312 add_while_stepping_state (struct thread_info *tinfo,
4313 int tp_number, CORE_ADDR tp_address)
4315 struct wstep_state *wstep = XNEW (struct wstep_state);
4317 wstep->next = tinfo->while_stepping;
4319 wstep->tp_number = tp_number;
4320 wstep->tp_address = tp_address;
4321 wstep->current_step = 0;
4323 tinfo->while_stepping = wstep;
4326 /* Release the while-stepping collecting state WSTEP. */
4328 static void
4329 release_while_stepping_state (struct wstep_state *wstep)
4331 free (wstep);
4334 /* Release all while-stepping collecting states currently associated
4335 with thread TINFO. */
4337 void
4338 release_while_stepping_state_list (struct thread_info *tinfo)
4340 struct wstep_state *head;
4342 while (tinfo->while_stepping)
4344 head = tinfo->while_stepping;
4345 tinfo->while_stepping = head->next;
4346 release_while_stepping_state (head);
4350 /* If TINFO was handling a 'while-stepping' action, the step has
4351 finished, so collect any step data needed, and check if any more
4352 steps are required. Return true if the thread was indeed
4353 collecting tracepoint data, false otherwise. */
4356 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
4358 struct tracepoint *tpoint;
4359 struct wstep_state *wstep;
4360 struct wstep_state **wstep_link;
4361 struct trap_tracepoint_ctx ctx;
4363 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4364 our buffer. */
4365 if (agent_loaded_p ())
4366 upload_fast_traceframes ();
4368 /* Check if we were indeed collecting data for one of more
4369 tracepoints with a 'while-stepping' count. */
4370 if (tinfo->while_stepping == NULL)
4371 return 0;
4373 if (!tracing)
4375 /* We're not even tracing anymore. Stop this thread from
4376 collecting. */
4377 release_while_stepping_state_list (tinfo);
4379 /* The thread had stopped due to a single-step request indeed
4380 explained by a tracepoint. */
4381 return 1;
4384 wstep = tinfo->while_stepping;
4385 wstep_link = &tinfo->while_stepping;
4387 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4388 target_pid_to_str (tinfo->id).c_str (),
4389 wstep->tp_number, paddress (wstep->tp_address));
4391 ctx.base.type = trap_tracepoint;
4392 ctx.regcache = get_thread_regcache (tinfo, 1);
4394 while (wstep != NULL)
4396 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4397 if (tpoint == NULL)
4399 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4400 wstep->tp_number, paddress (wstep->tp_address),
4401 target_pid_to_str (tinfo->id).c_str ());
4403 /* Unlink. */
4404 *wstep_link = wstep->next;
4405 release_while_stepping_state (wstep);
4406 wstep = *wstep_link;
4407 continue;
4410 /* We've just finished one step. */
4411 ++wstep->current_step;
4413 /* Collect data. */
4414 collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
4415 stop_pc, tpoint, wstep->current_step);
4417 if (wstep->current_step >= tpoint->step_count)
4419 /* The requested numbers of steps have occurred. */
4420 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4421 target_pid_to_str (tinfo->id).c_str (),
4422 wstep->tp_number, paddress (wstep->tp_address));
4424 /* Unlink the wstep. */
4425 *wstep_link = wstep->next;
4426 release_while_stepping_state (wstep);
4427 wstep = *wstep_link;
4429 /* Only check the hit count now, which ensure that we do all
4430 our stepping before stopping the run. */
4431 if (tpoint->pass_count > 0
4432 && tpoint->hit_count >= tpoint->pass_count
4433 && stopping_tracepoint == NULL)
4434 stopping_tracepoint = tpoint;
4436 else
4438 /* Keep single-stepping until the requested numbers of steps
4439 have occurred. */
4440 wstep_link = &wstep->next;
4441 wstep = *wstep_link;
4444 if (stopping_tracepoint
4445 || trace_buffer_is_full
4446 || expr_eval_result != expr_eval_no_error)
4448 stop_tracing ();
4449 break;
4453 return 1;
4456 /* Handle any internal tracing control breakpoint hits. That means,
4457 pull traceframes from the IPA to our buffer, and syncing both
4458 tracing agents when the IPA's tracing stops for some reason. */
4461 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
4463 /* Pull in fast tracepoint trace frames from the inferior in-process
4464 agent's buffer into our buffer. */
4466 if (!agent_loaded_p ())
4467 return 0;
4469 upload_fast_traceframes ();
4471 /* Check if the in-process agent had decided we should stop
4472 tracing. */
4473 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4475 int ipa_trace_buffer_is_full;
4476 CORE_ADDR ipa_stopping_tracepoint;
4477 int ipa_expr_eval_result;
4478 CORE_ADDR ipa_error_tracepoint;
4480 trace_debug ("lib stopped at stop_tracing");
4482 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4483 &ipa_trace_buffer_is_full);
4485 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4486 &ipa_stopping_tracepoint);
4487 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4489 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4490 &ipa_error_tracepoint);
4491 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4493 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4494 &ipa_expr_eval_result);
4495 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4497 trace_debug ("lib: trace_buffer_is_full: %d, "
4498 "stopping_tracepoint: %s, "
4499 "ipa_expr_eval_result: %d, "
4500 "error_tracepoint: %s, ",
4501 ipa_trace_buffer_is_full,
4502 paddress (ipa_stopping_tracepoint),
4503 ipa_expr_eval_result,
4504 paddress (ipa_error_tracepoint));
4506 if (ipa_trace_buffer_is_full)
4507 trace_debug ("lib stopped due to full buffer.");
4509 if (ipa_stopping_tracepoint)
4510 trace_debug ("lib stopped due to tpoint");
4512 if (ipa_error_tracepoint)
4513 trace_debug ("lib stopped due to error");
4515 if (ipa_stopping_tracepoint != 0)
4517 stopping_tracepoint
4518 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4520 else if (ipa_expr_eval_result != expr_eval_no_error)
4522 expr_eval_result = ipa_expr_eval_result;
4523 error_tracepoint
4524 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4526 stop_tracing ();
4527 return 1;
4529 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4531 trace_debug ("lib stopped at flush_trace_buffer");
4532 return 1;
4535 return 0;
4538 /* Return true if TINFO just hit a tracepoint. Collect data if
4539 so. */
4542 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
4544 struct tracepoint *tpoint;
4545 int ret = 0;
4546 struct trap_tracepoint_ctx ctx;
4548 /* Not tracing, don't handle. */
4549 if (!tracing)
4550 return 0;
4552 ctx.base.type = trap_tracepoint;
4553 ctx.regcache = get_thread_regcache (tinfo, 1);
4555 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4557 /* Note that we collect fast tracepoints here as well. We'll
4558 step over the fast tracepoint jump later, which avoids the
4559 double collect. However, we don't collect for static
4560 tracepoints here, because UST markers are compiled in program,
4561 and probes will be executed in program. So static tracepoints
4562 are collected there. */
4563 if (tpoint->enabled && stop_pc == tpoint->address
4564 && tpoint->type != static_tracepoint)
4566 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4567 target_pid_to_str (tinfo->id).c_str (),
4568 tpoint->number, paddress (tpoint->address));
4570 /* Test the condition if present, and collect if true. */
4571 if (!tpoint->cond
4572 || (condition_true_at_tracepoint
4573 ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
4574 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4575 stop_pc, tpoint);
4577 if (stopping_tracepoint
4578 || trace_buffer_is_full
4579 || expr_eval_result != expr_eval_no_error)
4581 stop_tracing ();
4583 /* If the tracepoint had a 'while-stepping' action, then set
4584 the thread to collect this tracepoint on the following
4585 single-steps. */
4586 else if (tpoint->step_count > 0)
4588 add_while_stepping_state (tinfo,
4589 tpoint->number, tpoint->address);
4592 ret = 1;
4596 return ret;
4599 #endif
4601 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4602 struct ust_marker_data;
4603 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4604 struct traceframe *tframe);
4605 #endif
4607 /* Create a trace frame for the hit of the given tracepoint in the
4608 given thread. */
4610 static void
4611 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4612 struct tracepoint *tpoint)
4614 struct traceframe *tframe;
4615 int acti;
4617 /* Only count it as a hit when we actually collect data. */
4618 tpoint->hit_count++;
4620 /* If we've exceeded a defined pass count, record the event for
4621 later, and finish the collection for this hit. This test is only
4622 for nonstepping tracepoints, stepping tracepoints test at the end
4623 of their while-stepping loop. */
4624 if (tpoint->pass_count > 0
4625 && tpoint->hit_count >= tpoint->pass_count
4626 && tpoint->step_count == 0
4627 && stopping_tracepoint == NULL)
4628 stopping_tracepoint = tpoint;
4630 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4631 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4633 tframe = add_traceframe (tpoint);
4635 if (tframe)
4637 for (acti = 0; acti < tpoint->numactions; ++acti)
4639 #ifndef IN_PROCESS_AGENT
4640 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4641 tpoint->number, paddress (tpoint->address),
4642 tpoint->actions_str[acti]);
4643 #endif
4645 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4646 tpoint->actions[acti]);
4649 finish_traceframe (tframe);
4652 if (tframe == NULL && tracing)
4653 trace_buffer_is_full = 1;
4656 #ifndef IN_PROCESS_AGENT
4658 static void
4659 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4660 CORE_ADDR stop_pc,
4661 struct tracepoint *tpoint, int current_step)
4663 struct traceframe *tframe;
4664 int acti;
4666 trace_debug ("Making new step traceframe for "
4667 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4668 tpoint->number, paddress (tpoint->address),
4669 current_step, tpoint->step_count,
4670 tpoint->hit_count);
4672 tframe = add_traceframe (tpoint);
4674 if (tframe)
4676 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4678 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4679 tpoint->number, paddress (tpoint->address),
4680 tpoint->step_actions_str[acti]);
4682 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4683 tpoint->step_actions[acti]);
4686 finish_traceframe (tframe);
4689 if (tframe == NULL && tracing)
4690 trace_buffer_is_full = 1;
4693 #endif
4695 #ifdef IN_PROCESS_AGENT
4696 /* The target description index for IPA. Passed from gdbserver, used
4697 to select ipa_tdesc. */
4698 EXTERN_C_PUSH
4699 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
4700 EXTERN_C_POP
4701 #endif
4703 static struct regcache *
4704 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4706 struct regcache *regcache = NULL;
4707 #ifdef IN_PROCESS_AGENT
4708 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
4710 if (ctx->type == fast_tracepoint)
4712 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4713 if (!fctx->regcache_initted)
4715 fctx->regcache_initted = 1;
4716 init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
4717 supply_regblock (&fctx->regcache, NULL);
4718 supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4720 regcache = &fctx->regcache;
4722 #ifdef HAVE_UST
4723 if (ctx->type == static_tracepoint)
4725 struct static_tracepoint_ctx *sctx
4726 = (struct static_tracepoint_ctx *) ctx;
4728 if (!sctx->regcache_initted)
4730 sctx->regcache_initted = 1;
4731 init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
4732 supply_regblock (&sctx->regcache, NULL);
4733 /* Pass down the tracepoint address, because REGS doesn't
4734 include the PC, but we know what it must have been. */
4735 supply_static_tracepoint_registers (&sctx->regcache,
4736 (const unsigned char *)
4737 sctx->regs,
4738 sctx->tpoint->address);
4740 regcache = &sctx->regcache;
4742 #endif
4743 #else
4744 if (ctx->type == trap_tracepoint)
4746 struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4747 regcache = tctx->regcache;
4749 #endif
4751 gdb_assert (regcache != NULL);
4753 return regcache;
4756 static void
4757 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4758 CORE_ADDR stop_pc,
4759 struct tracepoint *tpoint,
4760 struct traceframe *tframe,
4761 struct tracepoint_action *taction)
4763 enum eval_result_type err;
4765 switch (taction->type)
4767 case 'M':
4769 struct collect_memory_action *maction;
4770 struct eval_agent_expr_context ax_ctx;
4772 maction = (struct collect_memory_action *) taction;
4773 ax_ctx.regcache = NULL;
4774 ax_ctx.tframe = tframe;
4775 ax_ctx.tpoint = tpoint;
4777 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4778 pulongest (maction->len),
4779 paddress (maction->addr), maction->basereg);
4780 /* (should use basereg) */
4781 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4782 maction->len);
4783 break;
4785 case 'R':
4787 unsigned char *regspace;
4788 struct regcache tregcache;
4789 struct regcache *context_regcache;
4790 int regcache_size;
4792 trace_debug ("Want to collect registers");
4794 context_regcache = get_context_regcache (ctx);
4795 regcache_size = register_cache_size (context_regcache->tdesc);
4797 /* Collect all registers for now. */
4798 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4799 if (regspace == NULL)
4801 trace_debug ("Trace buffer block allocation failed, skipping");
4802 break;
4804 /* Identify a register block. */
4805 *regspace = 'R';
4807 /* Wrap the regblock in a register cache (in the stack, we
4808 don't want to malloc here). */
4809 init_register_cache (&tregcache, context_regcache->tdesc,
4810 regspace + 1);
4812 /* Copy the register data to the regblock. */
4813 regcache_cpy (&tregcache, context_regcache);
4815 #ifndef IN_PROCESS_AGENT
4816 /* On some platforms, trap-based tracepoints will have the PC
4817 pointing to the next instruction after the trap, but we
4818 don't want the user or GDB trying to guess whether the
4819 saved PC needs adjusting; so always record the adjusted
4820 stop_pc. Note that we can't use tpoint->address instead,
4821 since it will be wrong for while-stepping actions. This
4822 adjustment is a nop for fast tracepoints collected from the
4823 in-process lib (but not if GDBserver is collecting one
4824 preemptively), since the PC had already been adjusted to
4825 contain the tracepoint's address by the jump pad. */
4826 trace_debug ("Storing stop pc (0x%s) in regblock",
4827 paddress (stop_pc));
4829 /* This changes the regblock, not the thread's
4830 regcache. */
4831 regcache_write_pc (&tregcache, stop_pc);
4832 #endif
4834 break;
4835 case 'X':
4837 struct eval_expr_action *eaction;
4838 struct eval_agent_expr_context ax_ctx;
4840 eaction = (struct eval_expr_action *) taction;
4841 ax_ctx.regcache = get_context_regcache (ctx);
4842 ax_ctx.tframe = tframe;
4843 ax_ctx.tpoint = tpoint;
4845 trace_debug ("Want to evaluate expression");
4847 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4849 if (err != expr_eval_no_error)
4851 record_tracepoint_error (tpoint, "action expression", err);
4852 return;
4855 break;
4856 case 'L':
4858 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4859 trace_debug ("Want to collect static trace data");
4860 collect_ust_data_at_tracepoint (ctx, tframe);
4861 #else
4862 trace_debug ("warning: collecting static trace data, "
4863 "but static tracepoints are not supported");
4864 #endif
4866 break;
4867 default:
4868 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4869 break;
4873 static int
4874 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4875 struct tracepoint *tpoint)
4877 ULONGEST value = 0;
4878 enum eval_result_type err;
4880 /* Presently, gdbserver doesn't run compiled conditions, only the
4881 IPA does. If the program stops at a fast tracepoint's address
4882 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4883 gdbserver preemptively collect the fast tracepoint. Later, on
4884 resume, gdbserver steps over the fast tracepoint like it steps
4885 over breakpoints, so that the IPA doesn't see that fast
4886 tracepoint. This avoids double collects of fast tracepoints in
4887 that stopping scenario. Having gdbserver itself handle the fast
4888 tracepoint gives the user a consistent view of when fast or trap
4889 tracepoints are collected, compared to an alternative where only
4890 trap tracepoints are collected on stop, and fast tracepoints on
4891 resume. When a fast tracepoint is being processed by gdbserver,
4892 it is always the non-compiled condition expression that is
4893 used. */
4894 #ifdef IN_PROCESS_AGENT
4895 if (tpoint->compiled_cond)
4897 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4898 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4900 else
4901 #endif
4903 struct eval_agent_expr_context ax_ctx;
4905 ax_ctx.regcache = get_context_regcache (ctx);
4906 ax_ctx.tframe = NULL;
4907 ax_ctx.tpoint = tpoint;
4909 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4911 if (err != expr_eval_no_error)
4913 record_tracepoint_error (tpoint, "condition", err);
4914 /* The error case must return false. */
4915 return 0;
4918 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4919 tpoint->number, paddress (tpoint->address),
4920 pulongest (value));
4921 return (value ? 1 : 0);
4924 /* Do memory copies for bytecodes. */
4925 /* Do the recording of memory blocks for actions and bytecodes. */
4928 agent_mem_read (struct eval_agent_expr_context *ctx,
4929 unsigned char *to, CORE_ADDR from, ULONGEST len)
4931 unsigned char *mspace;
4932 ULONGEST remaining = len;
4933 unsigned short blocklen;
4935 /* If a 'to' buffer is specified, use it. */
4936 if (to != NULL)
4938 read_inferior_memory (from, to, len);
4939 return 0;
4942 /* Otherwise, create a new memory block in the trace buffer. */
4943 while (remaining > 0)
4945 size_t sp;
4947 blocklen = (remaining > 65535 ? 65535 : remaining);
4948 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4949 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4950 if (mspace == NULL)
4951 return 1;
4952 /* Identify block as a memory block. */
4953 *mspace = 'M';
4954 ++mspace;
4955 /* Record address and size. */
4956 memcpy (mspace, &from, sizeof (from));
4957 mspace += sizeof (from);
4958 memcpy (mspace, &blocklen, sizeof (blocklen));
4959 mspace += sizeof (blocklen);
4960 /* Record the memory block proper. */
4961 read_inferior_memory (from, mspace, blocklen);
4962 trace_debug ("%d bytes recorded", blocklen);
4963 remaining -= blocklen;
4964 from += blocklen;
4966 return 0;
4970 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4971 unsigned char *to, CORE_ADDR from, ULONGEST len)
4973 unsigned char *buf, *mspace;
4974 ULONGEST remaining = len;
4975 unsigned short blocklen, i;
4977 /* To save a bit of space, block lengths are 16-bit, so break large
4978 requests into multiple blocks. Bordering on overkill for strings,
4979 but it could happen that someone specifies a large max length. */
4980 while (remaining > 0)
4982 size_t sp;
4984 blocklen = (remaining > 65535 ? 65535 : remaining);
4985 /* We want working space to accumulate nonzero bytes, since
4986 traceframes must have a predecided size (otherwise it gets
4987 harder to wrap correctly for the circular case, etc). */
4988 buf = (unsigned char *) xmalloc (blocklen + 1);
4989 for (i = 0; i < blocklen; ++i)
4991 /* Read the string one byte at a time, in case the string is
4992 at the end of a valid memory area - we don't want a
4993 correctly-terminated string to engender segvio
4994 complaints. */
4995 read_inferior_memory (from + i, buf + i, 1);
4997 if (buf[i] == '\0')
4999 blocklen = i + 1;
5000 /* Make sure outer loop stops now too. */
5001 remaining = blocklen;
5002 break;
5005 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
5006 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
5007 if (mspace == NULL)
5009 xfree (buf);
5010 return 1;
5012 /* Identify block as a memory block. */
5013 *mspace = 'M';
5014 ++mspace;
5015 /* Record address and size. */
5016 memcpy ((void *) mspace, (void *) &from, sizeof (from));
5017 mspace += sizeof (from);
5018 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
5019 mspace += sizeof (blocklen);
5020 /* Copy the string contents. */
5021 memcpy ((void *) mspace, (void *) buf, blocklen);
5022 remaining -= blocklen;
5023 from += blocklen;
5024 xfree (buf);
5026 return 0;
5029 /* Record the value of a trace state variable. */
5032 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
5034 unsigned char *vspace;
5035 LONGEST val;
5037 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
5038 1 + sizeof (n) + sizeof (LONGEST));
5039 if (vspace == NULL)
5040 return 1;
5041 /* Identify block as a variable. */
5042 *vspace = 'V';
5043 /* Record variable's number and value. */
5044 memcpy (vspace + 1, &n, sizeof (n));
5045 val = get_trace_state_variable_value (n);
5046 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
5047 trace_debug ("Variable %d recorded", n);
5048 return 0;
5051 #ifndef IN_PROCESS_AGENT
5053 /* Callback for traceframe_walk_blocks, used to find a given block
5054 type in a traceframe. */
5056 static int
5057 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
5059 char *wantedp = (char *) data;
5061 if (*wantedp == blocktype)
5062 return 1;
5064 return 0;
5067 /* Walk over all traceframe blocks of the traceframe buffer starting
5068 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
5069 block found, passing in DATA unmodified. If CALLBACK returns true,
5070 this returns a pointer to where the block is found. Returns NULL
5071 if no callback call returned true, indicating that all blocks have
5072 been walked. */
5074 static unsigned char *
5075 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
5076 int tfnum,
5077 int (*callback) (char blocktype,
5078 unsigned char *dataptr,
5079 void *data),
5080 void *data)
5082 unsigned char *dataptr;
5084 if (datasize == 0)
5086 trace_debug ("traceframe %d has no data", tfnum);
5087 return NULL;
5090 /* Iterate through a traceframe's blocks, looking for a block of the
5091 requested type. */
5092 for (dataptr = database;
5093 dataptr < database + datasize;
5094 /* nothing */)
5096 char blocktype;
5097 unsigned short mlen;
5099 if (dataptr == trace_buffer_wrap)
5101 /* Adjust to reflect wrapping part of the frame around to
5102 the beginning. */
5103 datasize = dataptr - database;
5104 dataptr = database = trace_buffer_lo;
5107 blocktype = *dataptr++;
5109 if ((*callback) (blocktype, dataptr, data))
5110 return dataptr;
5112 switch (blocktype)
5114 case 'R':
5115 /* Skip over the registers block. */
5116 dataptr += current_target_desc ()->registers_size;
5117 break;
5118 case 'M':
5119 /* Skip over the memory block. */
5120 dataptr += sizeof (CORE_ADDR);
5121 memcpy (&mlen, dataptr, sizeof (mlen));
5122 dataptr += (sizeof (mlen) + mlen);
5123 break;
5124 case 'V':
5125 /* Skip over the TSV block. */
5126 dataptr += (sizeof (int) + sizeof (LONGEST));
5127 break;
5128 case 'S':
5129 /* Skip over the static trace data block. */
5130 memcpy (&mlen, dataptr, sizeof (mlen));
5131 dataptr += (sizeof (mlen) + mlen);
5132 break;
5133 default:
5134 trace_debug ("traceframe %d has unknown block type 0x%x",
5135 tfnum, blocktype);
5136 return NULL;
5140 return NULL;
5143 /* Look for the block of type TYPE_WANTED in the traceframe starting
5144 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
5145 number. */
5147 static unsigned char *
5148 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
5149 int tfnum, char type_wanted)
5151 return traceframe_walk_blocks (database, datasize, tfnum,
5152 match_blocktype, &type_wanted);
5155 static unsigned char *
5156 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
5158 unsigned char *regblock;
5160 regblock = traceframe_find_block_type (tframe->data,
5161 tframe->data_size,
5162 tfnum, 'R');
5164 if (regblock == NULL)
5165 trace_debug ("traceframe %d has no register data", tfnum);
5167 return regblock;
5170 /* Get registers from a traceframe. */
5173 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
5175 unsigned char *dataptr;
5176 struct tracepoint *tpoint;
5177 struct traceframe *tframe;
5179 tframe = find_traceframe (tfnum);
5181 if (tframe == NULL)
5183 trace_debug ("traceframe %d not found", tfnum);
5184 return 1;
5187 dataptr = traceframe_find_regblock (tframe, tfnum);
5188 if (dataptr == NULL)
5190 /* Mark registers unavailable. */
5191 supply_regblock (regcache, NULL);
5193 /* We can generally guess at a PC, although this will be
5194 misleading for while-stepping frames and multi-location
5195 tracepoints. */
5196 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
5197 if (tpoint != NULL)
5198 regcache_write_pc (regcache, tpoint->address);
5200 else
5201 supply_regblock (regcache, dataptr);
5203 return 0;
5206 static CORE_ADDR
5207 traceframe_get_pc (struct traceframe *tframe)
5209 struct regcache regcache;
5210 unsigned char *dataptr;
5211 const struct target_desc *tdesc = current_target_desc ();
5213 dataptr = traceframe_find_regblock (tframe, -1);
5214 if (dataptr == NULL)
5215 return 0;
5217 init_register_cache (&regcache, tdesc, dataptr);
5218 return regcache_read_pc (&regcache);
5221 /* Read a requested block of memory from a trace frame. */
5224 traceframe_read_mem (int tfnum, CORE_ADDR addr,
5225 unsigned char *buf, ULONGEST length,
5226 ULONGEST *nbytes)
5228 struct traceframe *tframe;
5229 unsigned char *database, *dataptr;
5230 unsigned int datasize;
5231 CORE_ADDR maddr;
5232 unsigned short mlen;
5234 trace_debug ("traceframe_read_mem");
5236 tframe = find_traceframe (tfnum);
5238 if (!tframe)
5240 trace_debug ("traceframe %d not found", tfnum);
5241 return 1;
5244 datasize = tframe->data_size;
5245 database = dataptr = &tframe->data[0];
5247 /* Iterate through a traceframe's blocks, looking for memory. */
5248 while ((dataptr = traceframe_find_block_type (dataptr,
5249 datasize
5250 - (dataptr - database),
5251 tfnum, 'M')) != NULL)
5253 memcpy (&maddr, dataptr, sizeof (maddr));
5254 dataptr += sizeof (maddr);
5255 memcpy (&mlen, dataptr, sizeof (mlen));
5256 dataptr += sizeof (mlen);
5257 trace_debug ("traceframe %d has %d bytes at %s",
5258 tfnum, mlen, paddress (maddr));
5260 /* If the block includes the first part of the desired range,
5261 return as much it has; GDB will re-request the remainder,
5262 which might be in a different block of this trace frame. */
5263 if (maddr <= addr && addr < (maddr + mlen))
5265 ULONGEST amt = (maddr + mlen) - addr;
5266 if (amt > length)
5267 amt = length;
5269 memcpy (buf, dataptr + (addr - maddr), amt);
5270 *nbytes = amt;
5271 return 0;
5274 /* Skip over this block. */
5275 dataptr += mlen;
5278 trace_debug ("traceframe %d has no memory data for the desired region",
5279 tfnum);
5281 *nbytes = 0;
5282 return 0;
5285 static int
5286 traceframe_read_tsv (int tsvnum, LONGEST *val)
5288 client_state &cs = get_client_state ();
5289 int tfnum;
5290 struct traceframe *tframe;
5291 unsigned char *database, *dataptr;
5292 unsigned int datasize;
5293 int vnum;
5294 int found = 0;
5296 trace_debug ("traceframe_read_tsv");
5298 tfnum = cs.current_traceframe;
5300 if (tfnum < 0)
5302 trace_debug ("no current traceframe");
5303 return 1;
5306 tframe = find_traceframe (tfnum);
5308 if (tframe == NULL)
5310 trace_debug ("traceframe %d not found", tfnum);
5311 return 1;
5314 datasize = tframe->data_size;
5315 database = dataptr = &tframe->data[0];
5317 /* Iterate through a traceframe's blocks, looking for the last
5318 matched tsv. */
5319 while ((dataptr = traceframe_find_block_type (dataptr,
5320 datasize
5321 - (dataptr - database),
5322 tfnum, 'V')) != NULL)
5324 memcpy (&vnum, dataptr, sizeof (vnum));
5325 dataptr += sizeof (vnum);
5327 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
5329 /* Check that this is the variable we want. */
5330 if (tsvnum == vnum)
5332 memcpy (val, dataptr, sizeof (*val));
5333 found = 1;
5336 /* Skip over this block. */
5337 dataptr += sizeof (LONGEST);
5340 if (!found)
5341 trace_debug ("traceframe %d has no data for variable %d",
5342 tfnum, tsvnum);
5343 return !found;
5346 /* Read a requested block of static tracepoint data from a trace
5347 frame. */
5350 traceframe_read_sdata (int tfnum, ULONGEST offset,
5351 unsigned char *buf, ULONGEST length,
5352 ULONGEST *nbytes)
5354 struct traceframe *tframe;
5355 unsigned char *database, *dataptr;
5356 unsigned int datasize;
5357 unsigned short mlen;
5359 trace_debug ("traceframe_read_sdata");
5361 tframe = find_traceframe (tfnum);
5363 if (!tframe)
5365 trace_debug ("traceframe %d not found", tfnum);
5366 return 1;
5369 datasize = tframe->data_size;
5370 database = &tframe->data[0];
5372 /* Iterate through a traceframe's blocks, looking for static
5373 tracepoint data. */
5374 dataptr = traceframe_find_block_type (database, datasize,
5375 tfnum, 'S');
5376 if (dataptr != NULL)
5378 memcpy (&mlen, dataptr, sizeof (mlen));
5379 dataptr += sizeof (mlen);
5380 if (offset < mlen)
5382 if (offset + length > mlen)
5383 length = mlen - offset;
5385 memcpy (buf, dataptr, length);
5386 *nbytes = length;
5388 else
5389 *nbytes = 0;
5390 return 0;
5393 trace_debug ("traceframe %d has no static trace data", tfnum);
5395 *nbytes = 0;
5396 return 0;
5399 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
5400 object. DATA is pointer to a struct buffer holding the
5401 traceframe-info object being built. */
5403 static int
5404 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
5406 struct buffer *buffer = (struct buffer *) data;
5408 switch (blocktype)
5410 case 'M':
5412 unsigned short mlen;
5413 CORE_ADDR maddr;
5415 memcpy (&maddr, dataptr, sizeof (maddr));
5416 dataptr += sizeof (maddr);
5417 memcpy (&mlen, dataptr, sizeof (mlen));
5418 dataptr += sizeof (mlen);
5419 buffer_xml_printf (buffer,
5420 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
5421 paddress (maddr), phex_nz (mlen, sizeof (mlen)));
5422 break;
5424 case 'V':
5426 int vnum;
5428 memcpy (&vnum, dataptr, sizeof (vnum));
5429 buffer_xml_printf (buffer, "<tvar id=\"%d\"/>\n", vnum);
5430 break;
5432 case 'R':
5433 case 'S':
5435 break;
5437 default:
5438 warning ("Unhandled trace block type (%d) '%c ' "
5439 "while building trace frame info.",
5440 blocktype, blocktype);
5441 break;
5444 return 0;
5447 /* Build a traceframe-info object for traceframe number TFNUM into
5448 BUFFER. */
5451 traceframe_read_info (int tfnum, struct buffer *buffer)
5453 struct traceframe *tframe;
5455 trace_debug ("traceframe_read_info");
5457 tframe = find_traceframe (tfnum);
5459 if (!tframe)
5461 trace_debug ("traceframe %d not found", tfnum);
5462 return 1;
5465 buffer_grow_str (buffer, "<traceframe-info>\n");
5466 traceframe_walk_blocks (tframe->data, tframe->data_size,
5467 tfnum, build_traceframe_info_xml, buffer);
5468 buffer_grow_str0 (buffer, "</traceframe-info>\n");
5469 return 0;
5472 /* Return the first fast tracepoint whose jump pad contains PC. */
5474 static struct tracepoint *
5475 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5477 struct tracepoint *tpoint;
5479 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5480 if (tpoint->type == fast_tracepoint)
5481 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5482 return tpoint;
5484 return NULL;
5487 /* Return the first fast tracepoint whose trampoline contains PC. */
5489 static struct tracepoint *
5490 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5492 struct tracepoint *tpoint;
5494 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5496 if (tpoint->type == fast_tracepoint
5497 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5498 return tpoint;
5501 return NULL;
5504 /* Return GDBserver's tracepoint that matches the IP Agent's
5505 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5506 address space. */
5508 static struct tracepoint *
5509 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5511 struct tracepoint *tpoint;
5513 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5514 if (tpoint->type == fast_tracepoint)
5515 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5516 return tpoint;
5518 return NULL;
5521 #endif
5523 /* The type of the object that is used to synchronize fast tracepoint
5524 collection. */
5526 typedef struct collecting_t
5528 /* The fast tracepoint number currently collecting. */
5529 uintptr_t tpoint;
5531 /* A number that GDBserver can use to identify the thread that is
5532 presently holding the collect lock. This need not (and usually
5533 is not) the thread id, as getting the current thread ID usually
5534 requires a system call, which we want to avoid like the plague.
5535 Usually this is thread's TCB, found in the TLS (pseudo-)
5536 register, which is readable with a single insn on several
5537 architectures. */
5538 uintptr_t thread_area;
5539 } collecting_t;
5541 #ifndef IN_PROCESS_AGENT
5543 void
5544 force_unlock_trace_buffer (void)
5546 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5549 /* Check if the thread identified by THREAD_AREA which is stopped at
5550 STOP_PC, is presently locking the fast tracepoint collection, and
5551 if so, gather some status of said collection. Returns 0 if the
5552 thread isn't collecting or in the jump pad at all. 1, if in the
5553 jump pad (or within gdb_collect) and hasn't executed the adjusted
5554 original insn yet (can set a breakpoint there and run to it). 2,
5555 if presently executing the adjusted original insn --- in which
5556 case, if we want to move the thread out of the jump pad, we need to
5557 single-step it until this function returns 0. */
5559 fast_tpoint_collect_result
5560 fast_tracepoint_collecting (CORE_ADDR thread_area,
5561 CORE_ADDR stop_pc,
5562 struct fast_tpoint_collect_status *status)
5564 CORE_ADDR ipa_collecting;
5565 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5566 CORE_ADDR ipa_gdb_trampoline_buffer;
5567 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5568 struct tracepoint *tpoint;
5569 int needs_breakpoint;
5571 /* The thread THREAD_AREA is either:
5573 0. not collecting at all, not within the jump pad, or within
5574 gdb_collect or one of its callees.
5576 1. in the jump pad and haven't reached gdb_collect
5578 2. within gdb_collect (out of the jump pad) (collect is set)
5580 3. we're in the jump pad, after gdb_collect having returned,
5581 possibly executing the adjusted insns.
5583 For cases 1 and 3, `collecting' may or not be set. The jump pad
5584 doesn't have any complicated jump logic, so we can tell if the
5585 thread is executing the adjust original insn or not by just
5586 matching STOP_PC with known jump pad addresses. If we it isn't
5587 yet executing the original insn, set a breakpoint there, and let
5588 the thread run to it, so to quickly step over a possible (many
5589 insns) gdb_collect call. Otherwise, or when the breakpoint is
5590 hit, only a few (small number of) insns are left to be executed
5591 in the jump pad. Single-step the thread until it leaves the
5592 jump pad. */
5594 again:
5595 tpoint = NULL;
5596 needs_breakpoint = 0;
5597 trace_debug ("fast_tracepoint_collecting");
5599 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5600 &ipa_gdb_jump_pad_buffer))
5602 internal_error (__FILE__, __LINE__,
5603 "error extracting `gdb_jump_pad_buffer'");
5605 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5606 &ipa_gdb_jump_pad_buffer_end))
5608 internal_error (__FILE__, __LINE__,
5609 "error extracting `gdb_jump_pad_buffer_end'");
5612 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5613 &ipa_gdb_trampoline_buffer))
5615 internal_error (__FILE__, __LINE__,
5616 "error extracting `gdb_trampoline_buffer'");
5618 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5619 &ipa_gdb_trampoline_buffer_end))
5621 internal_error (__FILE__, __LINE__,
5622 "error extracting `gdb_trampoline_buffer_end'");
5625 if (ipa_gdb_jump_pad_buffer <= stop_pc
5626 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5628 /* We can tell which tracepoint(s) the thread is collecting by
5629 matching the jump pad address back to the tracepoint. */
5630 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5631 if (tpoint == NULL)
5633 warning ("in jump pad, but no matching tpoint?");
5634 return fast_tpoint_collect_result::not_collecting;
5636 else
5638 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5639 "adj_insn(%s, %s)",
5640 tpoint->number, paddress (tpoint->address),
5641 paddress (tpoint->jump_pad),
5642 paddress (tpoint->jump_pad_end),
5643 paddress (tpoint->adjusted_insn_addr),
5644 paddress (tpoint->adjusted_insn_addr_end));
5647 /* Definitely in the jump pad. May or may not need
5648 fast-exit-jump-pad breakpoint. */
5649 if (tpoint->jump_pad <= stop_pc
5650 && stop_pc < tpoint->adjusted_insn_addr)
5651 needs_breakpoint = 1;
5653 else if (ipa_gdb_trampoline_buffer <= stop_pc
5654 && stop_pc < ipa_gdb_trampoline_buffer_end)
5656 /* We can tell which tracepoint(s) the thread is collecting by
5657 matching the trampoline address back to the tracepoint. */
5658 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5659 if (tpoint == NULL)
5661 warning ("in trampoline, but no matching tpoint?");
5662 return fast_tpoint_collect_result::not_collecting;
5664 else
5666 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5667 tpoint->number, paddress (tpoint->address),
5668 paddress (tpoint->trampoline),
5669 paddress (tpoint->trampoline_end));
5672 /* Have not reached jump pad yet, but treat the trampoline as a
5673 part of the jump pad that is before the adjusted original
5674 instruction. */
5675 needs_breakpoint = 1;
5677 else
5679 collecting_t ipa_collecting_obj;
5681 /* If `collecting' is set/locked, then the THREAD_AREA thread
5682 may or not be the one holding the lock. We have to read the
5683 lock to find out. */
5685 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5686 &ipa_collecting))
5688 trace_debug ("fast_tracepoint_collecting:"
5689 " failed reading 'collecting' in the inferior");
5690 return fast_tpoint_collect_result::not_collecting;
5693 if (!ipa_collecting)
5695 trace_debug ("fast_tracepoint_collecting: not collecting"
5696 " (and nobody is).");
5697 return fast_tpoint_collect_result::not_collecting;
5700 /* Some thread is collecting. Check which. */
5701 if (read_inferior_memory (ipa_collecting,
5702 (unsigned char *) &ipa_collecting_obj,
5703 sizeof (ipa_collecting_obj)) != 0)
5704 goto again;
5706 if (ipa_collecting_obj.thread_area != thread_area)
5708 trace_debug ("fast_tracepoint_collecting: not collecting "
5709 "(another thread is)");
5710 return fast_tpoint_collect_result::not_collecting;
5713 tpoint
5714 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5715 if (tpoint == NULL)
5717 warning ("fast_tracepoint_collecting: collecting, "
5718 "but tpoint %s not found?",
5719 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5720 return fast_tpoint_collect_result::not_collecting;
5723 /* The thread is within `gdb_collect', skip over the rest of
5724 fast tracepoint collection quickly using a breakpoint. */
5725 needs_breakpoint = 1;
5728 /* The caller wants a bit of status detail. */
5729 if (status != NULL)
5731 status->tpoint_num = tpoint->number;
5732 status->tpoint_addr = tpoint->address;
5733 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5734 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5737 if (needs_breakpoint)
5739 /* Hasn't executed the original instruction yet. Set breakpoint
5740 there, and wait till it's hit, then single-step until exiting
5741 the jump pad. */
5743 trace_debug ("\
5744 fast_tracepoint_collecting, returning continue-until-break at %s",
5745 paddress (tpoint->adjusted_insn_addr));
5747 return fast_tpoint_collect_result::before_insn; /* continue */
5749 else
5751 /* Just single-step until exiting the jump pad. */
5753 trace_debug ("fast_tracepoint_collecting, returning "
5754 "need-single-step (%s-%s)",
5755 paddress (tpoint->adjusted_insn_addr),
5756 paddress (tpoint->adjusted_insn_addr_end));
5758 return fast_tpoint_collect_result::at_insn; /* single-step */
5762 #endif
5764 #ifdef IN_PROCESS_AGENT
5766 /* The global fast tracepoint collect lock. Points to a collecting_t
5767 object built on the stack by the jump pad, if presently locked;
5768 NULL if it isn't locked. Note that this lock *must* be set while
5769 executing any *function other than the jump pad. See
5770 fast_tracepoint_collecting. */
5771 EXTERN_C_PUSH
5772 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5773 EXTERN_C_POP
5775 /* This is needed for -Wmissing-declarations. */
5776 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5777 unsigned char *regs);
5779 /* This routine, called from the jump pad (in asm) is designed to be
5780 called from the jump pads of fast tracepoints, thus it is on the
5781 critical path. */
5783 IP_AGENT_EXPORT_FUNC void
5784 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5786 struct fast_tracepoint_ctx ctx;
5787 const struct target_desc *ipa_tdesc;
5789 /* Don't do anything until the trace run is completely set up. */
5790 if (!tracing)
5791 return;
5793 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5794 ctx.base.type = fast_tracepoint;
5795 ctx.regs = regs;
5796 ctx.regcache_initted = 0;
5797 /* Wrap the regblock in a register cache (in the stack, we don't
5798 want to malloc here). */
5799 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5800 if (ctx.regspace == NULL)
5802 trace_debug ("Trace buffer block allocation failed, skipping");
5803 return;
5806 for (ctx.tpoint = tpoint;
5807 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5808 ctx.tpoint = ctx.tpoint->next)
5810 if (!ctx.tpoint->enabled)
5811 continue;
5813 /* Multiple tracepoints of different types, such as fast tracepoint and
5814 static tracepoint, can be set at the same address. */
5815 if (ctx.tpoint->type != tpoint->type)
5816 continue;
5818 /* Test the condition if present, and collect if true. */
5819 if (ctx.tpoint->cond == NULL
5820 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5821 ctx.tpoint))
5823 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5824 ctx.tpoint->address, ctx.tpoint);
5826 /* Note that this will cause original insns to be written back
5827 to where we jumped from, but that's OK because we're jumping
5828 back to the next whole instruction. This will go badly if
5829 instruction restoration is not atomic though. */
5830 if (stopping_tracepoint
5831 || trace_buffer_is_full
5832 || expr_eval_result != expr_eval_no_error)
5834 stop_tracing ();
5835 break;
5838 else
5840 /* If there was a condition and it evaluated to false, the only
5841 way we would stop tracing is if there was an error during
5842 condition expression evaluation. */
5843 if (expr_eval_result != expr_eval_no_error)
5845 stop_tracing ();
5846 break;
5852 /* These global variables points to the corresponding functions. This is
5853 necessary on powerpc64, where asking for function symbol address from gdb
5854 results in returning the actual code pointer, instead of the descriptor
5855 pointer. */
5857 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5858 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5859 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5860 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5862 EXTERN_C_PUSH
5863 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5864 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5865 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5866 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5867 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5868 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5869 EXTERN_C_POP
5871 #endif
5873 #ifndef IN_PROCESS_AGENT
5875 CORE_ADDR
5876 get_raw_reg_func_addr (void)
5878 CORE_ADDR res;
5879 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5881 error ("error extracting get_raw_reg_ptr");
5882 return 0;
5884 return res;
5887 CORE_ADDR
5888 get_get_tsv_func_addr (void)
5890 CORE_ADDR res;
5891 if (read_inferior_data_pointer (
5892 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5894 error ("error extracting get_trace_state_variable_value_ptr");
5895 return 0;
5897 return res;
5900 CORE_ADDR
5901 get_set_tsv_func_addr (void)
5903 CORE_ADDR res;
5904 if (read_inferior_data_pointer (
5905 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5907 error ("error extracting set_trace_state_variable_value_ptr");
5908 return 0;
5910 return res;
5913 static void
5914 compile_tracepoint_condition (struct tracepoint *tpoint,
5915 CORE_ADDR *jump_entry)
5917 CORE_ADDR entry_point = *jump_entry;
5918 enum eval_result_type err;
5920 trace_debug ("Starting condition compilation for tracepoint %d\n",
5921 tpoint->number);
5923 /* Initialize the global pointer to the code being built. */
5924 current_insn_ptr = *jump_entry;
5926 emit_prologue ();
5928 err = compile_bytecodes (tpoint->cond);
5930 if (err == expr_eval_no_error)
5932 emit_epilogue ();
5934 /* Record the beginning of the compiled code. */
5935 tpoint->compiled_cond = entry_point;
5937 trace_debug ("Condition compilation for tracepoint %d complete\n",
5938 tpoint->number);
5940 else
5942 /* Leave the unfinished code in situ, but don't point to it. */
5944 tpoint->compiled_cond = 0;
5946 trace_debug ("Condition compilation for tracepoint %d failed, "
5947 "error code %d",
5948 tpoint->number, err);
5951 /* Update the code pointer passed in. Note that we do this even if
5952 the compile fails, so that we can look at the partial results
5953 instead of letting them be overwritten. */
5954 *jump_entry = current_insn_ptr;
5956 /* Leave a gap, to aid dump decipherment. */
5957 *jump_entry += 16;
5960 /* The base pointer of the IPA's heap. This is the only memory the
5961 IPA is allowed to use. The IPA should _not_ call the inferior's
5962 `malloc' during operation. That'd be slow, and, most importantly,
5963 it may not be safe. We may be collecting a tracepoint in a signal
5964 handler, for example. */
5965 static CORE_ADDR target_tp_heap;
5967 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5968 to 8 bytes. */
5970 static CORE_ADDR
5971 target_malloc (ULONGEST size)
5973 CORE_ADDR ptr;
5975 if (target_tp_heap == 0)
5977 /* We have the pointer *address*, need what it points to. */
5978 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5979 &target_tp_heap))
5981 internal_error (__FILE__, __LINE__,
5982 "couldn't get target heap head pointer");
5986 ptr = target_tp_heap;
5987 target_tp_heap += size;
5989 /* Pad to 8-byte alignment. */
5990 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5992 return ptr;
5995 static CORE_ADDR
5996 download_agent_expr (struct agent_expr *expr)
5998 CORE_ADDR expr_addr;
5999 CORE_ADDR expr_bytes;
6001 expr_addr = target_malloc (sizeof (*expr));
6002 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
6004 expr_bytes = target_malloc (expr->length);
6005 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
6006 expr_bytes);
6007 target_write_memory (expr_bytes, expr->bytes, expr->length);
6009 return expr_addr;
6012 /* Align V up to N bits. */
6013 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
6015 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
6017 static void
6018 download_tracepoint_1 (struct tracepoint *tpoint)
6020 struct tracepoint target_tracepoint;
6021 CORE_ADDR tpptr = 0;
6023 gdb_assert (tpoint->type == fast_tracepoint
6024 || tpoint->type == static_tracepoint);
6026 if (tpoint->cond != NULL && target_emit_ops () != NULL)
6028 CORE_ADDR jentry, jump_entry;
6030 jentry = jump_entry = get_jump_space_head ();
6032 if (tpoint->cond != NULL)
6034 /* Pad to 8-byte alignment. (needed?) */
6035 /* Actually this should be left for the target to
6036 decide. */
6037 jentry = UALIGN (jentry, 8);
6039 compile_tracepoint_condition (tpoint, &jentry);
6042 /* Pad to 8-byte alignment. */
6043 jentry = UALIGN (jentry, 8);
6044 claim_jump_space (jentry - jump_entry);
6047 target_tracepoint = *tpoint;
6049 tpptr = target_malloc (sizeof (*tpoint));
6050 tpoint->obj_addr_on_target = tpptr;
6052 /* Write the whole object. We'll fix up its pointers in a bit.
6053 Assume no next for now. This is fixed up above on the next
6054 iteration, if there's any. */
6055 target_tracepoint.next = NULL;
6056 /* Need to clear this here too, since we're downloading the
6057 tracepoints before clearing our own copy. */
6058 target_tracepoint.hit_count = 0;
6060 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
6061 sizeof (target_tracepoint));
6063 if (tpoint->cond)
6064 write_inferior_data_pointer (tpptr
6065 + offsetof (struct tracepoint, cond),
6066 download_agent_expr (tpoint->cond));
6068 if (tpoint->numactions)
6070 int i;
6071 CORE_ADDR actions_array;
6073 /* The pointers array. */
6074 actions_array
6075 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
6076 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
6077 actions),
6078 actions_array);
6080 /* Now for each pointer, download the action. */
6081 for (i = 0; i < tpoint->numactions; i++)
6083 struct tracepoint_action *action = tpoint->actions[i];
6084 CORE_ADDR ipa_action = tracepoint_action_download (action);
6086 if (ipa_action != 0)
6087 write_inferior_data_pointer (actions_array
6088 + i * sizeof (*tpoint->actions),
6089 ipa_action);
6094 #define IPA_PROTO_FAST_TRACE_FLAG 0
6095 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
6096 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
6097 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
6098 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
6100 /* Send a command to agent to download and install tracepoint TPOINT. */
6102 static int
6103 tracepoint_send_agent (struct tracepoint *tpoint)
6105 char buf[IPA_CMD_BUF_SIZE];
6106 char *p;
6107 int i, ret;
6109 p = buf;
6110 strcpy (p, "FastTrace:");
6111 p += 10;
6113 COPY_FIELD_TO_BUF (p, tpoint, number);
6114 COPY_FIELD_TO_BUF (p, tpoint, address);
6115 COPY_FIELD_TO_BUF (p, tpoint, type);
6116 COPY_FIELD_TO_BUF (p, tpoint, enabled);
6117 COPY_FIELD_TO_BUF (p, tpoint, step_count);
6118 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
6119 COPY_FIELD_TO_BUF (p, tpoint, numactions);
6120 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
6121 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
6122 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
6123 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
6125 /* condition */
6126 p = agent_expr_send (p, tpoint->cond);
6128 /* tracepoint_action */
6129 for (i = 0; i < tpoint->numactions; i++)
6131 struct tracepoint_action *action = tpoint->actions[i];
6133 p[0] = action->type;
6134 p = tracepoint_action_send (&p[1], action);
6137 get_jump_space_head ();
6138 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
6139 agent can use jump pad from it. */
6140 if (tpoint->type == fast_tracepoint)
6142 memcpy (p, &gdb_jump_pad_head, 8);
6143 p += 8;
6146 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
6147 if (ret)
6148 return ret;
6150 if (!startswith (buf, "OK"))
6151 return 1;
6153 /* The value of tracepoint's target address is stored in BUF. */
6154 memcpy (&tpoint->obj_addr_on_target,
6155 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
6157 if (tpoint->type == fast_tracepoint)
6159 unsigned char *insn
6160 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
6161 int fjump_size;
6163 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
6164 (unsigned int) tpoint->obj_addr_on_target,
6165 (unsigned int) gdb_jump_pad_head);
6167 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
6169 /* This has been done in agent. We should also set up record for it. */
6170 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
6171 /* Wire it in. */
6172 tpoint->handle
6173 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
6176 return 0;
6179 static void
6180 download_tracepoint (struct tracepoint *tpoint)
6182 struct tracepoint *tp, *tp_prev;
6184 if (tpoint->type != fast_tracepoint
6185 && tpoint->type != static_tracepoint)
6186 return;
6188 download_tracepoint_1 (tpoint);
6190 /* Find the previous entry of TPOINT, which is fast tracepoint or
6191 static tracepoint. */
6192 tp_prev = NULL;
6193 for (tp = tracepoints; tp != tpoint; tp = tp->next)
6195 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
6196 tp_prev = tp;
6199 if (tp_prev)
6201 CORE_ADDR tp_prev_target_next_addr;
6203 /* Insert TPOINT after TP_PREV in IPA. */
6204 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
6205 + offsetof (struct tracepoint, next),
6206 &tp_prev_target_next_addr))
6208 internal_error (__FILE__, __LINE__,
6209 "error reading `tp_prev->next'");
6212 /* tpoint->next = tp_prev->next */
6213 write_inferior_data_pointer (tpoint->obj_addr_on_target
6214 + offsetof (struct tracepoint, next),
6215 tp_prev_target_next_addr);
6216 /* tp_prev->next = tpoint */
6217 write_inferior_data_pointer (tp_prev->obj_addr_on_target
6218 + offsetof (struct tracepoint, next),
6219 tpoint->obj_addr_on_target);
6221 else
6222 /* First object in list, set the head pointer in the
6223 inferior. */
6224 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
6225 tpoint->obj_addr_on_target);
6229 static void
6230 download_trace_state_variables (void)
6232 CORE_ADDR ptr = 0, prev_ptr = 0;
6233 struct trace_state_variable *tsv;
6235 /* Start out empty. */
6236 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
6238 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
6240 struct trace_state_variable target_tsv;
6242 /* TSV's with a getter have been initialized equally in both the
6243 inferior and GDBserver. Skip them. */
6244 if (tsv->getter != NULL)
6245 continue;
6247 target_tsv = *tsv;
6249 prev_ptr = ptr;
6250 ptr = target_malloc (sizeof (*tsv));
6252 if (tsv == trace_state_variables)
6254 /* First object in list, set the head pointer in the
6255 inferior. */
6257 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
6258 ptr);
6260 else
6262 write_inferior_data_pointer (prev_ptr
6263 + offsetof (struct trace_state_variable,
6264 next),
6265 ptr);
6268 /* Write the whole object. We'll fix up its pointers in a bit.
6269 Assume no next, fixup when needed. */
6270 target_tsv.next = NULL;
6272 target_write_memory (ptr, (unsigned char *) &target_tsv,
6273 sizeof (target_tsv));
6275 if (tsv->name != NULL)
6277 size_t size = strlen (tsv->name) + 1;
6278 CORE_ADDR name_addr = target_malloc (size);
6279 target_write_memory (name_addr,
6280 (unsigned char *) tsv->name, size);
6281 write_inferior_data_pointer (ptr
6282 + offsetof (struct trace_state_variable,
6283 name),
6284 name_addr);
6287 gdb_assert (tsv->getter == NULL);
6290 if (prev_ptr != 0)
6292 /* Fixup the next pointer in the last item in the list. */
6293 write_inferior_data_pointer (prev_ptr
6294 + offsetof (struct trace_state_variable,
6295 next), 0);
6299 /* Upload complete trace frames out of the IP Agent's trace buffer
6300 into GDBserver's trace buffer. This always uploads either all or
6301 no trace frames. This is the counter part of
6302 `trace_alloc_trace_buffer'. See its description of the atomic
6303 syncing mechanism. */
6305 static void
6306 upload_fast_traceframes (void)
6308 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
6309 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
6310 CORE_ADDR tf;
6311 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
6312 unsigned int curr_tbctrl_idx;
6313 unsigned int ipa_trace_buffer_ctrl_curr;
6314 unsigned int ipa_trace_buffer_ctrl_curr_old;
6315 CORE_ADDR ipa_trace_buffer_ctrl_addr;
6316 struct breakpoint *about_to_request_buffer_space_bkpt;
6317 CORE_ADDR ipa_trace_buffer_lo;
6318 CORE_ADDR ipa_trace_buffer_hi;
6320 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6321 &ipa_traceframe_read_count_racy))
6323 /* This will happen in most targets if the current thread is
6324 running. */
6325 return;
6328 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6329 &ipa_traceframe_write_count_racy))
6330 return;
6332 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
6333 ipa_traceframe_write_count_racy
6334 - ipa_traceframe_read_count_racy,
6335 ipa_traceframe_write_count_racy,
6336 ipa_traceframe_read_count_racy);
6338 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
6339 return;
6341 about_to_request_buffer_space_bkpt
6342 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
6343 NULL);
6345 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6346 &ipa_trace_buffer_ctrl_curr))
6347 return;
6349 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
6351 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
6354 unsigned int prev, counter;
6356 /* Update the token, with new counters, and the GDBserver stamp
6357 bit. Alway reuse the current TBC index. */
6358 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6359 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6361 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
6362 | (prev << 12)
6363 | counter
6364 | curr_tbctrl_idx);
6367 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6368 ipa_trace_buffer_ctrl_curr))
6369 return;
6371 trace_debug ("Lib: Committed %08x -> %08x",
6372 ipa_trace_buffer_ctrl_curr_old,
6373 ipa_trace_buffer_ctrl_curr);
6375 /* Re-read these, now that we've installed the
6376 `about_to_request_buffer_space' breakpoint/lock. A thread could
6377 have finished a traceframe between the last read of these
6378 counters and setting the breakpoint above. If we start
6379 uploading, we never want to leave this function with
6380 traceframe_read_count != 0, otherwise, GDBserver could end up
6381 incrementing the counter tokens more than once (due to event loop
6382 nesting), which would break the IP agent's "effective" detection
6383 (see trace_alloc_trace_buffer). */
6384 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6385 &ipa_traceframe_read_count))
6386 return;
6387 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6388 &ipa_traceframe_write_count))
6389 return;
6391 if (debug_threads)
6393 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
6394 ipa_traceframe_write_count - ipa_traceframe_read_count,
6395 ipa_traceframe_write_count, ipa_traceframe_read_count);
6397 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
6398 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
6399 trace_debug ("note that ipa_traceframe_count's parts changed");
6402 /* Get the address of the current TBC object (the IP agent has an
6403 array of 3 such objects). The index is stored in the TBC
6404 token. */
6405 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
6406 ipa_trace_buffer_ctrl_addr
6407 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
6409 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
6410 (unsigned char *) &ipa_trace_buffer_ctrl,
6411 sizeof (struct ipa_trace_buffer_control)))
6412 return;
6414 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
6415 &ipa_trace_buffer_lo))
6416 return;
6417 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
6418 &ipa_trace_buffer_hi))
6419 return;
6421 /* Offsets are easier to grok for debugging than raw addresses,
6422 especially for the small trace buffer sizes that are useful for
6423 testing. */
6424 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6425 "endfree=%d wrap=%d hi=%d",
6426 curr_tbctrl_idx,
6427 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6428 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6429 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6430 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6431 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6433 /* Note that the IPA's buffer is always circular. */
6435 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6437 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6438 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6440 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6441 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6442 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6443 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6444 : 0))
6446 tf = IPA_FIRST_TRACEFRAME ();
6448 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6450 struct tracepoint *tpoint;
6451 struct traceframe *tframe;
6452 unsigned char *block;
6453 struct traceframe ipa_tframe;
6455 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6456 offsetof (struct traceframe, data)))
6457 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6459 if (ipa_tframe.tpnum == 0)
6461 internal_error (__FILE__, __LINE__,
6462 "Uploading: No (more) fast traceframes, but"
6463 " ipa_traceframe_count == %u??\n",
6464 ipa_traceframe_write_count
6465 - ipa_traceframe_read_count);
6468 /* Note that this will be incorrect for multi-location
6469 tracepoints... */
6470 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6472 tframe = add_traceframe (tpoint);
6473 if (tframe == NULL)
6475 trace_buffer_is_full = 1;
6476 trace_debug ("Uploading: trace buffer is full");
6478 else
6480 /* Copy the whole set of blocks in one go for now. FIXME:
6481 split this in smaller blocks. */
6482 block = add_traceframe_block (tframe, tpoint,
6483 ipa_tframe.data_size);
6484 if (block != NULL)
6486 if (read_inferior_memory (tf
6487 + offsetof (struct traceframe, data),
6488 block, ipa_tframe.data_size))
6489 error ("Uploading: Couldn't read traceframe data at %s\n",
6490 paddress (tf + offsetof (struct traceframe, data)));
6493 trace_debug ("Uploading: traceframe didn't fit");
6494 finish_traceframe (tframe);
6497 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6499 /* If we freed the traceframe that wrapped around, go back
6500 to the non-wrap case. */
6501 if (tf < ipa_trace_buffer_ctrl.start)
6503 trace_debug ("Lib: Discarding past the wraparound");
6504 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6506 ipa_trace_buffer_ctrl.start = tf;
6507 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6508 ++ipa_traceframe_read_count;
6510 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6511 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6513 trace_debug ("Lib: buffer is fully empty. "
6514 "Trace buffer [%d] start=%d free=%d endfree=%d",
6515 curr_tbctrl_idx,
6516 (int) (ipa_trace_buffer_ctrl.start
6517 - ipa_trace_buffer_lo),
6518 (int) (ipa_trace_buffer_ctrl.free
6519 - ipa_trace_buffer_lo),
6520 (int) (ipa_trace_buffer_ctrl.end_free
6521 - ipa_trace_buffer_lo));
6523 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6524 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6525 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6526 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6529 trace_debug ("Uploaded a traceframe\n"
6530 "Lib: Trace buffer [%d] start=%d free=%d "
6531 "endfree=%d wrap=%d hi=%d",
6532 curr_tbctrl_idx,
6533 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6534 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6535 (int) (ipa_trace_buffer_ctrl.end_free
6536 - ipa_trace_buffer_lo),
6537 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6538 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6541 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6542 (unsigned char *) &ipa_trace_buffer_ctrl,
6543 sizeof (struct ipa_trace_buffer_control)))
6544 return;
6546 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6547 ipa_traceframe_read_count);
6549 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6551 target_pause_all (true);
6553 delete_breakpoint (about_to_request_buffer_space_bkpt);
6554 about_to_request_buffer_space_bkpt = NULL;
6556 target_unpause_all (true);
6558 if (trace_buffer_is_full)
6559 stop_tracing ();
6561 #endif
6563 #ifdef IN_PROCESS_AGENT
6565 IP_AGENT_EXPORT_VAR int ust_loaded;
6566 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6568 #ifdef HAVE_UST
6570 /* Static tracepoints. */
6572 /* UST puts a "struct tracepoint" in the global namespace, which
6573 conflicts with our tracepoint. Arguably, being a library, it
6574 shouldn't take ownership of such a generic name. We work around it
6575 here. */
6576 #define tracepoint ust_tracepoint
6577 #include <ust/ust.h>
6578 #undef tracepoint
6580 extern int serialize_to_text (char *outbuf, int bufsize,
6581 const char *fmt, va_list ap);
6583 #define GDB_PROBE_NAME "gdb"
6585 /* We dynamically search for the UST symbols instead of linking them
6586 in. This lets the user decide if the application uses static
6587 tracepoints, instead of always pulling libust.so in. This vector
6588 holds pointers to all functions we care about. */
6590 static struct
6592 int (*serialize_to_text) (char *outbuf, int bufsize,
6593 const char *fmt, va_list ap);
6595 int (*ltt_probe_register) (struct ltt_available_probe *pdata);
6596 int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
6598 int (*ltt_marker_connect) (const char *channel, const char *mname,
6599 const char *pname);
6600 int (*ltt_marker_disconnect) (const char *channel, const char *mname,
6601 const char *pname);
6603 void (*marker_iter_start) (struct marker_iter *iter);
6604 void (*marker_iter_next) (struct marker_iter *iter);
6605 void (*marker_iter_stop) (struct marker_iter *iter);
6606 void (*marker_iter_reset) (struct marker_iter *iter);
6607 } ust_ops;
6609 #include <dlfcn.h>
6611 /* Cast through typeof to catch incompatible API changes. Since UST
6612 only builds with gcc, we can freely use gcc extensions here
6613 too. */
6614 #define GET_UST_SYM(SYM) \
6615 do \
6617 if (ust_ops.SYM == NULL) \
6618 ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM); \
6619 if (ust_ops.SYM == NULL) \
6620 return 0; \
6621 } while (0)
6623 #define USTF(SYM) ust_ops.SYM
6625 /* Get pointers to all libust.so functions we care about. */
6627 static int
6628 dlsym_ust (void)
6630 GET_UST_SYM (serialize_to_text);
6632 GET_UST_SYM (ltt_probe_register);
6633 GET_UST_SYM (ltt_probe_unregister);
6634 GET_UST_SYM (ltt_marker_connect);
6635 GET_UST_SYM (ltt_marker_disconnect);
6637 GET_UST_SYM (marker_iter_start);
6638 GET_UST_SYM (marker_iter_next);
6639 GET_UST_SYM (marker_iter_stop);
6640 GET_UST_SYM (marker_iter_reset);
6642 ust_loaded = 1;
6643 return 1;
6646 /* Given an UST marker, return the matching gdb static tracepoint.
6647 The match is done by address. */
6649 static struct tracepoint *
6650 ust_marker_to_static_tracepoint (const struct marker *mdata)
6652 struct tracepoint *tpoint;
6654 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
6656 if (tpoint->type != static_tracepoint)
6657 continue;
6659 if (tpoint->address == (uintptr_t) mdata->location)
6660 return tpoint;
6663 return NULL;
6666 /* The probe function we install on lttng/ust markers. Whenever a
6667 probed ust marker is hit, this function is called. This is similar
6668 to gdb_collect, only for static tracepoints, instead of fast
6669 tracepoints. */
6671 static void
6672 gdb_probe (const struct marker *mdata, void *probe_private,
6673 struct registers *regs, void *call_private,
6674 const char *fmt, va_list *args)
6676 struct tracepoint *tpoint;
6677 struct static_tracepoint_ctx ctx;
6678 const struct target_desc *ipa_tdesc;
6680 /* Don't do anything until the trace run is completely set up. */
6681 if (!tracing)
6683 trace_debug ("gdb_probe: not tracing\n");
6684 return;
6687 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
6688 ctx.base.type = static_tracepoint;
6689 ctx.regcache_initted = 0;
6690 ctx.regs = regs;
6691 ctx.fmt = fmt;
6692 ctx.args = args;
6694 /* Wrap the regblock in a register cache (in the stack, we don't
6695 want to malloc here). */
6696 ctx.regspace = alloca (ipa_tdesc->registers_size);
6697 if (ctx.regspace == NULL)
6699 trace_debug ("Trace buffer block allocation failed, skipping");
6700 return;
6703 tpoint = ust_marker_to_static_tracepoint (mdata);
6704 if (tpoint == NULL)
6706 trace_debug ("gdb_probe: marker not known: "
6707 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6708 mdata->location, mdata->channel,
6709 mdata->name, mdata->format);
6710 return;
6713 if (!tpoint->enabled)
6715 trace_debug ("gdb_probe: tracepoint disabled");
6716 return;
6719 ctx.tpoint = tpoint;
6721 trace_debug ("gdb_probe: collecting marker: "
6722 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6723 mdata->location, mdata->channel,
6724 mdata->name, mdata->format);
6726 /* Test the condition if present, and collect if true. */
6727 if (tpoint->cond == NULL
6728 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6729 tpoint))
6731 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6732 tpoint->address, tpoint);
6734 if (stopping_tracepoint
6735 || trace_buffer_is_full
6736 || expr_eval_result != expr_eval_no_error)
6737 stop_tracing ();
6739 else
6741 /* If there was a condition and it evaluated to false, the only
6742 way we would stop tracing is if there was an error during
6743 condition expression evaluation. */
6744 if (expr_eval_result != expr_eval_no_error)
6745 stop_tracing ();
6749 /* Called if the gdb static tracepoint requested collecting "$_sdata",
6750 static tracepoint string data. This is a string passed to the
6751 tracing library by the user, at the time of the tracepoint marker
6752 call. E.g., in the UST marker call:
6754 trace_mark (ust, bar33, "str %s", "FOOBAZ");
6756 the collected data is "str FOOBAZ".
6759 static void
6760 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
6761 struct traceframe *tframe)
6763 struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
6764 unsigned char *bufspace;
6765 int size;
6766 va_list copy;
6767 unsigned short blocklen;
6769 if (umd == NULL)
6771 trace_debug ("Wanted to collect static trace data, "
6772 "but there's no static trace data");
6773 return;
6776 va_copy (copy, *umd->args);
6777 size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
6778 va_end (copy);
6780 trace_debug ("Want to collect ust data");
6782 /* 'S' + size + string */
6783 bufspace = add_traceframe_block (tframe, umd->tpoint,
6784 1 + sizeof (blocklen) + size + 1);
6785 if (bufspace == NULL)
6787 trace_debug ("Trace buffer block allocation failed, skipping");
6788 return;
6791 /* Identify a static trace data block. */
6792 *bufspace = 'S';
6794 blocklen = size + 1;
6795 memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
6797 va_copy (copy, *umd->args);
6798 USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
6799 size + 1, umd->fmt, copy);
6800 va_end (copy);
6802 trace_debug ("Storing static tracepoint data in regblock: %s",
6803 bufspace + 1 + sizeof (blocklen));
6806 /* The probe to register with lttng/ust. */
6807 static struct ltt_available_probe gdb_ust_probe =
6809 GDB_PROBE_NAME,
6810 NULL,
6811 gdb_probe,
6814 #endif /* HAVE_UST */
6815 #endif /* IN_PROCESS_AGENT */
6817 #ifndef IN_PROCESS_AGENT
6819 /* Ask the in-process agent to run a command. Since we don't want to
6820 have to handle the IPA hitting breakpoints while running the
6821 command, we pause all threads, remove all breakpoints, and then set
6822 the helper thread re-running. We communicate with the helper
6823 thread by means of direct memory xfering, and a socket for
6824 synchronization. */
6826 static int
6827 run_inferior_command (char *cmd, int len)
6829 int err = -1;
6830 int pid = current_ptid.pid ();
6832 trace_debug ("run_inferior_command: running: %s", cmd);
6834 target_pause_all (false);
6835 uninsert_all_breakpoints ();
6837 err = agent_run_command (pid, (const char *) cmd, len);
6839 reinsert_all_breakpoints ();
6840 target_unpause_all (false);
6842 return err;
6845 #else /* !IN_PROCESS_AGENT */
6847 #include <sys/socket.h>
6848 #include <sys/un.h>
6850 #ifndef UNIX_PATH_MAX
6851 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6852 #endif
6854 /* Where we put the socked used for synchronization. */
6855 #define SOCK_DIR P_tmpdir
6857 /* Thread ID of the helper thread. GDBserver reads this to know which
6858 is the help thread. This is an LWP id on Linux. */
6859 EXTERN_C_PUSH
6860 IP_AGENT_EXPORT_VAR int helper_thread_id;
6861 EXTERN_C_POP
6863 static int
6864 init_named_socket (const char *name)
6866 int result, fd;
6867 struct sockaddr_un addr;
6869 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6870 if (result == -1)
6872 warning ("socket creation failed: %s", safe_strerror (errno));
6873 return -1;
6876 addr.sun_family = AF_UNIX;
6878 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6880 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6881 return -1;
6884 strcpy (addr.sun_path, name);
6886 result = access (name, F_OK);
6887 if (result == 0)
6889 /* File exists. */
6890 result = unlink (name);
6891 if (result == -1)
6893 warning ("unlink failed: %s", safe_strerror (errno));
6894 close (fd);
6895 return -1;
6897 warning ("socket %s already exists; overwriting", name);
6900 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6901 if (result == -1)
6903 warning ("bind failed: %s", safe_strerror (errno));
6904 close (fd);
6905 return -1;
6908 result = listen (fd, 1);
6909 if (result == -1)
6911 warning ("listen: %s", safe_strerror (errno));
6912 close (fd);
6913 return -1;
6916 return fd;
6919 static char agent_socket_name[UNIX_PATH_MAX];
6921 static int
6922 gdb_agent_socket_init (void)
6924 int result, fd;
6926 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6927 SOCK_DIR, getpid ());
6928 if (result >= UNIX_PATH_MAX)
6930 trace_debug ("string overflow allocating socket name");
6931 return -1;
6934 fd = init_named_socket (agent_socket_name);
6935 if (fd < 0)
6936 warning ("Error initializing named socket (%s) for communication with the "
6937 "ust helper thread. Check that directory exists and that it "
6938 "is writable.", agent_socket_name);
6940 return fd;
6943 #ifdef HAVE_UST
6945 /* The next marker to be returned on a qTsSTM command. */
6946 static const struct marker *next_st;
6948 /* Returns the first known marker. */
6950 struct marker *
6951 first_marker (void)
6953 struct marker_iter iter;
6955 USTF(marker_iter_reset) (&iter);
6956 USTF(marker_iter_start) (&iter);
6958 return iter.marker;
6961 /* Returns the marker following M. */
6963 const struct marker *
6964 next_marker (const struct marker *m)
6966 struct marker_iter iter;
6968 USTF(marker_iter_reset) (&iter);
6969 USTF(marker_iter_start) (&iter);
6971 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
6973 if (iter.marker == m)
6975 USTF(marker_iter_next) (&iter);
6976 return iter.marker;
6980 return NULL;
6983 /* Return an hexstr version of the STR C string, fit for sending to
6984 GDB. */
6986 static char *
6987 cstr_to_hexstr (const char *str)
6989 int len = strlen (str);
6990 char *hexstr = xmalloc (len * 2 + 1);
6991 bin2hex ((gdb_byte *) str, hexstr, len);
6992 return hexstr;
6995 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
6996 packets. */
6998 static void
6999 response_ust_marker (char *packet, const struct marker *st)
7001 char *strid, *format, *tmp;
7003 next_st = next_marker (st);
7005 tmp = xmalloc (strlen (st->channel) + 1 +
7006 strlen (st->name) + 1);
7007 sprintf (tmp, "%s/%s", st->channel, st->name);
7009 strid = cstr_to_hexstr (tmp);
7010 free (tmp);
7012 format = cstr_to_hexstr (st->format);
7014 sprintf (packet, "m%s:%s:%s",
7015 paddress ((uintptr_t) st->location),
7016 strid,
7017 format);
7019 free (strid);
7020 free (format);
7023 /* Return the first static tracepoint, and initialize the state
7024 machine that will iterate through all the static tracepoints. */
7026 static void
7027 cmd_qtfstm (char *packet)
7029 trace_debug ("Returning first trace state variable definition");
7031 if (first_marker ())
7032 response_ust_marker (packet, first_marker ());
7033 else
7034 strcpy (packet, "l");
7037 /* Return additional trace state variable definitions. */
7039 static void
7040 cmd_qtsstm (char *packet)
7042 trace_debug ("Returning static tracepoint");
7044 if (next_st)
7045 response_ust_marker (packet, next_st);
7046 else
7047 strcpy (packet, "l");
7050 /* Disconnect the GDB probe from a marker at a given address. */
7052 static void
7053 unprobe_marker_at (char *packet)
7055 char *p = packet;
7056 ULONGEST address;
7057 struct marker_iter iter;
7059 p += sizeof ("unprobe_marker_at:") - 1;
7061 p = unpack_varlen_hex (p, &address);
7063 USTF(marker_iter_reset) (&iter);
7064 USTF(marker_iter_start) (&iter);
7065 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7066 if ((uintptr_t ) iter.marker->location == address)
7068 int result;
7070 result = USTF(ltt_marker_disconnect) (iter.marker->channel,
7071 iter.marker->name,
7072 GDB_PROBE_NAME);
7073 if (result < 0)
7074 warning ("could not disable marker %s/%s",
7075 iter.marker->channel, iter.marker->name);
7076 break;
7080 /* Connect the GDB probe to a marker at a given address. */
7082 static int
7083 probe_marker_at (char *packet)
7085 char *p = packet;
7086 ULONGEST address;
7087 struct marker_iter iter;
7088 struct marker *m;
7090 p += sizeof ("probe_marker_at:") - 1;
7092 p = unpack_varlen_hex (p, &address);
7094 USTF(marker_iter_reset) (&iter);
7096 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7097 m != NULL;
7098 USTF(marker_iter_next) (&iter), m = iter.marker)
7099 if ((uintptr_t ) m->location == address)
7101 int result;
7103 trace_debug ("found marker for address. "
7104 "ltt_marker_connect (marker = %s/%s)",
7105 m->channel, m->name);
7107 result = USTF(ltt_marker_connect) (m->channel, m->name,
7108 GDB_PROBE_NAME);
7109 if (result && result != -EEXIST)
7110 trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
7111 m->channel, m->name, -result);
7113 if (result < 0)
7115 sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
7116 m->channel, m->name);
7117 return -1;
7120 strcpy (packet, "OK");
7121 return 0;
7124 sprintf (packet, "E.no marker found at 0x%s", paddress (address));
7125 return -1;
7128 static int
7129 cmd_qtstmat (char *packet)
7131 char *p = packet;
7132 ULONGEST address;
7133 struct marker_iter iter;
7134 struct marker *m;
7136 p += sizeof ("qTSTMat:") - 1;
7138 p = unpack_varlen_hex (p, &address);
7140 USTF(marker_iter_reset) (&iter);
7142 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7143 m != NULL;
7144 USTF(marker_iter_next) (&iter), m = iter.marker)
7145 if ((uintptr_t ) m->location == address)
7147 response_ust_marker (packet, m);
7148 return 0;
7151 strcpy (packet, "l");
7152 return -1;
7155 static void
7156 gdb_ust_init (void)
7158 if (!dlsym_ust ())
7159 return;
7161 USTF(ltt_probe_register) (&gdb_ust_probe);
7164 #endif /* HAVE_UST */
7166 #include <sys/syscall.h>
7168 static void
7169 gdb_agent_remove_socket (void)
7171 unlink (agent_socket_name);
7174 /* Helper thread of agent. */
7176 static void *
7177 gdb_agent_helper_thread (void *arg)
7179 int listen_fd;
7181 atexit (gdb_agent_remove_socket);
7183 while (1)
7185 listen_fd = gdb_agent_socket_init ();
7187 if (helper_thread_id == 0)
7188 helper_thread_id = syscall (SYS_gettid);
7190 if (listen_fd == -1)
7192 warning ("could not create sync socket");
7193 break;
7196 while (1)
7198 socklen_t tmp;
7199 struct sockaddr_un sockaddr;
7200 int fd;
7201 char buf[1];
7202 int ret;
7203 int stop_loop = 0;
7205 tmp = sizeof (sockaddr);
7209 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
7211 /* It seems an ERESTARTSYS can escape out of accept. */
7212 while (fd == -512 || (fd == -1 && errno == EINTR));
7214 if (fd < 0)
7216 warning ("Accept returned %d, error: %s",
7217 fd, safe_strerror (errno));
7218 break;
7223 ret = read (fd, buf, 1);
7224 } while (ret == -1 && errno == EINTR);
7226 if (ret == -1)
7228 warning ("reading socket (fd=%d) failed with %s",
7229 fd, safe_strerror (errno));
7230 close (fd);
7231 break;
7234 if (cmd_buf[0])
7236 if (startswith (cmd_buf, "close"))
7238 stop_loop = 1;
7240 #ifdef HAVE_UST
7241 else if (strcmp ("qTfSTM", cmd_buf) == 0)
7243 cmd_qtfstm (cmd_buf);
7245 else if (strcmp ("qTsSTM", cmd_buf) == 0)
7247 cmd_qtsstm (cmd_buf);
7249 else if (startswith (cmd_buf, "unprobe_marker_at:"))
7251 unprobe_marker_at (cmd_buf);
7253 else if (startswith (cmd_buf, "probe_marker_at:"))
7255 probe_marker_at (cmd_buf);
7257 else if (startswith (cmd_buf, "qTSTMat:"))
7259 cmd_qtstmat (cmd_buf);
7261 #endif /* HAVE_UST */
7264 /* Fix compiler's warning: ignoring return value of 'write'. */
7265 ret = write (fd, buf, 1);
7266 close (fd);
7268 if (stop_loop)
7270 close (listen_fd);
7271 unlink (agent_socket_name);
7273 /* Sleep endlessly to wait the whole inferior stops. This
7274 thread can not exit because GDB or GDBserver may still need
7275 'current_thread' (representing this thread) to access
7276 inferior memory. Otherwise, this thread exits earlier than
7277 other threads, and 'current_thread' is set to NULL. */
7278 while (1)
7279 sleep (10);
7284 return NULL;
7287 #include <signal.h>
7288 #include <pthread.h>
7290 EXTERN_C_PUSH
7291 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
7292 EXTERN_C_POP
7294 static void
7295 gdb_agent_init (void)
7297 int res;
7298 pthread_t thread;
7299 sigset_t new_mask;
7300 sigset_t orig_mask;
7302 /* We want the helper thread to be as transparent as possible, so
7303 have it inherit an all-signals-blocked mask. */
7305 sigfillset (&new_mask);
7306 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
7307 if (res)
7308 perror_with_name ("pthread_sigmask (1)");
7310 res = pthread_create (&thread,
7311 NULL,
7312 gdb_agent_helper_thread,
7313 NULL);
7315 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
7316 if (res)
7317 perror_with_name ("pthread_sigmask (2)");
7319 while (helper_thread_id == 0)
7320 usleep (1);
7322 #ifdef HAVE_UST
7323 gdb_ust_init ();
7324 #endif
7327 #include <sys/mman.h>
7329 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
7330 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
7331 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
7332 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
7333 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
7334 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
7336 /* Record the result of getting buffer space for fast tracepoint
7337 trampolines. Any error message is copied, since caller may not be
7338 using persistent storage. */
7340 void
7341 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
7343 gdb_trampoline_buffer = (char *) (uintptr_t) begin;
7344 gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
7345 if (errmsg)
7346 strncpy (gdb_trampoline_buffer_error, errmsg, 99);
7347 else
7348 strcpy (gdb_trampoline_buffer_error, "no buffer passed");
7351 static void __attribute__ ((constructor))
7352 initialize_tracepoint_ftlib (void)
7354 initialize_tracepoint ();
7356 gdb_agent_init ();
7359 #ifndef HAVE_GETAUXVAL
7360 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
7361 found, 0 is returned. This function is provided if glibc is too old. */
7363 unsigned long
7364 getauxval (unsigned long type)
7366 unsigned long data[2];
7367 FILE *f = fopen ("/proc/self/auxv", "r");
7368 unsigned long value = 0;
7370 if (f == NULL)
7371 return 0;
7373 while (fread (data, sizeof (data), 1, f) > 0)
7375 if (data[0] == type)
7377 value = data[1];
7378 break;
7382 fclose (f);
7383 return value;
7385 #endif
7387 #endif /* IN_PROCESS_AGENT */
7389 /* Return a timestamp, expressed as microseconds of the usual Unix
7390 time. (As the result is a 64-bit number, it will not overflow any
7391 time soon.) */
7393 static LONGEST
7394 get_timestamp (void)
7396 using namespace std::chrono;
7398 steady_clock::time_point now = steady_clock::now ();
7399 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
7402 void
7403 initialize_tracepoint (void)
7405 /* Start with the default size. */
7406 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
7408 /* Wire trace state variable 1 to be the timestamp. This will be
7409 uploaded to GDB upon connection and become one of its trace state
7410 variables. (In case you're wondering, if GDB already has a trace
7411 variable numbered 1, it will be renumbered.) */
7412 create_trace_state_variable (1, 0);
7413 set_trace_state_variable_name (1, "trace_timestamp");
7414 set_trace_state_variable_getter (1, get_timestamp);
7416 #ifdef IN_PROCESS_AGENT
7418 int pagesize;
7419 size_t jump_pad_size;
7421 pagesize = sysconf (_SC_PAGE_SIZE);
7422 if (pagesize == -1)
7423 perror_with_name ("sysconf");
7425 #define SCRATCH_BUFFER_NPAGES 20
7427 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
7429 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
7430 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
7431 if (gdb_jump_pad_buffer == NULL)
7432 perror_with_name ("mmap");
7433 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
7436 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
7438 /* It's not a fatal error for something to go wrong with trampoline
7439 buffer setup, but it can be mysterious, so create a channel to
7440 report back on what went wrong, using a fixed size since we may
7441 not be able to allocate space later when the problem occurs. */
7442 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
7444 strcpy (gdb_trampoline_buffer_error, "No errors reported");
7446 initialize_low_tracepoint ();
7447 #endif