Add translations for various sub-directories
[binutils-gdb.git] / gdbserver / tracepoint.cc
blob1395c70ad39d2ac1b260fc6a0ed507966ac5aa42
1 /* Tracepoint code for remote server for GDB.
2 Copyright (C) 2009-2024 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 "tracepoint.h"
20 #include "gdbthread.h"
21 #include "gdbsupport/rsp-low.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <chrono>
27 #include <inttypes.h>
28 #include "ax.h"
29 #include "tdesc.h"
31 #define IPA_SYM_STRUCT_NAME ipa_sym_addresses
32 #include "gdbsupport/agent.h"
34 #define DEFAULT_TRACE_BUFFER_SIZE 5242880 /* 5*1024*1024 */
36 /* This file is built for both GDBserver, and the in-process
37 agent (IPA), a shared library that includes a tracing agent that is
38 loaded by the inferior to support fast tracepoints. Fast
39 tracepoints (or more accurately, jump based tracepoints) are
40 implemented by patching the tracepoint location with a jump into a
41 small trampoline function whose job is to save the register state,
42 call the in-process tracing agent, and then execute the original
43 instruction that was under the tracepoint jump (possibly adjusted,
44 if PC-relative, or some such).
46 The current synchronization design is pull based. That means,
47 GDBserver does most of the work, by peeking/poking at the inferior
48 agent's memory directly for downloading tracepoint and associated
49 objects, and for uploading trace frames. Whenever the IPA needs
50 something from GDBserver (trace buffer is full, tracing stopped for
51 some reason, etc.) the IPA calls a corresponding hook function
52 where GDBserver has placed a breakpoint.
54 Each of the agents has its own trace buffer. When browsing the
55 trace frames built from slow and fast tracepoints from GDB (tfind
56 mode), there's no guarantee the user is seeing the trace frames in
57 strict chronological creation order, although, GDBserver tries to
58 keep the order relatively reasonable, by syncing the trace buffers
59 at appropriate times.
63 #ifdef IN_PROCESS_AGENT
65 static void trace_vdebug (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
67 static void
68 trace_vdebug (const char *fmt, ...)
70 char buf[1024];
71 va_list ap;
73 va_start (ap, fmt);
74 vsprintf (buf, fmt, ap);
75 fprintf (stderr, PROG "/tracepoint: %s\n", buf);
76 va_end (ap);
79 #define trace_debug(fmt, args...) \
80 do { \
81 if (debug_threads) \
82 trace_vdebug ((fmt), ##args); \
83 } while (0)
85 #else
87 #define trace_debug(fmt, args...) \
88 do { \
89 threads_debug_printf ((fmt), ##args); \
90 } while (0)
92 #endif
94 /* Prefix exported symbols, for good citizenship. All the symbols
95 that need exporting are defined in this module. Note that all
96 these symbols must be tagged with IP_AGENT_EXPORT_*. */
97 #ifdef IN_PROCESS_AGENT
98 # define gdb_tp_heap_buffer IPA_SYM_EXPORTED_NAME (gdb_tp_heap_buffer)
99 # define gdb_jump_pad_buffer IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer)
100 # define gdb_jump_pad_buffer_end IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer_end)
101 # define gdb_trampoline_buffer IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer)
102 # define gdb_trampoline_buffer_end IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_end)
103 # define gdb_trampoline_buffer_error IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_error)
104 # define collecting IPA_SYM_EXPORTED_NAME (collecting)
105 # define gdb_collect_ptr IPA_SYM_EXPORTED_NAME (gdb_collect_ptr)
106 # define stop_tracing IPA_SYM_EXPORTED_NAME (stop_tracing)
107 # define flush_trace_buffer IPA_SYM_EXPORTED_NAME (flush_trace_buffer)
108 # define about_to_request_buffer_space IPA_SYM_EXPORTED_NAME (about_to_request_buffer_space)
109 # define trace_buffer_is_full IPA_SYM_EXPORTED_NAME (trace_buffer_is_full)
110 # define stopping_tracepoint IPA_SYM_EXPORTED_NAME (stopping_tracepoint)
111 # define expr_eval_result IPA_SYM_EXPORTED_NAME (expr_eval_result)
112 # define error_tracepoint IPA_SYM_EXPORTED_NAME (error_tracepoint)
113 # define tracepoints IPA_SYM_EXPORTED_NAME (tracepoints)
114 # define tracing IPA_SYM_EXPORTED_NAME (tracing)
115 # define trace_buffer_ctrl IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl)
116 # define trace_buffer_ctrl_curr IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl_curr)
117 # define trace_buffer_lo IPA_SYM_EXPORTED_NAME (trace_buffer_lo)
118 # define trace_buffer_hi IPA_SYM_EXPORTED_NAME (trace_buffer_hi)
119 # define traceframe_read_count IPA_SYM_EXPORTED_NAME (traceframe_read_count)
120 # define traceframe_write_count IPA_SYM_EXPORTED_NAME (traceframe_write_count)
121 # define traceframes_created IPA_SYM_EXPORTED_NAME (traceframes_created)
122 # define trace_state_variables IPA_SYM_EXPORTED_NAME (trace_state_variables)
123 # define get_raw_reg_ptr IPA_SYM_EXPORTED_NAME (get_raw_reg_ptr)
124 # define get_trace_state_variable_value_ptr \
125 IPA_SYM_EXPORTED_NAME (get_trace_state_variable_value_ptr)
126 # define set_trace_state_variable_value_ptr \
127 IPA_SYM_EXPORTED_NAME (set_trace_state_variable_value_ptr)
128 # define helper_thread_id IPA_SYM_EXPORTED_NAME (helper_thread_id)
129 # define cmd_buf IPA_SYM_EXPORTED_NAME (cmd_buf)
130 # define ipa_tdesc_idx IPA_SYM_EXPORTED_NAME (ipa_tdesc_idx)
131 #endif
133 #ifndef IN_PROCESS_AGENT
135 /* Addresses of in-process agent's symbols GDBserver cares about. */
137 struct ipa_sym_addresses
139 CORE_ADDR addr_gdb_tp_heap_buffer;
140 CORE_ADDR addr_gdb_jump_pad_buffer;
141 CORE_ADDR addr_gdb_jump_pad_buffer_end;
142 CORE_ADDR addr_gdb_trampoline_buffer;
143 CORE_ADDR addr_gdb_trampoline_buffer_end;
144 CORE_ADDR addr_gdb_trampoline_buffer_error;
145 CORE_ADDR addr_collecting;
146 CORE_ADDR addr_gdb_collect_ptr;
147 CORE_ADDR addr_stop_tracing;
148 CORE_ADDR addr_flush_trace_buffer;
149 CORE_ADDR addr_about_to_request_buffer_space;
150 CORE_ADDR addr_trace_buffer_is_full;
151 CORE_ADDR addr_stopping_tracepoint;
152 CORE_ADDR addr_expr_eval_result;
153 CORE_ADDR addr_error_tracepoint;
154 CORE_ADDR addr_tracepoints;
155 CORE_ADDR addr_tracing;
156 CORE_ADDR addr_trace_buffer_ctrl;
157 CORE_ADDR addr_trace_buffer_ctrl_curr;
158 CORE_ADDR addr_trace_buffer_lo;
159 CORE_ADDR addr_trace_buffer_hi;
160 CORE_ADDR addr_traceframe_read_count;
161 CORE_ADDR addr_traceframe_write_count;
162 CORE_ADDR addr_traceframes_created;
163 CORE_ADDR addr_trace_state_variables;
164 CORE_ADDR addr_get_raw_reg_ptr;
165 CORE_ADDR addr_get_trace_state_variable_value_ptr;
166 CORE_ADDR addr_set_trace_state_variable_value_ptr;
167 CORE_ADDR addr_ipa_tdesc_idx;
170 static struct
172 const char *name;
173 int offset;
174 } symbol_list[] = {
175 IPA_SYM(gdb_tp_heap_buffer),
176 IPA_SYM(gdb_jump_pad_buffer),
177 IPA_SYM(gdb_jump_pad_buffer_end),
178 IPA_SYM(gdb_trampoline_buffer),
179 IPA_SYM(gdb_trampoline_buffer_end),
180 IPA_SYM(gdb_trampoline_buffer_error),
181 IPA_SYM(collecting),
182 IPA_SYM(gdb_collect_ptr),
183 IPA_SYM(stop_tracing),
184 IPA_SYM(flush_trace_buffer),
185 IPA_SYM(about_to_request_buffer_space),
186 IPA_SYM(trace_buffer_is_full),
187 IPA_SYM(stopping_tracepoint),
188 IPA_SYM(expr_eval_result),
189 IPA_SYM(error_tracepoint),
190 IPA_SYM(tracepoints),
191 IPA_SYM(tracing),
192 IPA_SYM(trace_buffer_ctrl),
193 IPA_SYM(trace_buffer_ctrl_curr),
194 IPA_SYM(trace_buffer_lo),
195 IPA_SYM(trace_buffer_hi),
196 IPA_SYM(traceframe_read_count),
197 IPA_SYM(traceframe_write_count),
198 IPA_SYM(traceframes_created),
199 IPA_SYM(trace_state_variables),
200 IPA_SYM(get_raw_reg_ptr),
201 IPA_SYM(get_trace_state_variable_value_ptr),
202 IPA_SYM(set_trace_state_variable_value_ptr),
203 IPA_SYM(ipa_tdesc_idx),
206 static struct ipa_sym_addresses ipa_sym_addrs;
208 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
210 static void
211 write_e_ipa_not_loaded (char *buffer)
213 sprintf (buffer,
214 "E.In-process agent library not loaded in process. "
215 "Fast tracepoints unavailable.");
218 /* If the in-process agent library isn't loaded in the inferior, write
219 an error to BUFFER, and return 1. Otherwise, return 0. */
221 static int
222 maybe_write_ipa_not_loaded (char *buffer)
224 if (!agent_loaded_p ())
226 write_e_ipa_not_loaded (buffer);
227 return 1;
229 return 0;
232 /* Cache all future symbols that the tracepoints module might request.
233 We can not request symbols at arbitrary states in the remote
234 protocol, only when the client tells us that new symbols are
235 available. So when we load the in-process library, make sure to
236 check the entire list. */
238 void
239 tracepoint_look_up_symbols (void)
241 int i;
243 if (agent_loaded_p ())
244 return;
246 for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
248 CORE_ADDR *addrp =
249 (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
251 if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
253 threads_debug_printf ("symbol `%s' not found", symbol_list[i].name);
254 return;
258 agent_look_up_symbols (NULL);
261 #endif
263 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
264 of the "stop_tracing" function. When this breakpoint is hit,
265 tracing stopped in the IPA for some reason. E.g., due to
266 tracepoint reaching the pass count, hitting conditional expression
267 evaluation error, etc.
269 The IPA's trace buffer is never in circular tracing mode: instead,
270 GDBserver's is, and whenever the in-process buffer fills, it calls
271 "flush_trace_buffer", which triggers an internal breakpoint.
272 GDBserver reacts to this breakpoint by pulling the meanwhile
273 collected data. Old frames discarding is always handled on the
274 GDBserver side. */
276 #ifdef IN_PROCESS_AGENT
277 /* See target.h. */
280 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
282 memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
283 return 0;
286 /* Call this in the functions where GDBserver places a breakpoint, so
287 that the compiler doesn't try to be clever and skip calling the
288 function at all. This is necessary, even if we tell the compiler
289 to not inline said functions. */
291 #if defined(__GNUC__)
292 # define UNKNOWN_SIDE_EFFECTS() asm ("")
293 #else
294 # define UNKNOWN_SIDE_EFFECTS() do {} while (0)
295 #endif
297 /* This is needed for -Wmissing-declarations. */
298 IP_AGENT_EXPORT_FUNC void stop_tracing (void);
300 IP_AGENT_EXPORT_FUNC void
301 stop_tracing (void)
303 /* GDBserver places breakpoint here. */
304 UNKNOWN_SIDE_EFFECTS();
307 /* This is needed for -Wmissing-declarations. */
308 IP_AGENT_EXPORT_FUNC void flush_trace_buffer (void);
310 IP_AGENT_EXPORT_FUNC void
311 flush_trace_buffer (void)
313 /* GDBserver places breakpoint here. */
314 UNKNOWN_SIDE_EFFECTS();
317 #endif
319 #ifndef IN_PROCESS_AGENT
320 static int
321 tracepoint_handler (CORE_ADDR address)
323 trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
324 paddress (address));
325 return 0;
328 /* Breakpoint at "stop_tracing" in the inferior lib. */
329 static struct breakpoint *stop_tracing_bkpt;
330 static int stop_tracing_handler (CORE_ADDR);
332 /* Breakpoint at "flush_trace_buffer" in the inferior lib. */
333 static struct breakpoint *flush_trace_buffer_bkpt;
334 static int flush_trace_buffer_handler (CORE_ADDR);
336 static void download_trace_state_variables (void);
337 static void upload_fast_traceframes (void);
339 static int run_inferior_command (char *cmd, int len);
341 static int
342 read_inferior_integer (CORE_ADDR symaddr, int *val)
344 return read_inferior_memory (symaddr, (unsigned char *) val,
345 sizeof (*val));
348 struct tracepoint;
349 static int tracepoint_send_agent (struct tracepoint *tpoint);
351 static int
352 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
354 return read_inferior_memory (symaddr, (unsigned char *) val,
355 sizeof (*val));
358 static int
359 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
361 void *pval = (void *) (uintptr_t) val;
362 int ret;
364 ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
365 *val = (uintptr_t) pval;
366 return ret;
369 static int
370 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
372 void *pval = (void *) (uintptr_t) val;
373 return target_write_memory (symaddr,
374 (unsigned char *) &pval, sizeof (pval));
377 static int
378 write_inferior_integer (CORE_ADDR symaddr, int val)
380 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
383 static int
384 write_inferior_int8 (CORE_ADDR symaddr, int8_t val)
386 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
389 static int
390 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
392 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
395 static CORE_ADDR target_malloc (ULONGEST size);
397 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD) \
398 do { \
399 memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
400 BUF += sizeof ((OBJ)->FIELD); \
401 } while (0)
403 #endif
405 /* Base action. Concrete actions inherit this. */
407 struct tracepoint_action
409 char type;
412 /* An 'M' (collect memory) action. */
413 struct collect_memory_action
415 struct tracepoint_action base;
417 ULONGEST addr;
418 ULONGEST len;
419 int32_t basereg;
422 /* An 'R' (collect registers) action. */
424 struct collect_registers_action
426 struct tracepoint_action base;
429 /* An 'X' (evaluate expression) action. */
431 struct eval_expr_action
433 struct tracepoint_action base;
435 struct agent_expr *expr;
438 #ifndef IN_PROCESS_AGENT
439 static CORE_ADDR
440 m_tracepoint_action_download (const struct tracepoint_action *action)
442 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_memory_action));
444 target_write_memory (ipa_action, (unsigned char *) action,
445 sizeof (struct collect_memory_action));
447 return ipa_action;
449 static char *
450 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
452 struct collect_memory_action *maction
453 = (struct collect_memory_action *) action;
455 COPY_FIELD_TO_BUF (buffer, maction, addr);
456 COPY_FIELD_TO_BUF (buffer, maction, len);
457 COPY_FIELD_TO_BUF (buffer, maction, basereg);
459 return buffer;
462 static CORE_ADDR
463 r_tracepoint_action_download (const struct tracepoint_action *action)
465 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_registers_action));
467 target_write_memory (ipa_action, (unsigned char *) action,
468 sizeof (struct collect_registers_action));
470 return ipa_action;
473 static char *
474 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
476 return buffer;
479 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
481 static CORE_ADDR
482 x_tracepoint_action_download (const struct tracepoint_action *action)
484 CORE_ADDR ipa_action = target_malloc (sizeof (struct eval_expr_action));
485 CORE_ADDR expr;
487 target_write_memory (ipa_action, (unsigned char *) action,
488 sizeof (struct eval_expr_action));
489 expr = download_agent_expr (((struct eval_expr_action *) action)->expr);
490 write_inferior_data_pointer (ipa_action
491 + offsetof (struct eval_expr_action, expr),
492 expr);
494 return ipa_action;
497 /* Copy agent expression AEXPR to buffer pointed by P. If AEXPR is NULL,
498 copy 0 to P. Return updated header of buffer. */
500 static char *
501 agent_expr_send (char *p, const struct agent_expr *aexpr)
503 /* Copy the length of condition first, and then copy its
504 content. */
505 if (aexpr == NULL)
507 memset (p, 0, 4);
508 p += 4;
510 else
512 memcpy (p, &aexpr->length, 4);
513 p +=4;
515 memcpy (p, aexpr->bytes, aexpr->length);
516 p += aexpr->length;
518 return p;
521 static char *
522 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
524 struct eval_expr_action *eaction = (struct eval_expr_action *) action;
526 return agent_expr_send (buffer, eaction->expr);
529 static char *
530 tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
532 switch (action->type)
534 case 'M':
535 return m_tracepoint_action_send (buffer, action);
536 case 'R':
537 return r_tracepoint_action_send (buffer, action);
538 case 'X':
539 return x_tracepoint_action_send (buffer, action);
541 error ("Unknown trace action '%c'.", action->type);
544 static CORE_ADDR
545 tracepoint_action_download (const struct tracepoint_action *action)
547 switch (action->type)
549 case 'M':
550 return m_tracepoint_action_download (action);
551 case 'R':
552 return r_tracepoint_action_download (action);
553 case 'X':
554 return x_tracepoint_action_download (action);
556 error ("Unknown trace action '%c'.", action->type);
558 #endif
560 /* This structure describes a piece of the source-level definition of
561 the tracepoint. The contents are not interpreted by the target,
562 but preserved verbatim for uploading upon reconnection. */
564 struct source_string
566 /* The type of string, such as "cond" for a conditional. */
567 char *type;
569 /* The source-level string itself. For the sake of target
570 debugging, we store it in plaintext, even though it is always
571 transmitted in hex. */
572 char *str;
574 /* Link to the next one in the list. We link them in the order
575 received, in case some make up an ordered list of commands or
576 some such. */
577 struct source_string *next;
580 enum tracepoint_type
582 /* Trap based tracepoint. */
583 trap_tracepoint,
585 /* A fast tracepoint implemented with a jump instead of a trap. */
586 fast_tracepoint,
589 typedef enum eval_result_type (*condfn) (unsigned char *,
590 ULONGEST *);
592 /* The definition of a tracepoint. */
594 /* Tracepoints may have multiple locations, each at a different
595 address. This can occur with optimizations, template
596 instantiation, etc. Since the locations may be in different
597 scopes, the conditions and actions may be different for each
598 location. Our target version of tracepoints is more like GDB's
599 notion of "breakpoint locations", but we have almost nothing that
600 is not per-location, so we bother having two kinds of objects. The
601 key consequence is that numbers are not unique, and that it takes
602 both number and address to identify a tracepoint uniquely. */
604 struct tracepoint
606 /* The number of the tracepoint, as specified by GDB. Several
607 tracepoint objects here may share a number. */
608 uint32_t number;
610 /* Address at which the tracepoint is supposed to trigger. Several
611 tracepoints may share an address. */
612 CORE_ADDR address;
614 /* Tracepoint type. */
615 enum tracepoint_type type;
617 /* True if the tracepoint is currently enabled. */
618 int8_t enabled;
620 /* The number of single steps that will be performed after each
621 tracepoint hit. */
622 uint64_t step_count;
624 /* The number of times the tracepoint may be hit before it will
625 terminate the entire tracing run. */
626 uint64_t pass_count;
628 /* Pointer to the agent expression that is the tracepoint's
629 conditional, or NULL if the tracepoint is unconditional. */
630 struct agent_expr *cond;
632 /* The list of actions to take when the tracepoint triggers. */
633 uint32_t numactions;
634 struct tracepoint_action **actions;
636 /* Count of the times we've hit this tracepoint during the run.
637 Note that while-stepping steps are not counted as "hits". */
638 uint64_t hit_count;
640 /* Cached sum of the sizes of traceframes created by this point. */
641 uint64_t traceframe_usage;
643 CORE_ADDR compiled_cond;
645 /* Link to the next tracepoint in the list. */
646 struct tracepoint *next;
648 #ifndef IN_PROCESS_AGENT
649 /* The list of actions to take when the tracepoint triggers, in
650 string/packet form. */
651 char **actions_str;
653 /* The collection of strings that describe the tracepoint as it was
654 entered into GDB. These are not used by the target, but are
655 reported back to GDB upon reconnection. */
656 struct source_string *source_strings;
658 /* The number of bytes displaced by fast tracepoints. It may subsume
659 multiple instructions, for multi-byte fast tracepoints. This
660 field is only valid for fast tracepoints. */
661 uint32_t orig_size;
663 /* Only for fast tracepoints. */
664 CORE_ADDR obj_addr_on_target;
666 /* Address range where the original instruction under a fast
667 tracepoint was relocated to. (_end is actually one byte past
668 the end). */
669 CORE_ADDR adjusted_insn_addr;
670 CORE_ADDR adjusted_insn_addr_end;
672 /* The address range of the piece of the jump pad buffer that was
673 assigned to this fast tracepoint. (_end is actually one byte
674 past the end).*/
675 CORE_ADDR jump_pad;
676 CORE_ADDR jump_pad_end;
678 /* The address range of the piece of the trampoline buffer that was
679 assigned to this fast tracepoint. (_end is actually one byte
680 past the end). */
681 CORE_ADDR trampoline;
682 CORE_ADDR trampoline_end;
684 /* The list of actions to take while in a stepping loop. These
685 fields are only valid for patch-based tracepoints. */
686 int num_step_actions;
687 struct tracepoint_action **step_actions;
688 /* Same, but in string/packet form. */
689 char **step_actions_str;
691 /* Handle returned by the breakpoint or tracepoint module when we
692 inserted the trap or jump.
693 NULL if we haven't inserted it yet. */
694 void *handle;
695 #endif
699 #ifndef IN_PROCESS_AGENT
701 /* Given `while-stepping', a thread may be collecting data for more
702 than one tracepoint simultaneously. On the other hand, the same
703 tracepoint with a while-stepping action may be hit by more than one
704 thread simultaneously (but not quite, each thread could be handling
705 a different step). Each thread holds a list of these objects,
706 representing the current step of each while-stepping action being
707 collected. */
709 struct wstep_state
711 struct wstep_state *next;
713 /* The tracepoint number. */
714 int tp_number;
715 /* The tracepoint's address. */
716 CORE_ADDR tp_address;
718 /* The number of the current step in this 'while-stepping'
719 action. */
720 long current_step;
723 #endif
725 extern "C" {
727 /* The linked list of all tracepoints. Marked explicitly as used as
728 the in-process library doesn't use it for the fast tracepoints
729 support. */
730 IP_AGENT_EXPORT_VAR struct tracepoint *tracepoints;
732 /* The first tracepoint to exceed its pass count. */
734 IP_AGENT_EXPORT_VAR struct tracepoint *stopping_tracepoint;
736 /* True if the trace buffer is full or otherwise no longer usable. */
738 IP_AGENT_EXPORT_VAR int trace_buffer_is_full;
740 /* The first error that occurred during expression evaluation. */
742 /* Stored as an int to avoid the IPA ABI being dependent on whatever
743 the compiler decides to use for the enum's underlying type. Holds
744 enum eval_result_type values. */
745 IP_AGENT_EXPORT_VAR int expr_eval_result = expr_eval_no_error;
749 #ifndef IN_PROCESS_AGENT
751 /* Pointer to the last tracepoint in the list, new tracepoints are
752 linked in at the end. */
754 static struct tracepoint *last_tracepoint;
756 static const char * const eval_result_names[] =
758 #define AX_RESULT_TYPE(ENUM,STR) STR,
759 #include "ax-result-types.def"
760 #undef AX_RESULT_TYPE
763 #endif
765 /* The tracepoint in which the error occurred. */
767 extern "C" {
768 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
771 struct trace_state_variable
773 /* This is the name of the variable as used in GDB. The target
774 doesn't use the name, but needs to have it for saving and
775 reconnection purposes. */
776 char *name;
778 /* This number identifies the variable uniquely. Numbers may be
779 assigned either by the target (in the case of builtin variables),
780 or by GDB, and are presumed unique during the course of a trace
781 experiment. */
782 int number;
784 /* The variable's initial value, a 64-bit signed integer always. */
785 LONGEST initial_value;
787 /* The variable's value, a 64-bit signed integer always. */
788 LONGEST value;
790 /* Pointer to a getter function, used to supply computed values. */
791 LONGEST (*getter) (void);
793 /* Link to the next variable. */
794 struct trace_state_variable *next;
797 /* Linked list of all trace state variables. */
799 #ifdef IN_PROCESS_AGENT
800 static struct trace_state_variable *alloced_trace_state_variables;
801 #endif
803 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
805 /* The results of tracing go into a fixed-size space known as the
806 "trace buffer". Because usage follows a limited number of
807 patterns, we manage it ourselves rather than with malloc. Basic
808 rules are that we create only one trace frame at a time, each is
809 variable in size, they are never moved once created, and we only
810 discard if we are doing a circular buffer, and then only the oldest
811 ones. Each trace frame includes its own size, so we don't need to
812 link them together, and the trace frame number is relative to the
813 first one, so we don't need to record numbers. A trace frame also
814 records the number of the tracepoint that created it. The data
815 itself is a series of blocks, each introduced by a single character
816 and with a defined format. Each type of block has enough
817 type/length info to allow scanners to jump quickly from one block
818 to the next without reading each byte in the block. */
820 /* Trace buffer management would be simple - advance a free pointer
821 from beginning to end, then stop - were it not for the circular
822 buffer option, which is a useful way to prevent a trace run from
823 stopping prematurely because the buffer filled up. In the circular
824 case, the location of the first trace frame (trace_buffer_start)
825 moves as old trace frames are discarded. Also, since we grow trace
826 frames incrementally as actions are performed, we wrap around to
827 the beginning of the trace buffer. This is per-block, so each
828 block within a trace frame remains contiguous. Things get messy
829 when the wrapped-around trace frame is the one being discarded; the
830 free space ends up in two parts at opposite ends of the buffer. */
832 #ifndef ATTR_PACKED
833 # if defined(__GNUC__)
834 # define ATTR_PACKED __attribute__ ((packed))
835 # else
836 # define ATTR_PACKED /* nothing */
837 # endif
838 #endif
840 /* The data collected at a tracepoint hit. This object should be as
841 small as possible, since there may be a great many of them. We do
842 not need to keep a frame number, because they are all sequential
843 and there are no deletions; so the Nth frame in the buffer is
844 always frame number N. */
846 struct traceframe
848 /* Number of the tracepoint that collected this traceframe. A value
849 of 0 indicates the current end of the trace buffer. We make this
850 a 16-bit field because it's never going to happen that GDB's
851 numbering of tracepoints reaches 32,000. */
852 int tpnum : 16;
854 /* The size of the data in this trace frame. We limit this to 32
855 bits, even on a 64-bit target, because it's just implausible that
856 one is validly going to collect 4 gigabytes of data at a single
857 tracepoint hit. */
858 unsigned int data_size : 32;
860 /* The base of the trace data, which is contiguous from this point. */
861 unsigned char data[0];
863 } ATTR_PACKED;
865 /* The size of the EOB marker, in bytes. A traceframe with zeroed
866 fields (and no data) marks the end of trace data. */
867 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
869 /* This flag is true if the trace buffer is circular, meaning that
870 when it fills, the oldest trace frames are discarded in order to
871 make room. */
873 #ifndef IN_PROCESS_AGENT
874 static int circular_trace_buffer;
875 #endif
877 /* Size of the trace buffer. */
879 static LONGEST trace_buffer_size;
881 extern "C" {
883 /* Pointer to the block of memory that traceframes all go into. */
885 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
887 /* Pointer to the end of the trace buffer, more precisely to the byte
888 after the end of the buffer. */
890 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
894 /* Control structure holding the read/write/etc. pointers into the
895 trace buffer. We need more than one of these to implement a
896 transaction-like mechanism to guarantees that both GDBserver and the
897 in-process agent can try to change the trace buffer
898 simultaneously. */
900 struct trace_buffer_control
902 /* Pointer to the first trace frame in the buffer. In the
903 non-circular case, this is equal to trace_buffer_lo, otherwise it
904 moves around in the buffer. */
905 unsigned char *start;
907 /* Pointer to the free part of the trace buffer. Note that we clear
908 several bytes at and after this pointer, so that traceframe
909 scans/searches terminate properly. */
910 unsigned char *free;
912 /* Pointer to the byte after the end of the free part. Note that
913 this may be smaller than trace_buffer_free in the circular case,
914 and means that the free part is in two pieces. Initially it is
915 equal to trace_buffer_hi, then is generally equivalent to
916 trace_buffer_start. */
917 unsigned char *end_free;
919 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
920 this is the point at which the trace data breaks, and resumes at
921 trace_buffer_lo. */
922 unsigned char *wrap;
925 /* Same as above, to be used by GDBserver when updating the in-process
926 agent. */
927 struct ipa_trace_buffer_control
929 uintptr_t start;
930 uintptr_t free;
931 uintptr_t end_free;
932 uintptr_t wrap;
936 /* We have possibly both GDBserver and an inferior thread accessing
937 the same IPA trace buffer memory. The IPA is the producer (tries
938 to put new frames in the buffer), while GDBserver occasionally
939 consumes them, that is, flushes the IPA's buffer into its own
940 buffer. Both sides need to update the trace buffer control
941 pointers (current head, tail, etc.). We can't use a global lock to
942 synchronize the accesses, as otherwise we could deadlock GDBserver
943 (if the thread holding the lock stops for a signal, say). So
944 instead of that, we use a transaction scheme where GDBserver writes
945 always prevail over the IPAs writes, and, we have the IPA detect
946 the commit failure/overwrite, and retry the whole attempt. This is
947 mainly implemented by having a global token object that represents
948 who wrote last to the buffer control structure. We need to freeze
949 any inferior writing to the buffer while GDBserver touches memory,
950 so that the inferior can correctly detect that GDBserver had been
951 there, otherwise, it could mistakingly think its commit was
952 successful; that's implemented by simply having GDBserver set a
953 breakpoint the inferior hits if it is the critical region.
955 There are three cycling trace buffer control structure copies
956 (buffer head, tail, etc.), with the token object including an index
957 indicating which is current live copy. The IPA tentatively builds
958 an updated copy in a non-current control structure, while GDBserver
959 always clobbers the current version directly. The IPA then tries
960 to atomically "commit" its version; if GDBserver clobbered the
961 structure meanwhile, that will fail, and the IPA restarts the
962 allocation process.
964 Listing the step in further detail, we have:
966 In-process agent (producer):
968 - passes by `about_to_request_buffer_space' breakpoint/lock
970 - reads current token, extracts current trace buffer control index,
971 and starts tentatively updating the rightmost one (0->1, 1->2,
972 2->0). Note that only one inferior thread is executing this code
973 at any given time, due to an outer lock in the jump pads.
975 - updates counters, and tries to commit the token.
977 - passes by second `about_to_request_buffer_space' breakpoint/lock,
978 leaving the sync region.
980 - checks if the update was effective.
982 - if trace buffer was found full, hits flush_trace_buffer
983 breakpoint, and restarts later afterwards.
985 GDBserver (consumer):
987 - sets `about_to_request_buffer_space' breakpoint/lock.
989 - updates the token unconditionally, using the current buffer
990 control index, since it knows that the IP agent always writes to
991 the rightmost, and due to the breakpoint, at most one IP thread
992 can try to update the trace buffer concurrently to GDBserver, so
993 there will be no danger of trace buffer control index wrap making
994 the IPA write to the same index as GDBserver.
996 - flushes the IP agent's trace buffer completely, and updates the
997 current trace buffer control structure. GDBserver *always* wins.
999 - removes the `about_to_request_buffer_space' breakpoint.
1001 The token is stored in the `trace_buffer_ctrl_curr' variable.
1002 Internally, it's bits are defined as:
1004 |-------------+-----+-------------+--------+-------------+--------------|
1005 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1006 |-------------+-----+-------------+--------+-------------+--------------|
1007 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1008 |-------------+-----+-------------+--------+-------------+--------------|
1010 GSB - GDBserver Stamp Bit
1011 PC - Previous Counter
1012 CC - Current Counter
1013 TBCI - Trace Buffer Control Index
1016 An IPA update of `trace_buffer_ctrl_curr' does:
1018 - read CC from the current token, save as PC.
1019 - updates pointers
1020 - atomically tries to write PC+1,CC
1022 A GDBserver update of `trace_buffer_ctrl_curr' does:
1024 - reads PC and CC from the current token.
1025 - updates pointers
1026 - writes GSB,PC,CC
1029 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1030 for the counters described below. The cleared bits are used to
1031 hold the index of the items of the `trace_buffer_ctrl' array that
1032 is "current". */
1033 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1035 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1036 counter, and the `current' counter. */
1038 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1039 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1041 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1042 always stamps this bit as set. */
1043 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1045 #ifdef IN_PROCESS_AGENT
1046 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1047 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1049 # define TRACE_BUFFER_CTRL_CURR \
1050 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1052 #else
1054 /* The GDBserver side agent only needs one instance of this object, as
1055 it doesn't need to sync with itself. Define it as array anyway so
1056 that the rest of the code base doesn't need to care for the
1057 difference. */
1058 static trace_buffer_control trace_buffer_ctrl[1];
1059 # define TRACE_BUFFER_CTRL_CURR 0
1060 #endif
1062 /* These are convenience macros used to access the current trace
1063 buffer control in effect. */
1064 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1065 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1066 #define trace_buffer_end_free \
1067 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1068 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1071 /* Macro that returns a pointer to the first traceframe in the buffer. */
1073 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1075 /* Macro that returns a pointer to the next traceframe in the buffer.
1076 If the computed location is beyond the wraparound point, subtract
1077 the offset of the wraparound. */
1079 #define NEXT_TRACEFRAME_1(TF) \
1080 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1082 #define NEXT_TRACEFRAME(TF) \
1083 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1084 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1085 ? (trace_buffer_wrap - trace_buffer_lo) \
1086 : 0)))
1088 /* The difference between these counters represents the total number
1089 of complete traceframes present in the trace buffer. The IP agent
1090 writes to the write count, GDBserver writes to read count. */
1092 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1093 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1095 /* Convenience macro. */
1097 #define traceframe_count \
1098 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1100 /* The count of all traceframes created in the current run, including
1101 ones that were discarded to make room. */
1103 IP_AGENT_EXPORT_VAR int traceframes_created;
1105 #ifndef IN_PROCESS_AGENT
1107 /* Read-only regions are address ranges whose contents don't change,
1108 and so can be read from target memory even while looking at a trace
1109 frame. Without these, disassembly for instance will likely fail,
1110 because the program code is not usually collected into a trace
1111 frame. This data structure does not need to be very complicated or
1112 particularly efficient, it's only going to be used occasionally,
1113 and only by some commands. */
1115 struct readonly_region
1117 /* The bounds of the region. */
1118 CORE_ADDR start, end;
1120 /* Link to the next one. */
1121 struct readonly_region *next;
1124 /* Linked list of readonly regions. This list stays in effect from
1125 one tstart to the next. */
1127 static struct readonly_region *readonly_regions;
1129 #endif
1131 /* The global that controls tracing overall. */
1133 IP_AGENT_EXPORT_VAR int tracing;
1135 #ifndef IN_PROCESS_AGENT
1137 /* Controls whether tracing should continue after GDB disconnects. */
1139 int disconnected_tracing;
1141 /* The reason for the last tracing run to have stopped. We initialize
1142 to a distinct string so that GDB can distinguish between "stopped
1143 after running" and "stopped because never run" cases. */
1145 static const char *tracing_stop_reason = "tnotrun";
1147 static int tracing_stop_tpnum;
1149 /* 64-bit timestamps for the trace run's start and finish, expressed
1150 in microseconds from the Unix epoch. */
1152 static LONGEST tracing_start_time;
1153 static LONGEST tracing_stop_time;
1155 /* The (optional) user-supplied name of the user that started the run.
1156 This is an arbitrary string, and may be NULL. */
1158 static char *tracing_user_name;
1160 /* Optional user-supplied text describing the run. This is
1161 an arbitrary string, and may be NULL. */
1163 static char *tracing_notes;
1165 /* Optional user-supplied text explaining a tstop command. This is an
1166 arbitrary string, and may be NULL. */
1168 static char *tracing_stop_note;
1170 #endif
1172 /* Base "class" for tracepoint type specific data to be passed down to
1173 collect_data_at_tracepoint. */
1174 struct tracepoint_hit_ctx
1176 enum tracepoint_type type;
1179 #ifdef IN_PROCESS_AGENT
1181 /* Fast/jump tracepoint specific data to be passed down to
1182 collect_data_at_tracepoint. */
1183 struct fast_tracepoint_ctx
1185 struct tracepoint_hit_ctx base;
1187 struct regcache regcache;
1188 int regcache_initted;
1189 unsigned char *regspace;
1191 unsigned char *regs;
1192 struct tracepoint *tpoint;
1195 #else
1197 /* Static tracepoint specific data to be passed down to
1198 collect_data_at_tracepoint. */
1199 struct trap_tracepoint_ctx
1201 struct tracepoint_hit_ctx base;
1203 struct regcache *regcache;
1206 #endif
1208 #ifndef IN_PROCESS_AGENT
1209 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1210 static int traceframe_read_tsv (int num, LONGEST *val);
1211 #endif
1213 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1214 struct tracepoint *tpoint);
1216 #ifndef IN_PROCESS_AGENT
1217 static void clear_readonly_regions (void);
1218 static void clear_installed_tracepoints (void);
1219 #endif
1221 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1222 CORE_ADDR stop_pc,
1223 struct tracepoint *tpoint);
1224 #ifndef IN_PROCESS_AGENT
1225 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1226 CORE_ADDR stop_pc,
1227 struct tracepoint *tpoint, int current_step);
1228 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1229 CORE_ADDR *jump_entry);
1230 #endif
1231 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1232 CORE_ADDR stop_pc,
1233 struct tracepoint *tpoint,
1234 struct traceframe *tframe,
1235 struct tracepoint_action *taction);
1237 #ifndef IN_PROCESS_AGENT
1238 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1240 static void install_tracepoint (struct tracepoint *, char *own_buf);
1241 static void download_tracepoint (struct tracepoint *);
1242 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1243 static void clone_fast_tracepoint (struct tracepoint *to,
1244 const struct tracepoint *from);
1245 #endif
1247 static LONGEST get_timestamp (void);
1249 #if defined(__GNUC__)
1250 # define memory_barrier() asm volatile ("" : : : "memory")
1251 #else
1252 # define memory_barrier() do {} while (0)
1253 #endif
1255 /* We only build the IPA if this builtin is supported, and there are
1256 no uses of this in GDBserver itself, so we're safe in defining this
1257 unconditionally. */
1258 #define cmpxchg(mem, oldval, newval) \
1259 __sync_val_compare_and_swap (mem, oldval, newval)
1261 /* Record that an error occurred during expression evaluation. */
1263 static void
1264 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1265 enum eval_result_type rtype)
1267 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1268 tpoint->number, paddress (tpoint->address), which, rtype);
1270 #ifdef IN_PROCESS_AGENT
1271 /* Only record the first error we get. */
1272 if (cmpxchg (&expr_eval_result,
1273 expr_eval_no_error,
1274 rtype) != expr_eval_no_error)
1275 return;
1276 #else
1277 if (expr_eval_result != expr_eval_no_error)
1278 return;
1279 #endif
1281 error_tracepoint = tpoint;
1284 /* Trace buffer management. */
1286 static void
1287 clear_trace_buffer (void)
1289 trace_buffer_start = trace_buffer_lo;
1290 trace_buffer_free = trace_buffer_lo;
1291 trace_buffer_end_free = trace_buffer_hi;
1292 trace_buffer_wrap = trace_buffer_hi;
1293 /* A traceframe with zeroed fields marks the end of trace data. */
1294 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1295 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1296 traceframe_read_count = traceframe_write_count = 0;
1297 traceframes_created = 0;
1300 #ifndef IN_PROCESS_AGENT
1302 static void
1303 clear_inferior_trace_buffer (void)
1305 CORE_ADDR ipa_trace_buffer_lo;
1306 CORE_ADDR ipa_trace_buffer_hi;
1307 struct traceframe ipa_traceframe = { 0 };
1308 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1310 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1311 &ipa_trace_buffer_lo);
1312 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1313 &ipa_trace_buffer_hi);
1315 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1316 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1317 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1318 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1320 /* A traceframe with zeroed fields marks the end of trace data. */
1321 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1322 (unsigned char *) &ipa_trace_buffer_ctrl,
1323 sizeof (ipa_trace_buffer_ctrl));
1325 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1327 /* A traceframe with zeroed fields marks the end of trace data. */
1328 target_write_memory (ipa_trace_buffer_lo,
1329 (unsigned char *) &ipa_traceframe,
1330 sizeof (ipa_traceframe));
1332 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1333 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1334 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1337 #endif
1339 static void
1340 init_trace_buffer (LONGEST bufsize)
1342 size_t alloc_size;
1344 trace_buffer_size = bufsize;
1346 /* Make sure to internally allocate at least space for the EOB
1347 marker. */
1348 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1349 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1350 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1352 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1354 clear_trace_buffer ();
1357 #ifdef IN_PROCESS_AGENT
1359 /* This is needed for -Wmissing-declarations. */
1360 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1362 IP_AGENT_EXPORT_FUNC void
1363 about_to_request_buffer_space (void)
1365 /* GDBserver places breakpoint here while it goes about to flush
1366 data at random times. */
1367 UNKNOWN_SIDE_EFFECTS();
1370 #endif
1372 /* Carve out a piece of the trace buffer, returning NULL in case of
1373 failure. */
1375 static void *
1376 trace_buffer_alloc (size_t amt)
1378 unsigned char *rslt;
1379 struct trace_buffer_control *tbctrl;
1380 unsigned int curr;
1381 #ifdef IN_PROCESS_AGENT
1382 unsigned int prev, prev_filtered;
1383 unsigned int commit_count;
1384 unsigned int commit;
1385 unsigned int readout;
1386 #else
1387 struct traceframe *oldest;
1388 unsigned char *new_start;
1389 #endif
1391 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1392 (long) amt, (long) sizeof (struct traceframe));
1394 /* Account for the EOB marker. */
1395 amt += TRACEFRAME_EOB_MARKER_SIZE;
1397 #ifdef IN_PROCESS_AGENT
1398 again:
1399 memory_barrier ();
1401 /* Read the current token and extract the index to try to write to,
1402 storing it in CURR. */
1403 prev = trace_buffer_ctrl_curr;
1404 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1405 curr = prev_filtered + 1;
1406 if (curr > 2)
1407 curr = 0;
1409 about_to_request_buffer_space ();
1411 /* Start out with a copy of the current state. GDBserver may be
1412 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1413 be able to commit anyway if that happens. */
1414 trace_buffer_ctrl[curr]
1415 = trace_buffer_ctrl[prev_filtered];
1416 trace_debug ("trying curr=%u", curr);
1417 #else
1418 /* The GDBserver's agent doesn't need all that syncing, and always
1419 updates TCB 0 (there's only one, mind you). */
1420 curr = 0;
1421 #endif
1422 tbctrl = &trace_buffer_ctrl[curr];
1424 /* Offsets are easier to grok for debugging than raw addresses,
1425 especially for the small trace buffer sizes that are useful for
1426 testing. */
1427 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1428 curr,
1429 (int) (tbctrl->start - trace_buffer_lo),
1430 (int) (tbctrl->free - trace_buffer_lo),
1431 (int) (tbctrl->end_free - trace_buffer_lo),
1432 (int) (tbctrl->wrap - trace_buffer_lo),
1433 (int) (trace_buffer_hi - trace_buffer_lo));
1435 /* The algorithm here is to keep trying to get a contiguous block of
1436 the requested size, possibly discarding older traceframes to free
1437 up space. Since free space might come in one or two pieces,
1438 depending on whether discarded traceframes wrapped around at the
1439 high end of the buffer, we test both pieces after each
1440 discard. */
1441 while (1)
1443 /* First, if we have two free parts, try the upper one first. */
1444 if (tbctrl->end_free < tbctrl->free)
1446 if (tbctrl->free + amt <= trace_buffer_hi)
1447 /* We have enough in the upper part. */
1448 break;
1449 else
1451 /* Our high part of free space wasn't enough. Give up
1452 on it for now, set wraparound. We will recover the
1453 space later, if/when the wrapped-around traceframe is
1454 discarded. */
1455 trace_debug ("Upper part too small, setting wraparound");
1456 tbctrl->wrap = tbctrl->free;
1457 tbctrl->free = trace_buffer_lo;
1461 /* The normal case. */
1462 if (tbctrl->free + amt <= tbctrl->end_free)
1463 break;
1465 #ifdef IN_PROCESS_AGENT
1466 /* The IP Agent's buffer is always circular. It isn't used
1467 currently, but `circular_trace_buffer' could represent
1468 GDBserver's mode. If we didn't find space, ask GDBserver to
1469 flush. */
1471 flush_trace_buffer ();
1472 memory_barrier ();
1473 if (tracing)
1475 trace_debug ("gdbserver flushed buffer, retrying");
1476 goto again;
1479 /* GDBserver cancelled the tracing. Bail out as well. */
1480 return NULL;
1481 #else
1482 /* If we're here, then neither part is big enough, and
1483 non-circular trace buffers are now full. */
1484 if (!circular_trace_buffer)
1486 trace_debug ("Not enough space in the trace buffer");
1487 return NULL;
1490 trace_debug ("Need more space in the trace buffer");
1492 /* If we have a circular buffer, we can try discarding the
1493 oldest traceframe and see if that helps. */
1494 oldest = FIRST_TRACEFRAME ();
1495 if (oldest->tpnum == 0)
1497 /* Not good; we have no traceframes to free. Perhaps we're
1498 asking for a block that is larger than the buffer? In
1499 any case, give up. */
1500 trace_debug ("No traceframes to discard");
1501 return NULL;
1504 /* We don't run this code in the in-process agent currently.
1505 E.g., we could leave the in-process agent in autonomous
1506 circular mode if we only have fast tracepoints. If we do
1507 that, then this bit becomes racy with GDBserver, which also
1508 writes to this counter. */
1509 --traceframe_write_count;
1511 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1512 /* If we freed the traceframe that wrapped around, go back
1513 to the non-wrap case. */
1514 if (new_start < tbctrl->start)
1516 trace_debug ("Discarding past the wraparound");
1517 tbctrl->wrap = trace_buffer_hi;
1519 tbctrl->start = new_start;
1520 tbctrl->end_free = tbctrl->start;
1522 trace_debug ("Discarded a traceframe\n"
1523 "Trace buffer [%d], start=%d free=%d "
1524 "endfree=%d wrap=%d hi=%d",
1525 curr,
1526 (int) (tbctrl->start - trace_buffer_lo),
1527 (int) (tbctrl->free - trace_buffer_lo),
1528 (int) (tbctrl->end_free - trace_buffer_lo),
1529 (int) (tbctrl->wrap - trace_buffer_lo),
1530 (int) (trace_buffer_hi - trace_buffer_lo));
1532 /* Now go back around the loop. The discard might have resulted
1533 in either one or two pieces of free space, so we want to try
1534 both before freeing any more traceframes. */
1535 #endif
1538 /* If we get here, we know we can provide the asked-for space. */
1540 rslt = tbctrl->free;
1542 /* Adjust the request back down, now that we know we have space for
1543 the marker, but don't commit to AMT yet, we may still need to
1544 restart the operation if GDBserver touches the trace buffer
1545 (obviously only important in the in-process agent's version). */
1546 tbctrl->free += (amt - sizeof (struct traceframe));
1548 /* Or not. If GDBserver changed the trace buffer behind our back,
1549 we get to restart a new allocation attempt. */
1551 #ifdef IN_PROCESS_AGENT
1552 /* Build the tentative token. */
1553 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1554 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1555 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1556 | commit_count
1557 | curr);
1559 /* Try to commit it. */
1560 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1561 if (readout != prev)
1563 trace_debug ("GDBserver has touched the trace buffer, restarting."
1564 " (prev=%08x, commit=%08x, readout=%08x)",
1565 prev, commit, readout);
1566 goto again;
1569 /* Hold your horses here. Even if that change was committed,
1570 GDBserver could come in, and clobber it. We need to hold to be
1571 able to tell if GDBserver clobbers before or after we committed
1572 the change. Whenever GDBserver goes about touching the IPA
1573 buffer, it sets a breakpoint in this routine, so we have a sync
1574 point here. */
1575 about_to_request_buffer_space ();
1577 /* Check if the change has been effective, even if GDBserver stopped
1578 us at the breakpoint. */
1581 unsigned int refetch;
1583 memory_barrier ();
1585 refetch = trace_buffer_ctrl_curr;
1587 if (refetch == commit
1588 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1590 /* effective */
1591 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1592 "readout=%08x, refetch=%08x)",
1593 prev, commit, readout, refetch);
1595 else
1597 trace_debug ("GDBserver has touched the trace buffer, not effective."
1598 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1599 prev, commit, readout, refetch);
1600 goto again;
1603 #endif
1605 /* We have a new piece of the trace buffer. Hurray! */
1607 /* Add an EOB marker just past this allocation. */
1608 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1609 ((struct traceframe *) tbctrl->free)->data_size = 0;
1611 /* Adjust the request back down, now that we know we have space for
1612 the marker. */
1613 amt -= sizeof (struct traceframe);
1615 if (debug_threads)
1617 trace_debug ("Allocated %d bytes", (int) amt);
1618 trace_debug ("Trace buffer [%d] start=%d free=%d "
1619 "endfree=%d wrap=%d hi=%d",
1620 curr,
1621 (int) (tbctrl->start - trace_buffer_lo),
1622 (int) (tbctrl->free - trace_buffer_lo),
1623 (int) (tbctrl->end_free - trace_buffer_lo),
1624 (int) (tbctrl->wrap - trace_buffer_lo),
1625 (int) (trace_buffer_hi - trace_buffer_lo));
1628 return rslt;
1631 #ifndef IN_PROCESS_AGENT
1633 /* Return the total free space. This is not necessarily the largest
1634 block we can allocate, because of the two-part case. */
1636 static int
1637 free_space (void)
1639 if (trace_buffer_free <= trace_buffer_end_free)
1640 return trace_buffer_end_free - trace_buffer_free;
1641 else
1642 return ((trace_buffer_end_free - trace_buffer_lo)
1643 + (trace_buffer_hi - trace_buffer_free));
1646 /* An 'S' in continuation packets indicates remainder are for
1647 while-stepping. */
1649 static int seen_step_action_flag;
1651 /* Create a tracepoint (location) with given number and address. Add this
1652 new tracepoint to list and sort this list. */
1654 static struct tracepoint *
1655 add_tracepoint (int num, CORE_ADDR addr)
1657 struct tracepoint *tpoint, **tp_next;
1659 tpoint = XNEW (struct tracepoint);
1660 tpoint->number = num;
1661 tpoint->address = addr;
1662 tpoint->numactions = 0;
1663 tpoint->actions = NULL;
1664 tpoint->actions_str = NULL;
1665 tpoint->cond = NULL;
1666 tpoint->num_step_actions = 0;
1667 tpoint->step_actions = NULL;
1668 tpoint->step_actions_str = NULL;
1669 /* Start all off as regular (slow) tracepoints. */
1670 tpoint->type = trap_tracepoint;
1671 tpoint->orig_size = -1;
1672 tpoint->source_strings = NULL;
1673 tpoint->compiled_cond = 0;
1674 tpoint->handle = NULL;
1675 tpoint->next = NULL;
1677 /* Find a place to insert this tracepoint into list in order to keep
1678 the tracepoint list still in the ascending order. There may be
1679 multiple tracepoints at the same address as TPOINT's, and this
1680 guarantees TPOINT is inserted after all the tracepoints which are
1681 set at the same address. For example, fast tracepoints A, B, C are
1682 set at the same address, and D is to be insert at the same place as
1683 well,
1685 -->| A |--> | B |-->| C |->...
1687 One jump pad was created for tracepoint A, B, and C, and the target
1688 address of A is referenced/used in jump pad. So jump pad will let
1689 inferior jump to A. If D is inserted in front of A, like this,
1691 -->| D |-->| A |--> | B |-->| C |->...
1693 without updating jump pad, D is not reachable during collect, which
1694 is wrong. As we can see, the order of B, C and D doesn't matter, but
1695 A should always be the `first' one. */
1696 for (tp_next = &tracepoints;
1697 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1698 tp_next = &(*tp_next)->next)
1700 tpoint->next = *tp_next;
1701 *tp_next = tpoint;
1702 last_tracepoint = tpoint;
1704 seen_step_action_flag = 0;
1706 return tpoint;
1709 #ifndef IN_PROCESS_AGENT
1711 /* Return the tracepoint with the given number and address, or NULL. */
1713 static struct tracepoint *
1714 find_tracepoint (int id, CORE_ADDR addr)
1716 struct tracepoint *tpoint;
1718 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1719 if (tpoint->number == id && tpoint->address == addr)
1720 return tpoint;
1722 return NULL;
1725 /* Remove TPOINT from global list. */
1727 static void
1728 remove_tracepoint (struct tracepoint *tpoint)
1730 struct tracepoint *tp, *tp_prev;
1732 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1733 tp_prev = tp, tp = tp->next)
1736 if (tp)
1738 if (tp_prev)
1739 tp_prev->next = tp->next;
1740 else
1741 tracepoints = tp->next;
1743 xfree (tp);
1747 /* There may be several tracepoints with the same number (because they
1748 are "locations", in GDB parlance); return the next one after the
1749 given tracepoint, or search from the beginning of the list if the
1750 first argument is NULL. */
1752 static struct tracepoint *
1753 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1755 struct tracepoint *tpoint;
1757 if (prev_tp)
1758 tpoint = prev_tp->next;
1759 else
1760 tpoint = tracepoints;
1761 for (; tpoint; tpoint = tpoint->next)
1762 if (tpoint->number == num)
1763 return tpoint;
1765 return NULL;
1768 #endif
1770 /* Append another action to perform when the tracepoint triggers. */
1772 static void
1773 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1775 const char *act;
1777 if (*packet == 'S')
1779 seen_step_action_flag = 1;
1780 ++packet;
1783 act = packet;
1785 while (*act)
1787 const char *act_start = act;
1788 struct tracepoint_action *action = NULL;
1790 switch (*act)
1792 case 'M':
1794 struct collect_memory_action *maction =
1795 XNEW (struct collect_memory_action);
1796 ULONGEST basereg;
1797 int is_neg;
1799 maction->base.type = *act;
1800 action = &maction->base;
1802 ++act;
1803 is_neg = (*act == '-');
1804 if (*act == '-')
1805 ++act;
1806 act = unpack_varlen_hex (act, &basereg);
1807 ++act;
1808 act = unpack_varlen_hex (act, &maction->addr);
1809 ++act;
1810 act = unpack_varlen_hex (act, &maction->len);
1811 maction->basereg = (is_neg
1812 ? - (int) basereg
1813 : (int) basereg);
1814 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1815 pulongest (maction->len),
1816 paddress (maction->addr), maction->basereg);
1817 break;
1819 case 'R':
1821 struct collect_registers_action *raction =
1822 XNEW (struct collect_registers_action);
1824 raction->base.type = *act;
1825 action = &raction->base;
1827 trace_debug ("Want to collect registers");
1828 ++act;
1829 /* skip past hex digits of mask for now */
1830 while (isxdigit(*act))
1831 ++act;
1832 break;
1834 case 'S':
1835 trace_debug ("Unexpected step action, ignoring");
1836 ++act;
1837 break;
1838 case 'X':
1840 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1842 xaction->base.type = *act;
1843 action = &xaction->base;
1845 trace_debug ("Want to evaluate expression");
1846 xaction->expr = gdb_parse_agent_expr (&act);
1847 break;
1849 default:
1850 trace_debug ("unknown trace action '%c', ignoring...", *act);
1851 break;
1852 case '-':
1853 break;
1856 if (action == NULL)
1857 break;
1859 if (seen_step_action_flag)
1861 tpoint->num_step_actions++;
1863 tpoint->step_actions
1864 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
1865 tpoint->num_step_actions);
1866 tpoint->step_actions_str
1867 = XRESIZEVEC (char *, tpoint->step_actions_str,
1868 tpoint->num_step_actions);
1869 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
1870 tpoint->step_actions_str[tpoint->num_step_actions - 1]
1871 = savestring (act_start, act - act_start);
1873 else
1875 tpoint->numactions++;
1876 tpoint->actions
1877 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
1878 tpoint->numactions);
1879 tpoint->actions_str
1880 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
1881 tpoint->actions[tpoint->numactions - 1] = action;
1882 tpoint->actions_str[tpoint->numactions - 1]
1883 = savestring (act_start, act - act_start);
1888 #endif
1890 /* Find or create a trace state variable with the given number. */
1892 static struct trace_state_variable *
1893 get_trace_state_variable (int num)
1895 struct trace_state_variable *tsv;
1897 #ifdef IN_PROCESS_AGENT
1898 /* Search for an existing variable. */
1899 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
1900 if (tsv->number == num)
1901 return tsv;
1902 #endif
1904 /* Search for an existing variable. */
1905 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
1906 if (tsv->number == num)
1907 return tsv;
1909 return NULL;
1912 /* Find or create a trace state variable with the given number. */
1914 static struct trace_state_variable *
1915 create_trace_state_variable (int num, int gdb)
1917 struct trace_state_variable *tsv;
1919 tsv = get_trace_state_variable (num);
1920 if (tsv != NULL)
1921 return tsv;
1923 /* Create a new variable. */
1924 tsv = XNEW (struct trace_state_variable);
1925 tsv->number = num;
1926 tsv->initial_value = 0;
1927 tsv->value = 0;
1928 tsv->getter = NULL;
1929 tsv->name = NULL;
1930 #ifdef IN_PROCESS_AGENT
1931 if (!gdb)
1933 tsv->next = alloced_trace_state_variables;
1934 alloced_trace_state_variables = tsv;
1936 else
1937 #endif
1939 tsv->next = trace_state_variables;
1940 trace_state_variables = tsv;
1942 return tsv;
1945 /* This is needed for -Wmissing-declarations. */
1946 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
1948 IP_AGENT_EXPORT_FUNC LONGEST
1949 get_trace_state_variable_value (int num)
1951 struct trace_state_variable *tsv;
1953 tsv = get_trace_state_variable (num);
1955 if (!tsv)
1957 trace_debug ("No trace state variable %d, skipping value get", num);
1958 return 0;
1961 /* Call a getter function if we have one. While it's tempting to
1962 set up something to only call the getter once per tracepoint hit,
1963 it could run afoul of thread races. Better to let the getter
1964 handle it directly, if necessary to worry about it. */
1965 if (tsv->getter)
1966 tsv->value = (tsv->getter) ();
1968 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
1969 num, plongest (tsv->value));
1971 return tsv->value;
1974 /* This is needed for -Wmissing-declarations. */
1975 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
1976 LONGEST val);
1978 IP_AGENT_EXPORT_FUNC void
1979 set_trace_state_variable_value (int num, LONGEST val)
1981 struct trace_state_variable *tsv;
1983 tsv = get_trace_state_variable (num);
1985 if (!tsv)
1987 trace_debug ("No trace state variable %d, skipping value set", num);
1988 return;
1991 tsv->value = val;
1994 LONGEST
1995 agent_get_trace_state_variable_value (int num)
1997 return get_trace_state_variable_value (num);
2000 void
2001 agent_set_trace_state_variable_value (int num, LONGEST val)
2003 set_trace_state_variable_value (num, val);
2006 static void
2007 set_trace_state_variable_name (int num, const char *name)
2009 struct trace_state_variable *tsv;
2011 tsv = get_trace_state_variable (num);
2013 if (!tsv)
2015 trace_debug ("No trace state variable %d, skipping name set", num);
2016 return;
2019 tsv->name = (char *) name;
2022 static void
2023 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2025 struct trace_state_variable *tsv;
2027 tsv = get_trace_state_variable (num);
2029 if (!tsv)
2031 trace_debug ("No trace state variable %d, skipping getter set", num);
2032 return;
2035 tsv->getter = getter;
2038 /* Add a raw traceframe for the given tracepoint. */
2040 static struct traceframe *
2041 add_traceframe (struct tracepoint *tpoint)
2043 struct traceframe *tframe;
2045 tframe
2046 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2048 if (tframe == NULL)
2049 return NULL;
2051 tframe->tpnum = tpoint->number;
2052 tframe->data_size = 0;
2054 return tframe;
2057 /* Add a block to the traceframe currently being worked on. */
2059 static unsigned char *
2060 add_traceframe_block (struct traceframe *tframe,
2061 struct tracepoint *tpoint, int amt)
2063 unsigned char *block;
2065 if (!tframe)
2066 return NULL;
2068 block = (unsigned char *) trace_buffer_alloc (amt);
2070 if (!block)
2071 return NULL;
2073 gdb_assert (tframe->tpnum == tpoint->number);
2075 tframe->data_size += amt;
2076 tpoint->traceframe_usage += amt;
2078 return block;
2081 /* Flag that the current traceframe is finished. */
2083 static void
2084 finish_traceframe (struct traceframe *tframe)
2086 ++traceframe_write_count;
2087 ++traceframes_created;
2090 #ifndef IN_PROCESS_AGENT
2092 /* Given a traceframe number NUM, find the NUMth traceframe in the
2093 buffer. */
2095 static struct traceframe *
2096 find_traceframe (int num)
2098 struct traceframe *tframe;
2099 int tfnum = 0;
2101 for (tframe = FIRST_TRACEFRAME ();
2102 tframe->tpnum != 0;
2103 tframe = NEXT_TRACEFRAME (tframe))
2105 if (tfnum == num)
2106 return tframe;
2107 ++tfnum;
2110 return NULL;
2113 static CORE_ADDR
2114 get_traceframe_address (struct traceframe *tframe)
2116 CORE_ADDR addr;
2117 struct tracepoint *tpoint;
2119 addr = traceframe_get_pc (tframe);
2121 if (addr)
2122 return addr;
2124 /* Fallback strategy, will be incorrect for while-stepping frames
2125 and multi-location tracepoints. */
2126 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2127 return tpoint->address;
2130 /* Search for the next traceframe whose address is inside or outside
2131 the given range. */
2133 static struct traceframe *
2134 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2135 int *tfnump)
2137 client_state &cs = get_client_state ();
2138 struct traceframe *tframe;
2139 CORE_ADDR tfaddr;
2141 *tfnump = cs.current_traceframe + 1;
2142 tframe = find_traceframe (*tfnump);
2143 /* The search is not supposed to wrap around. */
2144 if (!tframe)
2146 *tfnump = -1;
2147 return NULL;
2150 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2152 tfaddr = get_traceframe_address (tframe);
2153 if (inside_p
2154 ? (lo <= tfaddr && tfaddr <= hi)
2155 : (lo > tfaddr || tfaddr > hi))
2156 return tframe;
2157 ++*tfnump;
2160 *tfnump = -1;
2161 return NULL;
2164 /* Search for the next traceframe recorded by the given tracepoint.
2165 Note that for multi-location tracepoints, this will find whatever
2166 location appears first. */
2168 static struct traceframe *
2169 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2171 client_state &cs = get_client_state ();
2172 struct traceframe *tframe;
2174 *tfnump = cs.current_traceframe + 1;
2175 tframe = find_traceframe (*tfnump);
2176 /* The search is not supposed to wrap around. */
2177 if (!tframe)
2179 *tfnump = -1;
2180 return NULL;
2183 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2185 if (tframe->tpnum == num)
2186 return tframe;
2187 ++*tfnump;
2190 *tfnump = -1;
2191 return NULL;
2194 #endif
2196 #ifndef IN_PROCESS_AGENT
2198 /* Clear all past trace state. */
2200 static void
2201 cmd_qtinit (char *packet)
2203 client_state &cs = get_client_state ();
2204 struct trace_state_variable *tsv, *prev, *next;
2206 /* Can't do this command without a pid attached. */
2207 if (current_thread == NULL)
2209 write_enn (packet);
2210 return;
2213 /* Make sure we don't try to read from a trace frame. */
2214 cs.current_traceframe = -1;
2216 stop_tracing ();
2218 trace_debug ("Initializing the trace");
2220 clear_installed_tracepoints ();
2221 clear_readonly_regions ();
2223 tracepoints = NULL;
2224 last_tracepoint = NULL;
2226 /* Clear out any leftover trace state variables. Ones with target
2227 defined getters should be kept however. */
2228 prev = NULL;
2229 tsv = trace_state_variables;
2230 while (tsv)
2232 trace_debug ("Looking at var %d", tsv->number);
2233 if (tsv->getter == NULL)
2235 next = tsv->next;
2236 if (prev)
2237 prev->next = next;
2238 else
2239 trace_state_variables = next;
2240 trace_debug ("Deleting var %d", tsv->number);
2241 free (tsv);
2242 tsv = next;
2244 else
2246 prev = tsv;
2247 tsv = tsv->next;
2251 clear_trace_buffer ();
2252 clear_inferior_trace_buffer ();
2254 write_ok (packet);
2257 /* Restore the program to its pre-tracing state. This routine may be called
2258 in error situations, so it needs to be careful about only restoring
2259 from known-valid bits. */
2261 static void
2262 clear_installed_tracepoints (void)
2264 struct tracepoint *tpoint;
2266 target_pause_all (true);
2268 /* Restore any bytes overwritten by tracepoints. */
2269 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2271 /* Catch the case where we might try to remove a tracepoint that
2272 was never actually installed. */
2273 if (tpoint->handle == NULL)
2275 trace_debug ("Tracepoint %d at 0x%s was "
2276 "never installed, nothing to clear",
2277 tpoint->number, paddress (tpoint->address));
2278 continue;
2281 switch (tpoint->type)
2283 case trap_tracepoint:
2285 struct breakpoint *bp
2286 = (struct breakpoint *) tpoint->handle;
2288 delete_breakpoint (bp);
2290 break;
2291 case fast_tracepoint:
2293 struct fast_tracepoint_jump *jump
2294 = (struct fast_tracepoint_jump *) tpoint->handle;
2296 delete_fast_tracepoint_jump (jump);
2298 break;
2301 tpoint->handle = NULL;
2304 target_unpause_all (true);
2307 /* Parse a packet that defines a tracepoint. */
2309 static void
2310 cmd_qtdp (char *own_buf)
2312 int tppacket;
2313 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2314 int trail_hyphen = 0;
2315 ULONGEST num;
2316 ULONGEST addr;
2317 ULONGEST count;
2318 struct tracepoint *tpoint;
2319 const char *packet = own_buf;
2321 packet += strlen ("QTDP:");
2323 /* A hyphen at the beginning marks a packet specifying actions for a
2324 tracepoint already supplied. */
2325 tppacket = 1;
2326 if (*packet == '-')
2328 tppacket = 0;
2329 ++packet;
2331 packet = unpack_varlen_hex (packet, &num);
2332 ++packet; /* skip a colon */
2333 packet = unpack_varlen_hex (packet, &addr);
2334 ++packet; /* skip a colon */
2336 /* See if we already have this tracepoint. */
2337 tpoint = find_tracepoint (num, addr);
2339 if (tppacket)
2341 /* Duplicate tracepoints are never allowed. */
2342 if (tpoint)
2344 trace_debug ("Tracepoint error: tracepoint %d"
2345 " at 0x%s already exists",
2346 (int) num, paddress (addr));
2347 write_enn (own_buf);
2348 return;
2351 tpoint = add_tracepoint (num, addr);
2353 tpoint->enabled = (*packet == 'E');
2354 ++packet; /* skip 'E' */
2355 ++packet; /* skip a colon */
2356 packet = unpack_varlen_hex (packet, &count);
2357 tpoint->step_count = count;
2358 ++packet; /* skip a colon */
2359 packet = unpack_varlen_hex (packet, &count);
2360 tpoint->pass_count = count;
2361 /* See if we have any of the additional optional fields. */
2362 while (*packet == ':')
2364 ++packet;
2365 if (*packet == 'F')
2367 tpoint->type = fast_tracepoint;
2368 ++packet;
2369 packet = unpack_varlen_hex (packet, &count);
2370 tpoint->orig_size = count;
2372 else if (*packet == 'X')
2374 tpoint->cond = gdb_parse_agent_expr (&packet);
2376 else if (*packet == '-')
2377 break;
2378 else if (*packet == '\0')
2379 break;
2380 else
2381 trace_debug ("Unknown optional tracepoint field");
2383 if (*packet == '-')
2385 trail_hyphen = 1;
2386 trace_debug ("Also has actions\n");
2389 trace_debug ("Defined %stracepoint %d at 0x%s, "
2390 "enabled %d step %" PRIu64 " pass %" PRIu64,
2391 tpoint->type == fast_tracepoint ? "fast " : "",
2392 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2393 tpoint->step_count, tpoint->pass_count);
2395 else if (tpoint)
2396 add_tracepoint_action (tpoint, packet);
2397 else
2399 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2400 (int) num, paddress (addr));
2401 write_enn (own_buf);
2402 return;
2405 /* Install tracepoint during tracing only once for each tracepoint location.
2406 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2407 determine the last QTDP packet for one tracepoint location by checking
2408 trailing hyphen in QTDP packet. */
2409 if (tracing && !trail_hyphen)
2411 struct tracepoint *tp = NULL;
2413 /* Pause all threads temporarily while we patch tracepoints. */
2414 target_pause_all (false);
2416 /* download_tracepoint will update global `tracepoints'
2417 list, so it is unsafe to leave threads in jump pad. */
2418 target_stabilize_threads ();
2420 /* Freeze threads. */
2421 target_pause_all (true);
2424 if (tpoint->type != trap_tracepoint)
2426 /* Find another fast tracepoint at the same address. */
2427 for (tp = tracepoints; tp; tp = tp->next)
2429 if (tp->address == tpoint->address && tp->type == tpoint->type
2430 && tp->number != tpoint->number)
2431 break;
2434 /* TPOINT is installed at the same address as TP. */
2435 if (tp)
2437 if (tpoint->type == fast_tracepoint)
2438 clone_fast_tracepoint (tpoint, tp);
2442 if (use_agent && tpoint->type == fast_tracepoint
2443 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2445 /* Download and install fast tracepoint by agent. */
2446 if (tracepoint_send_agent (tpoint) == 0)
2447 write_ok (own_buf);
2448 else
2450 write_enn (own_buf);
2451 remove_tracepoint (tpoint);
2454 else
2456 download_tracepoint (tpoint);
2458 if (tpoint->type == trap_tracepoint || tp == NULL)
2460 install_tracepoint (tpoint, own_buf);
2461 if (strcmp (own_buf, "OK") != 0)
2462 remove_tracepoint (tpoint);
2464 else
2465 write_ok (own_buf);
2468 target_unpause_all (true);
2469 return;
2472 write_ok (own_buf);
2475 static void
2476 cmd_qtdpsrc (char *own_buf)
2478 ULONGEST num, addr, start, slen;
2479 struct tracepoint *tpoint;
2480 const char *packet = own_buf;
2481 const char *saved;
2482 char *srctype, *src;
2483 size_t nbytes;
2484 struct source_string *last, *newlast;
2486 packet += strlen ("QTDPsrc:");
2488 packet = unpack_varlen_hex (packet, &num);
2489 ++packet; /* skip a colon */
2490 packet = unpack_varlen_hex (packet, &addr);
2491 ++packet; /* skip a colon */
2493 /* See if we already have this tracepoint. */
2494 tpoint = find_tracepoint (num, addr);
2496 if (!tpoint)
2498 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2499 (int) num, paddress (addr));
2500 write_enn (own_buf);
2501 return;
2504 saved = packet;
2505 packet = strchr (packet, ':');
2506 srctype = (char *) xmalloc (packet - saved + 1);
2507 memcpy (srctype, saved, packet - saved);
2508 srctype[packet - saved] = '\0';
2509 ++packet;
2510 packet = unpack_varlen_hex (packet, &start);
2511 ++packet; /* skip a colon */
2512 packet = unpack_varlen_hex (packet, &slen);
2513 ++packet; /* skip a colon */
2514 src = (char *) xmalloc (slen + 1);
2515 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2516 src[nbytes] = '\0';
2518 newlast = XNEW (struct source_string);
2519 newlast->type = srctype;
2520 newlast->str = src;
2521 newlast->next = NULL;
2522 /* Always add a source string to the end of the list;
2523 this keeps sequences of actions/commands in the right
2524 order. */
2525 if (tpoint->source_strings)
2527 for (last = tpoint->source_strings; last->next; last = last->next)
2529 last->next = newlast;
2531 else
2532 tpoint->source_strings = newlast;
2534 write_ok (own_buf);
2537 static void
2538 cmd_qtdv (char *own_buf)
2540 ULONGEST num, val, builtin;
2541 char *varname;
2542 size_t nbytes;
2543 struct trace_state_variable *tsv;
2544 const char *packet = own_buf;
2546 packet += strlen ("QTDV:");
2548 packet = unpack_varlen_hex (packet, &num);
2549 ++packet; /* skip a colon */
2550 packet = unpack_varlen_hex (packet, &val);
2551 ++packet; /* skip a colon */
2552 packet = unpack_varlen_hex (packet, &builtin);
2553 ++packet; /* skip a colon */
2555 nbytes = strlen (packet) / 2;
2556 varname = (char *) xmalloc (nbytes + 1);
2557 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2558 varname[nbytes] = '\0';
2560 tsv = create_trace_state_variable (num, 1);
2561 tsv->initial_value = (LONGEST) val;
2562 tsv->name = varname;
2564 set_trace_state_variable_value (num, (LONGEST) val);
2566 write_ok (own_buf);
2569 static void
2570 cmd_qtenable_disable (char *own_buf, int enable)
2572 const char *packet = own_buf;
2573 ULONGEST num, addr;
2574 struct tracepoint *tp;
2576 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2577 packet = unpack_varlen_hex (packet, &num);
2578 ++packet; /* skip a colon */
2579 packet = unpack_varlen_hex (packet, &addr);
2581 tp = find_tracepoint (num, addr);
2583 if (tp)
2585 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2587 trace_debug ("Tracepoint %d at 0x%s is already %s",
2588 (int) num, paddress (addr),
2589 enable ? "enabled" : "disabled");
2590 write_ok (own_buf);
2591 return;
2594 trace_debug ("%s tracepoint %d at 0x%s",
2595 enable ? "Enabling" : "Disabling",
2596 (int) num, paddress (addr));
2598 tp->enabled = enable;
2600 if (tp->type == fast_tracepoint)
2602 int offset = offsetof (struct tracepoint, enabled);
2603 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2605 int ret = write_inferior_int8 (obj_addr, enable);
2606 if (ret)
2608 trace_debug ("Cannot write enabled flag into "
2609 "inferior process memory");
2610 write_enn (own_buf);
2611 return;
2615 write_ok (own_buf);
2617 else
2619 trace_debug ("Tracepoint %d at 0x%s not found",
2620 (int) num, paddress (addr));
2621 write_enn (own_buf);
2625 static void
2626 cmd_qtv (char *own_buf)
2628 client_state &cs = get_client_state ();
2629 ULONGEST num;
2630 LONGEST val = 0;
2631 int err;
2632 char *packet = own_buf;
2634 packet += strlen ("qTV:");
2635 unpack_varlen_hex (packet, &num);
2637 if (cs.current_traceframe >= 0)
2639 err = traceframe_read_tsv ((int) num, &val);
2640 if (err)
2642 strcpy (own_buf, "U");
2643 return;
2646 /* Only make tsv's be undefined before the first trace run. After a
2647 trace run is over, the user might want to see the last value of
2648 the tsv, and it might not be available in a traceframe. */
2649 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2651 strcpy (own_buf, "U");
2652 return;
2654 else
2655 val = get_trace_state_variable_value (num);
2657 sprintf (own_buf, "V%s", phex_nz (val, 0));
2660 /* Clear out the list of readonly regions. */
2662 static void
2663 clear_readonly_regions (void)
2665 struct readonly_region *roreg;
2667 while (readonly_regions)
2669 roreg = readonly_regions;
2670 readonly_regions = readonly_regions->next;
2671 free (roreg);
2675 /* Parse the collection of address ranges whose contents GDB believes
2676 to be unchanging and so can be read directly from target memory
2677 even while looking at a traceframe. */
2679 static void
2680 cmd_qtro (char *own_buf)
2682 ULONGEST start, end;
2683 struct readonly_region *roreg;
2684 const char *packet = own_buf;
2686 trace_debug ("Want to mark readonly regions");
2688 clear_readonly_regions ();
2690 packet += strlen ("QTro");
2692 while (*packet == ':')
2694 ++packet; /* skip a colon */
2695 packet = unpack_varlen_hex (packet, &start);
2696 ++packet; /* skip a comma */
2697 packet = unpack_varlen_hex (packet, &end);
2699 roreg = XNEW (struct readonly_region);
2700 roreg->start = start;
2701 roreg->end = end;
2702 roreg->next = readonly_regions;
2703 readonly_regions = roreg;
2704 trace_debug ("Added readonly region from 0x%s to 0x%s",
2705 paddress (roreg->start), paddress (roreg->end));
2708 write_ok (own_buf);
2711 /* Test to see if the given range is in our list of readonly ranges.
2712 We only test for being entirely within a range, GDB is not going to
2713 send a single memory packet that spans multiple regions. */
2716 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2718 struct readonly_region *roreg;
2720 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2721 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2722 return 1;
2724 return 0;
2727 static CORE_ADDR gdb_jump_pad_head;
2729 /* Return the address of the next free jump space. */
2731 static CORE_ADDR
2732 get_jump_space_head (void)
2734 if (gdb_jump_pad_head == 0)
2736 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2737 &gdb_jump_pad_head))
2739 internal_error ("error extracting jump_pad_buffer");
2743 return gdb_jump_pad_head;
2746 /* Reserve USED bytes from the jump space. */
2748 static void
2749 claim_jump_space (ULONGEST used)
2751 trace_debug ("claim_jump_space reserves %s bytes at %s",
2752 pulongest (used), paddress (gdb_jump_pad_head));
2753 gdb_jump_pad_head += used;
2756 static CORE_ADDR trampoline_buffer_head = 0;
2757 static CORE_ADDR trampoline_buffer_tail;
2759 /* Reserve USED bytes from the trampoline buffer and return the
2760 address of the start of the reserved space in TRAMPOLINE. Returns
2761 non-zero if the space is successfully claimed. */
2764 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2766 if (!trampoline_buffer_head)
2768 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2769 &trampoline_buffer_tail))
2771 internal_error ("error extracting trampoline_buffer");
2774 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2775 &trampoline_buffer_head))
2777 internal_error ("error extracting trampoline_buffer_end");
2781 /* Start claiming space from the top of the trampoline space. If
2782 the space is located at the bottom of the virtual address space,
2783 this reduces the possibility that corruption will occur if a null
2784 pointer is used to write to memory. */
2785 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2787 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2788 pulongest (used));
2789 return 0;
2792 trampoline_buffer_head -= used;
2794 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2795 pulongest (used), paddress (trampoline_buffer_head));
2797 *trampoline = trampoline_buffer_head;
2798 return 1;
2801 /* Returns non-zero if there is space allocated for use in trampolines
2802 for fast tracepoints. */
2805 have_fast_tracepoint_trampoline_buffer (char *buf)
2807 CORE_ADDR trampoline_end, errbuf;
2809 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2810 &trampoline_end))
2812 internal_error ("error extracting trampoline_buffer_end");
2815 if (buf)
2817 buf[0] = '\0';
2818 strcpy (buf, "was claiming");
2819 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
2820 &errbuf))
2822 internal_error ("error extracting errbuf");
2825 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
2828 return trampoline_end != 0;
2831 static void
2832 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
2834 to->jump_pad = from->jump_pad;
2835 to->jump_pad_end = from->jump_pad_end;
2836 to->trampoline = from->trampoline;
2837 to->trampoline_end = from->trampoline_end;
2838 to->adjusted_insn_addr = from->adjusted_insn_addr;
2839 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
2840 to->handle = from->handle;
2842 gdb_assert (from->handle);
2843 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
2846 #define MAX_JUMP_SIZE 20
2848 /* Install fast tracepoint. Return 0 if successful, otherwise return
2849 non-zero. */
2851 static int
2852 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
2854 CORE_ADDR jentry, jump_entry;
2855 CORE_ADDR trampoline;
2856 CORE_ADDR collect;
2857 ULONGEST trampoline_size;
2858 int err = 0;
2859 /* The jump to the jump pad of the last fast tracepoint
2860 installed. */
2861 unsigned char fjump[MAX_JUMP_SIZE];
2862 ULONGEST fjump_size;
2864 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
2866 trace_debug ("Requested a fast tracepoint on an instruction "
2867 "that is of less than the minimum length.");
2868 return 0;
2871 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
2872 &collect))
2874 error ("error extracting gdb_collect_ptr");
2875 return 1;
2878 jentry = jump_entry = get_jump_space_head ();
2880 trampoline = 0;
2881 trampoline_size = 0;
2883 /* Install the jump pad. */
2884 err = target_install_fast_tracepoint_jump_pad
2885 (tpoint->obj_addr_on_target, tpoint->address, collect,
2886 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
2887 &trampoline, &trampoline_size, fjump, &fjump_size,
2888 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
2890 if (err)
2891 return 1;
2893 /* Wire it in. */
2894 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
2895 fjump_size);
2897 if (tpoint->handle != NULL)
2899 tpoint->jump_pad = jump_entry;
2900 tpoint->jump_pad_end = jentry;
2901 tpoint->trampoline = trampoline;
2902 tpoint->trampoline_end = trampoline + trampoline_size;
2904 /* Pad to 8-byte alignment. */
2905 jentry = ((jentry + 7) & ~0x7);
2906 claim_jump_space (jentry - jump_entry);
2909 return 0;
2913 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
2915 static void
2916 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
2918 tpoint->handle = NULL;
2919 *own_buf = '\0';
2921 if (tpoint->type == trap_tracepoint)
2923 /* Tracepoints are installed as memory breakpoints. Just go
2924 ahead and install the trap. The breakpoints module
2925 handles duplicated breakpoints, and the memory read
2926 routine handles un-patching traps from memory reads. */
2927 tpoint->handle = set_breakpoint_at (tpoint->address,
2928 tracepoint_handler);
2930 else if (tpoint->type == fast_tracepoint)
2932 if (!agent_loaded_p ())
2934 trace_debug ("Requested a fast tracepoint, but fast "
2935 "tracepoints aren't supported.");
2936 write_e_ipa_not_loaded (own_buf);
2937 return;
2940 install_fast_tracepoint (tpoint, own_buf);
2942 else
2943 internal_error ("Unknown tracepoint type");
2945 if (tpoint->handle == NULL)
2947 if (*own_buf == '\0')
2948 write_enn (own_buf);
2950 else
2951 write_ok (own_buf);
2954 static void download_tracepoint_1 (struct tracepoint *tpoint);
2956 static void
2957 cmd_qtstart (char *packet)
2959 struct tracepoint *tpoint, *prev_ftpoint;
2960 CORE_ADDR tpptr = 0, prev_tpptr = 0;
2962 trace_debug ("Starting the trace");
2964 /* Pause all threads temporarily while we patch tracepoints. */
2965 target_pause_all (false);
2967 /* Get threads out of jump pads. Safe to do here, since this is a
2968 top level command. And, required to do here, since we're
2969 deleting/rewriting jump pads. */
2971 target_stabilize_threads ();
2973 /* Freeze threads. */
2974 target_pause_all (true);
2976 /* Sync the fast tracepoints list in the inferior ftlib. */
2977 if (agent_loaded_p ())
2978 download_trace_state_variables ();
2980 /* No previous fast tpoint yet. */
2981 prev_ftpoint = NULL;
2983 *packet = '\0';
2985 if (agent_loaded_p ())
2987 /* Tell IPA about the correct tdesc. */
2988 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
2989 target_get_ipa_tdesc_idx ()))
2990 error ("Error setting ipa_tdesc_idx variable in lib");
2993 /* Start out empty. */
2994 if (agent_loaded_p ())
2995 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
2997 /* Download and install tracepoints. */
2998 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3000 /* Ensure all the hit counts start at zero. */
3001 tpoint->hit_count = 0;
3002 tpoint->traceframe_usage = 0;
3004 if (tpoint->type == trap_tracepoint)
3006 /* Tracepoints are installed as memory breakpoints. Just go
3007 ahead and install the trap. The breakpoints module
3008 handles duplicated breakpoints, and the memory read
3009 routine handles un-patching traps from memory reads. */
3010 tpoint->handle = set_breakpoint_at (tpoint->address,
3011 tracepoint_handler);
3013 else if (tpoint->type == fast_tracepoint)
3015 if (maybe_write_ipa_not_loaded (packet))
3017 trace_debug ("Requested a fast tracepoint, but fast "
3018 "tracepoints aren't supported.");
3019 break;
3022 int use_agent_p
3023 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3025 if (prev_ftpoint != NULL
3026 && prev_ftpoint->address == tpoint->address)
3028 if (use_agent_p)
3029 tracepoint_send_agent (tpoint);
3030 else
3031 download_tracepoint_1 (tpoint);
3033 clone_fast_tracepoint (tpoint, prev_ftpoint);
3035 else
3037 /* Tracepoint is installed successfully? */
3038 int installed = 0;
3040 /* Download and install fast tracepoint by agent. */
3041 if (use_agent_p)
3042 installed = !tracepoint_send_agent (tpoint);
3043 else
3045 download_tracepoint_1 (tpoint);
3046 installed = !install_fast_tracepoint (tpoint, packet);
3049 if (installed)
3050 prev_ftpoint = tpoint;
3053 prev_tpptr = tpptr;
3054 tpptr = tpoint->obj_addr_on_target;
3056 if (tpoint == tracepoints)
3057 /* First object in list, set the head pointer in the
3058 inferior. */
3059 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3060 else
3061 write_inferior_data_pointer (prev_tpptr
3062 + offsetof (struct tracepoint, next),
3063 tpptr);
3066 /* Any failure in the inner loop is sufficient cause to give
3067 up. */
3068 if (tpoint->handle == NULL)
3069 break;
3072 /* Any error in tracepoint insertion is unacceptable; better to
3073 address the problem now, than end up with a useless or misleading
3074 trace run. */
3075 if (tpoint != NULL)
3077 clear_installed_tracepoints ();
3078 if (*packet == '\0')
3079 write_enn (packet);
3080 target_unpause_all (true);
3081 return;
3084 stopping_tracepoint = NULL;
3085 trace_buffer_is_full = 0;
3086 expr_eval_result = expr_eval_no_error;
3087 error_tracepoint = NULL;
3088 tracing_start_time = get_timestamp ();
3090 /* Tracing is now active, hits will now start being logged. */
3091 tracing = 1;
3093 if (agent_loaded_p ())
3095 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3097 internal_error ("Error setting tracing variable in lib");
3100 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3103 internal_error ("Error clearing stopping_tracepoint variable"
3104 " in lib");
3107 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3109 internal_error ("Error clearing trace_buffer_is_full variable"
3110 " in lib");
3113 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3114 stop_tracing_handler);
3115 if (stop_tracing_bkpt == NULL)
3116 error ("Error setting stop_tracing breakpoint");
3118 flush_trace_buffer_bkpt
3119 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3120 flush_trace_buffer_handler);
3121 if (flush_trace_buffer_bkpt == NULL)
3122 error ("Error setting flush_trace_buffer breakpoint");
3125 target_unpause_all (true);
3127 write_ok (packet);
3130 /* End a tracing run, filling in a stop reason to report back to GDB,
3131 and removing the tracepoints from the code. */
3133 void
3134 stop_tracing (void)
3136 if (!tracing)
3138 trace_debug ("Tracing is already off, ignoring");
3139 return;
3142 trace_debug ("Stopping the trace");
3144 /* Pause all threads before removing fast jumps from memory,
3145 breakpoints, and touching IPA state variables (inferior memory).
3146 Some thread may hit the internal tracing breakpoints, or be
3147 collecting this moment, but that's ok, we don't release the
3148 tpoint object's memory or the jump pads here (we only do that
3149 when we're sure we can move all threads out of the jump pads).
3150 We can't now, since we may be getting here due to the inferior
3151 agent calling us. */
3152 target_pause_all (true);
3154 /* Stop logging. Tracepoints can still be hit, but they will not be
3155 recorded. */
3156 tracing = 0;
3157 if (agent_loaded_p ())
3159 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3161 internal_error ("Error clearing tracing variable in lib");
3165 tracing_stop_time = get_timestamp ();
3166 tracing_stop_reason = "t???";
3167 tracing_stop_tpnum = 0;
3168 if (stopping_tracepoint)
3170 trace_debug ("Stopping the trace because "
3171 "tracepoint %d was hit %" PRIu64 " times",
3172 stopping_tracepoint->number,
3173 stopping_tracepoint->pass_count);
3174 tracing_stop_reason = "tpasscount";
3175 tracing_stop_tpnum = stopping_tracepoint->number;
3177 else if (trace_buffer_is_full)
3179 trace_debug ("Stopping the trace because the trace buffer is full");
3180 tracing_stop_reason = "tfull";
3182 else if (expr_eval_result != expr_eval_no_error)
3184 trace_debug ("Stopping the trace because of an expression eval error");
3185 tracing_stop_reason = eval_result_names[expr_eval_result];
3186 tracing_stop_tpnum = error_tracepoint->number;
3188 #ifndef IN_PROCESS_AGENT
3189 else if (!gdb_connected ())
3191 trace_debug ("Stopping the trace because GDB disconnected");
3192 tracing_stop_reason = "tdisconnected";
3194 #endif
3195 else
3197 trace_debug ("Stopping the trace because of a tstop command");
3198 tracing_stop_reason = "tstop";
3201 stopping_tracepoint = NULL;
3202 error_tracepoint = NULL;
3204 /* Clear out the tracepoints. */
3205 clear_installed_tracepoints ();
3207 if (agent_loaded_p ())
3209 /* Pull in fast tracepoint trace frames from the inferior lib
3210 buffer into our buffer, even if our buffer is already full,
3211 because we want to present the full number of created frames
3212 in addition to what fit in the trace buffer. */
3213 upload_fast_traceframes ();
3216 if (stop_tracing_bkpt != NULL)
3218 delete_breakpoint (stop_tracing_bkpt);
3219 stop_tracing_bkpt = NULL;
3222 if (flush_trace_buffer_bkpt != NULL)
3224 delete_breakpoint (flush_trace_buffer_bkpt);
3225 flush_trace_buffer_bkpt = NULL;
3228 target_unpause_all (true);
3231 static int
3232 stop_tracing_handler (CORE_ADDR addr)
3234 trace_debug ("lib hit stop_tracing");
3236 /* Don't actually handle it here. When we stop tracing we remove
3237 breakpoints from the inferior, and that is not allowed in a
3238 breakpoint handler (as the caller is walking the breakpoint
3239 list). */
3240 return 0;
3243 static int
3244 flush_trace_buffer_handler (CORE_ADDR addr)
3246 trace_debug ("lib hit flush_trace_buffer");
3247 return 0;
3250 static void
3251 cmd_qtstop (char *packet)
3253 stop_tracing ();
3254 write_ok (packet);
3257 static void
3258 cmd_qtdisconnected (char *own_buf)
3260 ULONGEST setting;
3261 char *packet = own_buf;
3263 packet += strlen ("QTDisconnected:");
3265 unpack_varlen_hex (packet, &setting);
3267 write_ok (own_buf);
3269 disconnected_tracing = setting;
3272 static void
3273 cmd_qtframe (char *own_buf)
3275 client_state &cs = get_client_state ();
3276 ULONGEST frame, pc, lo, hi, num;
3277 int tfnum, tpnum;
3278 struct traceframe *tframe;
3279 const char *packet = own_buf;
3281 packet += strlen ("QTFrame:");
3283 if (startswith (packet, "pc:"))
3285 packet += strlen ("pc:");
3286 unpack_varlen_hex (packet, &pc);
3287 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3288 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3290 else if (startswith (packet, "range:"))
3292 packet += strlen ("range:");
3293 packet = unpack_varlen_hex (packet, &lo);
3294 ++packet;
3295 unpack_varlen_hex (packet, &hi);
3296 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3297 paddress (lo), paddress (hi));
3298 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3300 else if (startswith (packet, "outside:"))
3302 packet += strlen ("outside:");
3303 packet = unpack_varlen_hex (packet, &lo);
3304 ++packet;
3305 unpack_varlen_hex (packet, &hi);
3306 trace_debug ("Want to find next traceframe "
3307 "outside the range 0x%s to 0x%s",
3308 paddress (lo), paddress (hi));
3309 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3311 else if (startswith (packet, "tdp:"))
3313 packet += strlen ("tdp:");
3314 unpack_varlen_hex (packet, &num);
3315 tpnum = (int) num;
3316 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3317 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3319 else
3321 unpack_varlen_hex (packet, &frame);
3322 tfnum = (int) frame;
3323 if (tfnum == -1)
3325 trace_debug ("Want to stop looking at traceframes");
3326 cs.current_traceframe = -1;
3327 write_ok (own_buf);
3328 return;
3330 trace_debug ("Want to look at traceframe %d", tfnum);
3331 tframe = find_traceframe (tfnum);
3334 if (tframe)
3336 cs.current_traceframe = tfnum;
3337 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3339 else
3340 sprintf (own_buf, "F-1");
3343 static void
3344 cmd_qtstatus (char *packet)
3346 char *stop_reason_rsp = NULL;
3347 char *buf1, *buf2, *buf3;
3348 const char *str;
3349 int slen;
3351 /* Translate the plain text of the notes back into hex for
3352 transmission. */
3354 str = (tracing_user_name ? tracing_user_name : "");
3355 slen = strlen (str);
3356 buf1 = (char *) alloca (slen * 2 + 1);
3357 bin2hex ((gdb_byte *) str, buf1, slen);
3359 str = (tracing_notes ? tracing_notes : "");
3360 slen = strlen (str);
3361 buf2 = (char *) alloca (slen * 2 + 1);
3362 bin2hex ((gdb_byte *) str, buf2, slen);
3364 str = (tracing_stop_note ? tracing_stop_note : "");
3365 slen = strlen (str);
3366 buf3 = (char *) alloca (slen * 2 + 1);
3367 bin2hex ((gdb_byte *) str, buf3, slen);
3369 trace_debug ("Returning trace status as %d, stop reason %s",
3370 tracing, tracing_stop_reason);
3372 if (agent_loaded_p ())
3374 target_pause_all (true);
3376 upload_fast_traceframes ();
3378 target_unpause_all (true);
3381 stop_reason_rsp = (char *) tracing_stop_reason;
3383 /* The user visible error string in terror needs to be hex encoded.
3384 We leave it as plain string in `tracing_stop_reason' to ease
3385 debugging. */
3386 if (startswith (stop_reason_rsp, "terror:"))
3388 const char *result_name;
3389 int hexstr_len;
3390 char *p;
3392 result_name = stop_reason_rsp + strlen ("terror:");
3393 hexstr_len = strlen (result_name) * 2;
3394 p = stop_reason_rsp
3395 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3396 strcpy (p, "terror:");
3397 p += strlen (p);
3398 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3401 /* If this was a forced stop, include any stop note that was supplied. */
3402 if (strcmp (stop_reason_rsp, "tstop") == 0)
3404 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3405 strcpy (stop_reason_rsp, "tstop:");
3406 strcat (stop_reason_rsp, buf3);
3409 sprintf (packet,
3410 "T%d;"
3411 "%s:%x;"
3412 "tframes:%x;tcreated:%x;"
3413 "tfree:%x;tsize:%s;"
3414 "circular:%d;"
3415 "disconn:%d;"
3416 "starttime:%s;stoptime:%s;"
3417 "username:%s;notes:%s:",
3418 tracing ? 1 : 0,
3419 stop_reason_rsp, tracing_stop_tpnum,
3420 traceframe_count, traceframes_created,
3421 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3422 circular_trace_buffer,
3423 disconnected_tracing,
3424 phex_nz (tracing_start_time, sizeof (tracing_start_time)),
3425 phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
3426 buf1, buf2);
3429 static void
3430 cmd_qtp (char *own_buf)
3432 ULONGEST num, addr;
3433 struct tracepoint *tpoint;
3434 const char *packet = own_buf;
3436 packet += strlen ("qTP:");
3438 packet = unpack_varlen_hex (packet, &num);
3439 ++packet; /* skip a colon */
3440 packet = unpack_varlen_hex (packet, &addr);
3442 /* See if we already have this tracepoint. */
3443 tpoint = find_tracepoint (num, addr);
3445 if (!tpoint)
3447 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3448 (int) num, paddress (addr));
3449 write_enn (own_buf);
3450 return;
3453 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3454 tpoint->traceframe_usage);
3457 /* State variables to help return all the tracepoint bits. */
3458 static struct tracepoint *cur_tpoint;
3459 static unsigned int cur_action;
3460 static unsigned int cur_step_action;
3461 static struct source_string *cur_source_string;
3462 static struct trace_state_variable *cur_tsv;
3464 /* Compose a response that is an imitation of the syntax by which the
3465 tracepoint was originally downloaded. */
3467 static void
3468 response_tracepoint (char *packet, struct tracepoint *tpoint)
3470 char *buf;
3472 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3473 paddress (tpoint->address),
3474 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3475 tpoint->pass_count);
3476 if (tpoint->type == fast_tracepoint)
3477 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3479 if (tpoint->cond)
3481 buf = gdb_unparse_agent_expr (tpoint->cond);
3482 sprintf (packet + strlen (packet), ":X%x,%s",
3483 tpoint->cond->length, buf);
3484 free (buf);
3488 /* Compose a response that is an imitation of the syntax by which the
3489 tracepoint action was originally downloaded (with the difference
3490 that due to the way we store the actions, this will output a packet
3491 per action, while GDB could have combined more than one action
3492 per-packet. */
3494 static void
3495 response_action (char *packet, struct tracepoint *tpoint,
3496 char *taction, int step)
3498 sprintf (packet, "%c%x:%s:%s",
3499 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3500 taction);
3503 /* Compose a response that is an imitation of the syntax by which the
3504 tracepoint source piece was originally downloaded. */
3506 static void
3507 response_source (char *packet,
3508 struct tracepoint *tpoint, struct source_string *src)
3510 char *buf;
3511 int len;
3513 len = strlen (src->str);
3514 buf = (char *) alloca (len * 2 + 1);
3515 bin2hex ((gdb_byte *) src->str, buf, len);
3517 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3518 tpoint->number, paddress (tpoint->address),
3519 src->type, 0, len, buf);
3522 /* Return the first piece of tracepoint definition, and initialize the
3523 state machine that will iterate through all the tracepoint
3524 bits. */
3526 static void
3527 cmd_qtfp (char *packet)
3529 trace_debug ("Returning first tracepoint definition piece");
3531 cur_tpoint = tracepoints;
3532 cur_action = cur_step_action = 0;
3533 cur_source_string = NULL;
3535 if (cur_tpoint)
3536 response_tracepoint (packet, cur_tpoint);
3537 else
3538 strcpy (packet, "l");
3541 /* Return additional pieces of tracepoint definition. Each action and
3542 stepping action must go into its own packet, because of packet size
3543 limits, and so we use state variables to deliver one piece at a
3544 time. */
3546 static void
3547 cmd_qtsp (char *packet)
3549 trace_debug ("Returning subsequent tracepoint definition piece");
3551 if (!cur_tpoint)
3553 /* This case would normally never occur, but be prepared for
3554 GDB misbehavior. */
3555 strcpy (packet, "l");
3557 else if (cur_action < cur_tpoint->numactions)
3559 response_action (packet, cur_tpoint,
3560 cur_tpoint->actions_str[cur_action], 0);
3561 ++cur_action;
3563 else if (cur_step_action < cur_tpoint->num_step_actions)
3565 response_action (packet, cur_tpoint,
3566 cur_tpoint->step_actions_str[cur_step_action], 1);
3567 ++cur_step_action;
3569 else if ((cur_source_string
3570 ? cur_source_string->next
3571 : cur_tpoint->source_strings))
3573 if (cur_source_string)
3574 cur_source_string = cur_source_string->next;
3575 else
3576 cur_source_string = cur_tpoint->source_strings;
3577 response_source (packet, cur_tpoint, cur_source_string);
3579 else
3581 cur_tpoint = cur_tpoint->next;
3582 cur_action = cur_step_action = 0;
3583 cur_source_string = NULL;
3584 if (cur_tpoint)
3585 response_tracepoint (packet, cur_tpoint);
3586 else
3587 strcpy (packet, "l");
3591 /* Compose a response that is an imitation of the syntax by which the
3592 trace state variable was originally downloaded. */
3594 static void
3595 response_tsv (char *packet, struct trace_state_variable *tsv)
3597 char *buf = (char *) "";
3598 int namelen;
3600 if (tsv->name)
3602 namelen = strlen (tsv->name);
3603 buf = (char *) alloca (namelen * 2 + 1);
3604 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3607 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3608 tsv->getter ? 1 : 0, buf);
3611 /* Return the first trace state variable definition, and initialize
3612 the state machine that will iterate through all the tsv bits. */
3614 static void
3615 cmd_qtfv (char *packet)
3617 trace_debug ("Returning first trace state variable definition");
3619 cur_tsv = trace_state_variables;
3621 if (cur_tsv)
3622 response_tsv (packet, cur_tsv);
3623 else
3624 strcpy (packet, "l");
3627 /* Return additional trace state variable definitions. */
3629 static void
3630 cmd_qtsv (char *packet)
3632 trace_debug ("Returning additional trace state variable definition");
3634 if (cur_tsv)
3636 cur_tsv = cur_tsv->next;
3637 if (cur_tsv)
3638 response_tsv (packet, cur_tsv);
3639 else
3640 strcpy (packet, "l");
3642 else
3643 strcpy (packet, "l");
3646 /* Sent the agent a command to close it. */
3648 void
3649 gdb_agent_about_to_close (int pid)
3651 char buf[IPA_CMD_BUF_SIZE];
3653 if (!maybe_write_ipa_not_loaded (buf))
3655 scoped_restore_current_thread restore_thread;
3657 /* Find any thread which belongs to process PID. */
3658 switch_to_thread (find_any_thread_of_pid (pid));
3660 strcpy (buf, "close");
3662 run_inferior_command (buf, strlen (buf) + 1);
3666 /* Return the minimum instruction size needed for fast tracepoints as a
3667 hexadecimal number. */
3669 static void
3670 cmd_qtminftpilen (char *packet)
3672 if (current_thread == NULL)
3674 /* Indicate that the minimum length is currently unknown. */
3675 strcpy (packet, "0");
3676 return;
3679 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3682 /* Respond to qTBuffer packet with a block of raw data from the trace
3683 buffer. GDB may ask for a lot, but we are allowed to reply with
3684 only as much as will fit within packet limits or whatever. */
3686 static void
3687 cmd_qtbuffer (char *own_buf)
3689 ULONGEST offset, num, tot;
3690 unsigned char *tbp;
3691 const char *packet = own_buf;
3693 packet += strlen ("qTBuffer:");
3695 packet = unpack_varlen_hex (packet, &offset);
3696 ++packet; /* skip a comma */
3697 unpack_varlen_hex (packet, &num);
3699 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3700 (int) num, phex_nz (offset, 0));
3702 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3704 /* If we're right at the end, reply specially that we're done. */
3705 if (offset == tot)
3707 strcpy (own_buf, "l");
3708 return;
3711 /* Object to any other out-of-bounds request. */
3712 if (offset > tot)
3714 write_enn (own_buf);
3715 return;
3718 /* Compute the pointer corresponding to the given offset, accounting
3719 for wraparound. */
3720 tbp = trace_buffer_start + offset;
3721 if (tbp >= trace_buffer_wrap)
3722 tbp -= (trace_buffer_wrap - trace_buffer_lo);
3724 /* Trim to the remaining bytes if we're close to the end. */
3725 if (num > tot - offset)
3726 num = tot - offset;
3728 /* Trim to available packet size. */
3729 if (num >= (PBUFSIZ - 16) / 2 )
3730 num = (PBUFSIZ - 16) / 2;
3732 bin2hex (tbp, own_buf, num);
3735 static void
3736 cmd_bigqtbuffer_circular (char *own_buf)
3738 ULONGEST val;
3739 char *packet = own_buf;
3741 packet += strlen ("QTBuffer:circular:");
3743 unpack_varlen_hex (packet, &val);
3744 circular_trace_buffer = val;
3745 trace_debug ("Trace buffer is now %s",
3746 circular_trace_buffer ? "circular" : "linear");
3747 write_ok (own_buf);
3750 static void
3751 cmd_bigqtbuffer_size (char *own_buf)
3753 ULONGEST val;
3754 LONGEST sval;
3755 char *packet = own_buf;
3757 /* Can't change the size during a tracing run. */
3758 if (tracing)
3760 write_enn (own_buf);
3761 return;
3764 packet += strlen ("QTBuffer:size:");
3766 /* -1 is sent as literal "-1". */
3767 if (strcmp (packet, "-1") == 0)
3768 sval = DEFAULT_TRACE_BUFFER_SIZE;
3769 else
3771 unpack_varlen_hex (packet, &val);
3772 sval = (LONGEST) val;
3775 init_trace_buffer (sval);
3776 trace_debug ("Trace buffer is now %s bytes",
3777 plongest (trace_buffer_size));
3778 write_ok (own_buf);
3781 static void
3782 cmd_qtnotes (char *own_buf)
3784 size_t nbytes;
3785 char *saved, *user, *notes, *stopnote;
3786 char *packet = own_buf;
3788 packet += strlen ("QTNotes:");
3790 while (*packet)
3792 if (startswith (packet, "user:"))
3794 packet += strlen ("user:");
3795 saved = packet;
3796 packet = strchr (packet, ';');
3797 nbytes = (packet - saved) / 2;
3798 user = (char *) xmalloc (nbytes + 1);
3799 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
3800 user[nbytes] = '\0';
3801 ++packet; /* skip the semicolon */
3802 trace_debug ("User is '%s'", user);
3803 xfree (tracing_user_name);
3804 tracing_user_name = user;
3806 else if (startswith (packet, "notes:"))
3808 packet += strlen ("notes:");
3809 saved = packet;
3810 packet = strchr (packet, ';');
3811 nbytes = (packet - saved) / 2;
3812 notes = (char *) xmalloc (nbytes + 1);
3813 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
3814 notes[nbytes] = '\0';
3815 ++packet; /* skip the semicolon */
3816 trace_debug ("Notes is '%s'", notes);
3817 xfree (tracing_notes);
3818 tracing_notes = notes;
3820 else if (startswith (packet, "tstop:"))
3822 packet += strlen ("tstop:");
3823 saved = packet;
3824 packet = strchr (packet, ';');
3825 nbytes = (packet - saved) / 2;
3826 stopnote = (char *) xmalloc (nbytes + 1);
3827 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
3828 stopnote[nbytes] = '\0';
3829 ++packet; /* skip the semicolon */
3830 trace_debug ("tstop note is '%s'", stopnote);
3831 xfree (tracing_stop_note);
3832 tracing_stop_note = stopnote;
3834 else
3835 break;
3838 write_ok (own_buf);
3842 handle_tracepoint_general_set (char *packet)
3844 if (strcmp ("QTinit", packet) == 0)
3846 cmd_qtinit (packet);
3847 return 1;
3849 else if (startswith (packet, "QTDP:"))
3851 cmd_qtdp (packet);
3852 return 1;
3854 else if (startswith (packet, "QTDPsrc:"))
3856 cmd_qtdpsrc (packet);
3857 return 1;
3859 else if (startswith (packet, "QTEnable:"))
3861 cmd_qtenable_disable (packet, 1);
3862 return 1;
3864 else if (startswith (packet, "QTDisable:"))
3866 cmd_qtenable_disable (packet, 0);
3867 return 1;
3869 else if (startswith (packet, "QTDV:"))
3871 cmd_qtdv (packet);
3872 return 1;
3874 else if (startswith (packet, "QTro:"))
3876 cmd_qtro (packet);
3877 return 1;
3879 else if (strcmp ("QTStart", packet) == 0)
3881 cmd_qtstart (packet);
3882 return 1;
3884 else if (strcmp ("QTStop", packet) == 0)
3886 cmd_qtstop (packet);
3887 return 1;
3889 else if (startswith (packet, "QTDisconnected:"))
3891 cmd_qtdisconnected (packet);
3892 return 1;
3894 else if (startswith (packet, "QTFrame:"))
3896 cmd_qtframe (packet);
3897 return 1;
3899 else if (startswith (packet, "QTBuffer:circular:"))
3901 cmd_bigqtbuffer_circular (packet);
3902 return 1;
3904 else if (startswith (packet, "QTBuffer:size:"))
3906 cmd_bigqtbuffer_size (packet);
3907 return 1;
3909 else if (startswith (packet, "QTNotes:"))
3911 cmd_qtnotes (packet);
3912 return 1;
3915 return 0;
3919 handle_tracepoint_query (char *packet)
3921 if (strcmp ("qTStatus", packet) == 0)
3923 cmd_qtstatus (packet);
3924 return 1;
3926 else if (startswith (packet, "qTP:"))
3928 cmd_qtp (packet);
3929 return 1;
3931 else if (strcmp ("qTfP", packet) == 0)
3933 cmd_qtfp (packet);
3934 return 1;
3936 else if (strcmp ("qTsP", packet) == 0)
3938 cmd_qtsp (packet);
3939 return 1;
3941 else if (strcmp ("qTfV", packet) == 0)
3943 cmd_qtfv (packet);
3944 return 1;
3946 else if (strcmp ("qTsV", packet) == 0)
3948 cmd_qtsv (packet);
3949 return 1;
3951 else if (startswith (packet, "qTV:"))
3953 cmd_qtv (packet);
3954 return 1;
3956 else if (startswith (packet, "qTBuffer:"))
3958 cmd_qtbuffer (packet);
3959 return 1;
3961 else if (strcmp ("qTMinFTPILen", packet) == 0)
3963 cmd_qtminftpilen (packet);
3964 return 1;
3967 return 0;
3970 #endif
3971 #ifndef IN_PROCESS_AGENT
3973 /* Call this when thread TINFO has hit the tracepoint defined by
3974 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
3975 action. This adds a while-stepping collecting state item to the
3976 threads' collecting state list, so that we can keep track of
3977 multiple simultaneous while-stepping actions being collected by the
3978 same thread. This can happen in cases like:
3980 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
3981 ff0002 INSN2
3982 ff0003 INSN3 <-- TP2, collect $regs
3983 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
3984 ff0005 INSN5
3986 Notice that when instruction INSN5 is reached, the while-stepping
3987 actions of both TP1 and TP3 are still being collected, and that TP2
3988 had been collected meanwhile. The whole range of ff0001-ff0005
3989 should be single-stepped, due to at least TP1's while-stepping
3990 action covering the whole range. */
3992 static void
3993 add_while_stepping_state (thread_info *tinfo,
3994 int tp_number, CORE_ADDR tp_address)
3996 struct wstep_state *wstep = XNEW (struct wstep_state);
3998 wstep->next = tinfo->while_stepping;
4000 wstep->tp_number = tp_number;
4001 wstep->tp_address = tp_address;
4002 wstep->current_step = 0;
4004 tinfo->while_stepping = wstep;
4007 /* Release the while-stepping collecting state WSTEP. */
4009 static void
4010 release_while_stepping_state (struct wstep_state *wstep)
4012 free (wstep);
4015 /* Release all while-stepping collecting states currently associated
4016 with thread TINFO. */
4018 void
4019 release_while_stepping_state_list (thread_info *tinfo)
4021 struct wstep_state *head;
4023 while (tinfo->while_stepping)
4025 head = tinfo->while_stepping;
4026 tinfo->while_stepping = head->next;
4027 release_while_stepping_state (head);
4031 /* If TINFO was handling a 'while-stepping' action, the step has
4032 finished, so collect any step data needed, and check if any more
4033 steps are required. Return true if the thread was indeed
4034 collecting tracepoint data, false otherwise. */
4037 tracepoint_finished_step (thread_info *tinfo, CORE_ADDR stop_pc)
4039 struct tracepoint *tpoint;
4040 struct wstep_state *wstep;
4041 struct wstep_state **wstep_link;
4042 struct trap_tracepoint_ctx ctx;
4044 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4045 our buffer. */
4046 if (agent_loaded_p ())
4047 upload_fast_traceframes ();
4049 /* Check if we were indeed collecting data for one of more
4050 tracepoints with a 'while-stepping' count. */
4051 if (tinfo->while_stepping == NULL)
4052 return 0;
4054 if (!tracing)
4056 /* We're not even tracing anymore. Stop this thread from
4057 collecting. */
4058 release_while_stepping_state_list (tinfo);
4060 /* The thread had stopped due to a single-step request indeed
4061 explained by a tracepoint. */
4062 return 1;
4065 wstep = tinfo->while_stepping;
4066 wstep_link = &tinfo->while_stepping;
4068 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4069 target_pid_to_str (tinfo->id).c_str (),
4070 wstep->tp_number, paddress (wstep->tp_address));
4072 ctx.base.type = trap_tracepoint;
4073 ctx.regcache = get_thread_regcache (tinfo);
4075 while (wstep != NULL)
4077 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4078 if (tpoint == NULL)
4080 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4081 wstep->tp_number, paddress (wstep->tp_address),
4082 target_pid_to_str (tinfo->id).c_str ());
4084 /* Unlink. */
4085 *wstep_link = wstep->next;
4086 release_while_stepping_state (wstep);
4087 wstep = *wstep_link;
4088 continue;
4091 /* We've just finished one step. */
4092 ++wstep->current_step;
4094 /* Collect data. */
4095 collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
4096 stop_pc, tpoint, wstep->current_step);
4098 if (wstep->current_step >= tpoint->step_count)
4100 /* The requested numbers of steps have occurred. */
4101 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4102 target_pid_to_str (tinfo->id).c_str (),
4103 wstep->tp_number, paddress (wstep->tp_address));
4105 /* Unlink the wstep. */
4106 *wstep_link = wstep->next;
4107 release_while_stepping_state (wstep);
4108 wstep = *wstep_link;
4110 /* Only check the hit count now, which ensure that we do all
4111 our stepping before stopping the run. */
4112 if (tpoint->pass_count > 0
4113 && tpoint->hit_count >= tpoint->pass_count
4114 && stopping_tracepoint == NULL)
4115 stopping_tracepoint = tpoint;
4117 else
4119 /* Keep single-stepping until the requested numbers of steps
4120 have occurred. */
4121 wstep_link = &wstep->next;
4122 wstep = *wstep_link;
4125 if (stopping_tracepoint
4126 || trace_buffer_is_full
4127 || expr_eval_result != expr_eval_no_error)
4129 stop_tracing ();
4130 break;
4134 return 1;
4137 /* Handle any internal tracing control breakpoint hits. That means,
4138 pull traceframes from the IPA to our buffer, and syncing both
4139 tracing agents when the IPA's tracing stops for some reason. */
4142 handle_tracepoint_bkpts (thread_info *tinfo, CORE_ADDR stop_pc)
4144 /* Pull in fast tracepoint trace frames from the inferior in-process
4145 agent's buffer into our buffer. */
4147 if (!agent_loaded_p ())
4148 return 0;
4150 upload_fast_traceframes ();
4152 /* Check if the in-process agent had decided we should stop
4153 tracing. */
4154 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4156 int ipa_trace_buffer_is_full;
4157 CORE_ADDR ipa_stopping_tracepoint;
4158 int ipa_expr_eval_result;
4159 CORE_ADDR ipa_error_tracepoint;
4161 trace_debug ("lib stopped at stop_tracing");
4163 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4164 &ipa_trace_buffer_is_full);
4166 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4167 &ipa_stopping_tracepoint);
4168 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4170 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4171 &ipa_error_tracepoint);
4172 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4174 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4175 &ipa_expr_eval_result);
4176 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4178 trace_debug ("lib: trace_buffer_is_full: %d, "
4179 "stopping_tracepoint: %s, "
4180 "ipa_expr_eval_result: %d, "
4181 "error_tracepoint: %s, ",
4182 ipa_trace_buffer_is_full,
4183 paddress (ipa_stopping_tracepoint),
4184 ipa_expr_eval_result,
4185 paddress (ipa_error_tracepoint));
4187 if (ipa_trace_buffer_is_full)
4188 trace_debug ("lib stopped due to full buffer.");
4190 if (ipa_stopping_tracepoint)
4191 trace_debug ("lib stopped due to tpoint");
4193 if (ipa_error_tracepoint)
4194 trace_debug ("lib stopped due to error");
4196 if (ipa_stopping_tracepoint != 0)
4198 stopping_tracepoint
4199 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4201 else if (ipa_expr_eval_result != expr_eval_no_error)
4203 expr_eval_result = ipa_expr_eval_result;
4204 error_tracepoint
4205 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4207 stop_tracing ();
4208 return 1;
4210 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4212 trace_debug ("lib stopped at flush_trace_buffer");
4213 return 1;
4216 return 0;
4219 /* Return true if TINFO just hit a tracepoint. Collect data if
4220 so. */
4223 tracepoint_was_hit (thread_info *tinfo, CORE_ADDR stop_pc)
4225 struct tracepoint *tpoint;
4226 int ret = 0;
4227 struct trap_tracepoint_ctx ctx;
4229 /* Not tracing, don't handle. */
4230 if (!tracing)
4231 return 0;
4233 ctx.base.type = trap_tracepoint;
4234 ctx.regcache = get_thread_regcache (tinfo);
4236 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4238 /* Note that we collect fast tracepoints here as well. We'll
4239 step over the fast tracepoint jump later, which avoids the
4240 double collect. */
4241 if (tpoint->enabled && stop_pc == tpoint->address)
4243 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4244 target_pid_to_str (tinfo->id).c_str (),
4245 tpoint->number, paddress (tpoint->address));
4247 /* Test the condition if present, and collect if true. */
4248 if (!tpoint->cond
4249 || (condition_true_at_tracepoint
4250 ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
4251 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4252 stop_pc, tpoint);
4254 if (stopping_tracepoint
4255 || trace_buffer_is_full
4256 || expr_eval_result != expr_eval_no_error)
4258 stop_tracing ();
4260 /* If the tracepoint had a 'while-stepping' action, then set
4261 the thread to collect this tracepoint on the following
4262 single-steps. */
4263 else if (tpoint->step_count > 0)
4265 add_while_stepping_state (tinfo,
4266 tpoint->number, tpoint->address);
4269 ret = 1;
4273 return ret;
4276 #endif
4278 /* Create a trace frame for the hit of the given tracepoint in the
4279 given thread. */
4281 static void
4282 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4283 struct tracepoint *tpoint)
4285 struct traceframe *tframe;
4286 int acti;
4288 /* Only count it as a hit when we actually collect data. */
4289 tpoint->hit_count++;
4291 /* If we've exceeded a defined pass count, record the event for
4292 later, and finish the collection for this hit. This test is only
4293 for nonstepping tracepoints, stepping tracepoints test at the end
4294 of their while-stepping loop. */
4295 if (tpoint->pass_count > 0
4296 && tpoint->hit_count >= tpoint->pass_count
4297 && tpoint->step_count == 0
4298 && stopping_tracepoint == NULL)
4299 stopping_tracepoint = tpoint;
4301 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4302 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4304 tframe = add_traceframe (tpoint);
4306 if (tframe)
4308 for (acti = 0; acti < tpoint->numactions; ++acti)
4310 #ifndef IN_PROCESS_AGENT
4311 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4312 tpoint->number, paddress (tpoint->address),
4313 tpoint->actions_str[acti]);
4314 #endif
4316 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4317 tpoint->actions[acti]);
4320 finish_traceframe (tframe);
4323 if (tframe == NULL && tracing)
4324 trace_buffer_is_full = 1;
4327 #ifndef IN_PROCESS_AGENT
4329 static void
4330 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4331 CORE_ADDR stop_pc,
4332 struct tracepoint *tpoint, int current_step)
4334 struct traceframe *tframe;
4335 int acti;
4337 trace_debug ("Making new step traceframe for "
4338 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4339 tpoint->number, paddress (tpoint->address),
4340 current_step, tpoint->step_count,
4341 tpoint->hit_count);
4343 tframe = add_traceframe (tpoint);
4345 if (tframe)
4347 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4349 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4350 tpoint->number, paddress (tpoint->address),
4351 tpoint->step_actions_str[acti]);
4353 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4354 tpoint->step_actions[acti]);
4357 finish_traceframe (tframe);
4360 if (tframe == NULL && tracing)
4361 trace_buffer_is_full = 1;
4364 #endif
4366 #ifdef IN_PROCESS_AGENT
4367 /* The target description index for IPA. Passed from gdbserver, used
4368 to select ipa_tdesc. */
4369 extern "C" {
4370 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
4372 #endif
4374 static struct regcache *
4375 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4377 struct regcache *regcache = NULL;
4378 #ifdef IN_PROCESS_AGENT
4379 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
4381 if (ctx->type == fast_tracepoint)
4383 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4384 if (!fctx->regcache_initted)
4386 fctx->regcache_initted = 1;
4387 init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
4388 supply_regblock (&fctx->regcache, NULL);
4389 supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4391 regcache = &fctx->regcache;
4393 #else
4394 if (ctx->type == trap_tracepoint)
4396 struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4397 regcache = tctx->regcache;
4399 #endif
4401 gdb_assert (regcache != NULL);
4403 return regcache;
4406 static void
4407 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4408 CORE_ADDR stop_pc,
4409 struct tracepoint *tpoint,
4410 struct traceframe *tframe,
4411 struct tracepoint_action *taction)
4413 enum eval_result_type err;
4415 switch (taction->type)
4417 case 'M':
4419 struct collect_memory_action *maction;
4420 struct eval_agent_expr_context ax_ctx;
4422 maction = (struct collect_memory_action *) taction;
4423 ax_ctx.regcache = NULL;
4424 ax_ctx.tframe = tframe;
4425 ax_ctx.tpoint = tpoint;
4427 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4428 pulongest (maction->len),
4429 paddress (maction->addr), maction->basereg);
4430 /* (should use basereg) */
4431 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4432 maction->len);
4433 break;
4435 case 'R':
4437 unsigned char *regspace;
4438 struct regcache tregcache;
4439 struct regcache *context_regcache;
4440 int regcache_size;
4442 trace_debug ("Want to collect registers");
4444 context_regcache = get_context_regcache (ctx);
4445 regcache_size = register_cache_size (context_regcache->tdesc);
4447 /* Collect all registers for now. */
4448 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4449 if (regspace == NULL)
4451 trace_debug ("Trace buffer block allocation failed, skipping");
4452 break;
4454 /* Identify a register block. */
4455 *regspace = 'R';
4457 /* Wrap the regblock in a register cache (in the stack, we
4458 don't want to malloc here). */
4459 init_register_cache (&tregcache, context_regcache->tdesc,
4460 regspace + 1);
4462 /* Copy the register data to the regblock. */
4463 tregcache.copy_from (context_regcache);
4465 #ifndef IN_PROCESS_AGENT
4466 /* On some platforms, trap-based tracepoints will have the PC
4467 pointing to the next instruction after the trap, but we
4468 don't want the user or GDB trying to guess whether the
4469 saved PC needs adjusting; so always record the adjusted
4470 stop_pc. Note that we can't use tpoint->address instead,
4471 since it will be wrong for while-stepping actions. This
4472 adjustment is a nop for fast tracepoints collected from the
4473 in-process lib (but not if GDBserver is collecting one
4474 preemptively), since the PC had already been adjusted to
4475 contain the tracepoint's address by the jump pad. */
4476 trace_debug ("Storing stop pc (0x%s) in regblock",
4477 paddress (stop_pc));
4479 /* This changes the regblock, not the thread's
4480 regcache. */
4481 regcache_write_pc (&tregcache, stop_pc);
4482 #endif
4484 break;
4485 case 'X':
4487 struct eval_expr_action *eaction;
4488 struct eval_agent_expr_context ax_ctx;
4490 eaction = (struct eval_expr_action *) taction;
4491 ax_ctx.regcache = get_context_regcache (ctx);
4492 ax_ctx.tframe = tframe;
4493 ax_ctx.tpoint = tpoint;
4495 trace_debug ("Want to evaluate expression");
4497 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4499 if (err != expr_eval_no_error)
4501 record_tracepoint_error (tpoint, "action expression", err);
4502 return;
4505 break;
4506 default:
4507 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4508 break;
4512 static int
4513 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4514 struct tracepoint *tpoint)
4516 ULONGEST value = 0;
4517 enum eval_result_type err;
4519 /* Presently, gdbserver doesn't run compiled conditions, only the
4520 IPA does. If the program stops at a fast tracepoint's address
4521 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4522 gdbserver preemptively collect the fast tracepoint. Later, on
4523 resume, gdbserver steps over the fast tracepoint like it steps
4524 over breakpoints, so that the IPA doesn't see that fast
4525 tracepoint. This avoids double collects of fast tracepoints in
4526 that stopping scenario. Having gdbserver itself handle the fast
4527 tracepoint gives the user a consistent view of when fast or trap
4528 tracepoints are collected, compared to an alternative where only
4529 trap tracepoints are collected on stop, and fast tracepoints on
4530 resume. When a fast tracepoint is being processed by gdbserver,
4531 it is always the non-compiled condition expression that is
4532 used. */
4533 #ifdef IN_PROCESS_AGENT
4534 if (tpoint->compiled_cond)
4536 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4537 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4539 else
4540 #endif
4542 struct eval_agent_expr_context ax_ctx;
4544 ax_ctx.regcache = get_context_regcache (ctx);
4545 ax_ctx.tframe = NULL;
4546 ax_ctx.tpoint = tpoint;
4548 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4550 if (err != expr_eval_no_error)
4552 record_tracepoint_error (tpoint, "condition", err);
4553 /* The error case must return false. */
4554 return 0;
4557 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4558 tpoint->number, paddress (tpoint->address),
4559 pulongest (value));
4560 return (value ? 1 : 0);
4563 /* See tracepoint.h. */
4566 agent_mem_read (struct eval_agent_expr_context *ctx,
4567 unsigned char *to, CORE_ADDR from, ULONGEST len)
4569 unsigned char *mspace;
4570 ULONGEST remaining = len;
4571 unsigned short blocklen;
4573 /* If a 'to' buffer is specified, use it. */
4574 if (to != NULL)
4575 return read_inferior_memory (from, to, len);
4577 /* Otherwise, create a new memory block in the trace buffer. */
4578 while (remaining > 0)
4580 size_t sp;
4582 blocklen = (remaining > 65535 ? 65535 : remaining);
4583 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4584 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4585 if (mspace == NULL)
4586 return 1;
4587 /* Identify block as a memory block. */
4588 *mspace = 'M';
4589 ++mspace;
4590 /* Record address and size. */
4591 memcpy (mspace, &from, sizeof (from));
4592 mspace += sizeof (from);
4593 memcpy (mspace, &blocklen, sizeof (blocklen));
4594 mspace += sizeof (blocklen);
4595 /* Record the memory block proper. */
4596 if (read_inferior_memory (from, mspace, blocklen) != 0)
4597 return 1;
4598 trace_debug ("%d bytes recorded", blocklen);
4599 remaining -= blocklen;
4600 from += blocklen;
4602 return 0;
4606 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4607 unsigned char *to, CORE_ADDR from, ULONGEST len)
4609 unsigned char *buf, *mspace;
4610 ULONGEST remaining = len;
4611 unsigned short blocklen, i;
4613 /* To save a bit of space, block lengths are 16-bit, so break large
4614 requests into multiple blocks. Bordering on overkill for strings,
4615 but it could happen that someone specifies a large max length. */
4616 while (remaining > 0)
4618 size_t sp;
4620 blocklen = (remaining > 65535 ? 65535 : remaining);
4621 /* We want working space to accumulate nonzero bytes, since
4622 traceframes must have a predecided size (otherwise it gets
4623 harder to wrap correctly for the circular case, etc). */
4624 buf = (unsigned char *) xmalloc (blocklen + 1);
4625 for (i = 0; i < blocklen; ++i)
4627 /* Read the string one byte at a time, in case the string is
4628 at the end of a valid memory area - we don't want a
4629 correctly-terminated string to engender segvio
4630 complaints. */
4631 read_inferior_memory (from + i, buf + i, 1);
4633 if (buf[i] == '\0')
4635 blocklen = i + 1;
4636 /* Make sure outer loop stops now too. */
4637 remaining = blocklen;
4638 break;
4641 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4642 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4643 if (mspace == NULL)
4645 xfree (buf);
4646 return 1;
4648 /* Identify block as a memory block. */
4649 *mspace = 'M';
4650 ++mspace;
4651 /* Record address and size. */
4652 memcpy ((void *) mspace, (void *) &from, sizeof (from));
4653 mspace += sizeof (from);
4654 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
4655 mspace += sizeof (blocklen);
4656 /* Copy the string contents. */
4657 memcpy ((void *) mspace, (void *) buf, blocklen);
4658 remaining -= blocklen;
4659 from += blocklen;
4660 xfree (buf);
4662 return 0;
4665 /* Record the value of a trace state variable. */
4668 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
4670 unsigned char *vspace;
4671 LONGEST val;
4673 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
4674 1 + sizeof (n) + sizeof (LONGEST));
4675 if (vspace == NULL)
4676 return 1;
4677 /* Identify block as a variable. */
4678 *vspace = 'V';
4679 /* Record variable's number and value. */
4680 memcpy (vspace + 1, &n, sizeof (n));
4681 val = get_trace_state_variable_value (n);
4682 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
4683 trace_debug ("Variable %d recorded", n);
4684 return 0;
4687 #ifndef IN_PROCESS_AGENT
4689 /* Callback for traceframe_walk_blocks, used to find a given block
4690 type in a traceframe. */
4692 static int
4693 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
4695 char *wantedp = (char *) data;
4697 if (*wantedp == blocktype)
4698 return 1;
4700 return 0;
4703 /* Walk over all traceframe blocks of the traceframe buffer starting
4704 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
4705 block found, passing in DATA unmodified. If CALLBACK returns true,
4706 this returns a pointer to where the block is found. Returns NULL
4707 if no callback call returned true, indicating that all blocks have
4708 been walked. */
4710 static unsigned char *
4711 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
4712 int tfnum,
4713 int (*callback) (char blocktype,
4714 unsigned char *dataptr,
4715 void *data),
4716 void *data)
4718 unsigned char *dataptr;
4720 if (datasize == 0)
4722 trace_debug ("traceframe %d has no data", tfnum);
4723 return NULL;
4726 /* Iterate through a traceframe's blocks, looking for a block of the
4727 requested type. */
4728 for (dataptr = database;
4729 dataptr < database + datasize;
4730 /* nothing */)
4732 char blocktype;
4733 unsigned short mlen;
4735 if (dataptr == trace_buffer_wrap)
4737 /* Adjust to reflect wrapping part of the frame around to
4738 the beginning. */
4739 datasize = dataptr - database;
4740 dataptr = database = trace_buffer_lo;
4743 blocktype = *dataptr++;
4745 if ((*callback) (blocktype, dataptr, data))
4746 return dataptr;
4748 switch (blocktype)
4750 case 'R':
4751 /* Skip over the registers block. */
4752 dataptr += current_target_desc ()->registers_size;
4753 break;
4754 case 'M':
4755 /* Skip over the memory block. */
4756 dataptr += sizeof (CORE_ADDR);
4757 memcpy (&mlen, dataptr, sizeof (mlen));
4758 dataptr += (sizeof (mlen) + mlen);
4759 break;
4760 case 'V':
4761 /* Skip over the TSV block. */
4762 dataptr += (sizeof (int) + sizeof (LONGEST));
4763 break;
4764 case 'S':
4765 /* Skip over the static trace data block. */
4766 memcpy (&mlen, dataptr, sizeof (mlen));
4767 dataptr += (sizeof (mlen) + mlen);
4768 break;
4769 default:
4770 trace_debug ("traceframe %d has unknown block type 0x%x",
4771 tfnum, blocktype);
4772 return NULL;
4776 return NULL;
4779 /* Look for the block of type TYPE_WANTED in the traceframe starting
4780 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
4781 number. */
4783 static unsigned char *
4784 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
4785 int tfnum, char type_wanted)
4787 return traceframe_walk_blocks (database, datasize, tfnum,
4788 match_blocktype, &type_wanted);
4791 static unsigned char *
4792 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
4794 unsigned char *regblock;
4796 regblock = traceframe_find_block_type (tframe->data,
4797 tframe->data_size,
4798 tfnum, 'R');
4800 if (regblock == NULL)
4801 trace_debug ("traceframe %d has no register data", tfnum);
4803 return regblock;
4806 /* Get registers from a traceframe. */
4809 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
4811 unsigned char *dataptr;
4812 struct tracepoint *tpoint;
4813 struct traceframe *tframe;
4815 tframe = find_traceframe (tfnum);
4817 if (tframe == NULL)
4819 trace_debug ("traceframe %d not found", tfnum);
4820 return 1;
4823 dataptr = traceframe_find_regblock (tframe, tfnum);
4824 if (dataptr == NULL)
4826 /* Mark registers unavailable. */
4827 supply_regblock (regcache, NULL);
4829 /* We can generally guess at a PC, although this will be
4830 misleading for while-stepping frames and multi-location
4831 tracepoints. */
4832 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
4833 if (tpoint != NULL)
4834 regcache_write_pc (regcache, tpoint->address);
4836 else
4837 supply_regblock (regcache, dataptr);
4839 return 0;
4842 static CORE_ADDR
4843 traceframe_get_pc (struct traceframe *tframe)
4845 struct regcache regcache;
4846 unsigned char *dataptr;
4847 const struct target_desc *tdesc = current_target_desc ();
4849 dataptr = traceframe_find_regblock (tframe, -1);
4850 if (dataptr == NULL)
4851 return 0;
4853 init_register_cache (&regcache, tdesc, dataptr);
4854 return regcache_read_pc (&regcache);
4857 /* Read a requested block of memory from a trace frame. */
4860 traceframe_read_mem (int tfnum, CORE_ADDR addr,
4861 unsigned char *buf, ULONGEST length,
4862 ULONGEST *nbytes)
4864 struct traceframe *tframe;
4865 unsigned char *database, *dataptr;
4866 unsigned int datasize;
4867 CORE_ADDR maddr;
4868 unsigned short mlen;
4870 trace_debug ("traceframe_read_mem");
4872 tframe = find_traceframe (tfnum);
4874 if (!tframe)
4876 trace_debug ("traceframe %d not found", tfnum);
4877 return 1;
4880 datasize = tframe->data_size;
4881 database = dataptr = &tframe->data[0];
4883 /* Iterate through a traceframe's blocks, looking for memory. */
4884 while ((dataptr = traceframe_find_block_type (dataptr,
4885 datasize
4886 - (dataptr - database),
4887 tfnum, 'M')) != NULL)
4889 memcpy (&maddr, dataptr, sizeof (maddr));
4890 dataptr += sizeof (maddr);
4891 memcpy (&mlen, dataptr, sizeof (mlen));
4892 dataptr += sizeof (mlen);
4893 trace_debug ("traceframe %d has %d bytes at %s",
4894 tfnum, mlen, paddress (maddr));
4896 /* If the block includes the first part of the desired range,
4897 return as much it has; GDB will re-request the remainder,
4898 which might be in a different block of this trace frame. */
4899 if (maddr <= addr && addr < (maddr + mlen))
4901 ULONGEST amt = (maddr + mlen) - addr;
4902 if (amt > length)
4903 amt = length;
4905 memcpy (buf, dataptr + (addr - maddr), amt);
4906 *nbytes = amt;
4907 return 0;
4910 /* Skip over this block. */
4911 dataptr += mlen;
4914 trace_debug ("traceframe %d has no memory data for the desired region",
4915 tfnum);
4917 *nbytes = 0;
4918 return 0;
4921 static int
4922 traceframe_read_tsv (int tsvnum, LONGEST *val)
4924 client_state &cs = get_client_state ();
4925 int tfnum;
4926 struct traceframe *tframe;
4927 unsigned char *database, *dataptr;
4928 unsigned int datasize;
4929 int vnum;
4930 int found = 0;
4932 trace_debug ("traceframe_read_tsv");
4934 tfnum = cs.current_traceframe;
4936 if (tfnum < 0)
4938 trace_debug ("no current traceframe");
4939 return 1;
4942 tframe = find_traceframe (tfnum);
4944 if (tframe == NULL)
4946 trace_debug ("traceframe %d not found", tfnum);
4947 return 1;
4950 datasize = tframe->data_size;
4951 database = dataptr = &tframe->data[0];
4953 /* Iterate through a traceframe's blocks, looking for the last
4954 matched tsv. */
4955 while ((dataptr = traceframe_find_block_type (dataptr,
4956 datasize
4957 - (dataptr - database),
4958 tfnum, 'V')) != NULL)
4960 memcpy (&vnum, dataptr, sizeof (vnum));
4961 dataptr += sizeof (vnum);
4963 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
4965 /* Check that this is the variable we want. */
4966 if (tsvnum == vnum)
4968 memcpy (val, dataptr, sizeof (*val));
4969 found = 1;
4972 /* Skip over this block. */
4973 dataptr += sizeof (LONGEST);
4976 if (!found)
4977 trace_debug ("traceframe %d has no data for variable %d",
4978 tfnum, tsvnum);
4979 return !found;
4982 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
4983 object. DATA is pointer to a string holding the traceframe-info
4984 object being built. */
4986 static int
4987 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
4989 std::string *buffer = (std::string *) data;
4991 switch (blocktype)
4993 case 'M':
4995 unsigned short mlen;
4996 CORE_ADDR maddr;
4998 memcpy (&maddr, dataptr, sizeof (maddr));
4999 dataptr += sizeof (maddr);
5000 memcpy (&mlen, dataptr, sizeof (mlen));
5001 dataptr += sizeof (mlen);
5002 string_xml_appendf (*buffer,
5003 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
5004 paddress (maddr), phex_nz (mlen, sizeof (mlen)));
5005 break;
5007 case 'V':
5009 int vnum;
5011 memcpy (&vnum, dataptr, sizeof (vnum));
5012 string_xml_appendf (*buffer, "<tvar id=\"%d\"/>\n", vnum);
5013 break;
5015 case 'R':
5016 case 'S':
5018 break;
5020 default:
5021 warning ("Unhandled trace block type (%d) '%c ' "
5022 "while building trace frame info.",
5023 blocktype, blocktype);
5024 break;
5027 return 0;
5030 /* Build a traceframe-info object for traceframe number TFNUM into
5031 BUFFER. */
5034 traceframe_read_info (int tfnum, std::string *buffer)
5036 struct traceframe *tframe;
5038 trace_debug ("traceframe_read_info");
5040 tframe = find_traceframe (tfnum);
5042 if (!tframe)
5044 trace_debug ("traceframe %d not found", tfnum);
5045 return 1;
5048 *buffer += "<traceframe-info>\n";
5049 traceframe_walk_blocks (tframe->data, tframe->data_size,
5050 tfnum, build_traceframe_info_xml, buffer);
5051 *buffer += "</traceframe-info>\n";
5052 return 0;
5055 /* Return the first fast tracepoint whose jump pad contains PC. */
5057 static struct tracepoint *
5058 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5060 struct tracepoint *tpoint;
5062 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5063 if (tpoint->type == fast_tracepoint)
5064 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5065 return tpoint;
5067 return NULL;
5070 /* Return the first fast tracepoint whose trampoline contains PC. */
5072 static struct tracepoint *
5073 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5075 struct tracepoint *tpoint;
5077 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5079 if (tpoint->type == fast_tracepoint
5080 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5081 return tpoint;
5084 return NULL;
5087 /* Return GDBserver's tracepoint that matches the IP Agent's
5088 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5089 address space. */
5091 static struct tracepoint *
5092 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5094 struct tracepoint *tpoint;
5096 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5097 if (tpoint->type == fast_tracepoint)
5098 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5099 return tpoint;
5101 return NULL;
5104 #endif
5106 /* The type of the object that is used to synchronize fast tracepoint
5107 collection. */
5109 typedef struct collecting_t
5111 /* The fast tracepoint number currently collecting. */
5112 uintptr_t tpoint;
5114 /* A number that GDBserver can use to identify the thread that is
5115 presently holding the collect lock. This need not (and usually
5116 is not) the thread id, as getting the current thread ID usually
5117 requires a system call, which we want to avoid like the plague.
5118 Usually this is thread's TCB, found in the TLS (pseudo-)
5119 register, which is readable with a single insn on several
5120 architectures. */
5121 uintptr_t thread_area;
5122 } collecting_t;
5124 #ifndef IN_PROCESS_AGENT
5126 void
5127 force_unlock_trace_buffer (void)
5129 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5132 /* Check if the thread identified by THREAD_AREA which is stopped at
5133 STOP_PC, is presently locking the fast tracepoint collection, and
5134 if so, gather some status of said collection. Returns 0 if the
5135 thread isn't collecting or in the jump pad at all. 1, if in the
5136 jump pad (or within gdb_collect) and hasn't executed the adjusted
5137 original insn yet (can set a breakpoint there and run to it). 2,
5138 if presently executing the adjusted original insn --- in which
5139 case, if we want to move the thread out of the jump pad, we need to
5140 single-step it until this function returns 0. */
5142 fast_tpoint_collect_result
5143 fast_tracepoint_collecting (CORE_ADDR thread_area,
5144 CORE_ADDR stop_pc,
5145 struct fast_tpoint_collect_status *status)
5147 CORE_ADDR ipa_collecting;
5148 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5149 CORE_ADDR ipa_gdb_trampoline_buffer;
5150 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5151 struct tracepoint *tpoint;
5152 int needs_breakpoint;
5154 /* The thread THREAD_AREA is either:
5156 0. not collecting at all, not within the jump pad, or within
5157 gdb_collect or one of its callees.
5159 1. in the jump pad and haven't reached gdb_collect
5161 2. within gdb_collect (out of the jump pad) (collect is set)
5163 3. we're in the jump pad, after gdb_collect having returned,
5164 possibly executing the adjusted insns.
5166 For cases 1 and 3, `collecting' may or not be set. The jump pad
5167 doesn't have any complicated jump logic, so we can tell if the
5168 thread is executing the adjust original insn or not by just
5169 matching STOP_PC with known jump pad addresses. If we it isn't
5170 yet executing the original insn, set a breakpoint there, and let
5171 the thread run to it, so to quickly step over a possible (many
5172 insns) gdb_collect call. Otherwise, or when the breakpoint is
5173 hit, only a few (small number of) insns are left to be executed
5174 in the jump pad. Single-step the thread until it leaves the
5175 jump pad. */
5177 again:
5178 tpoint = NULL;
5179 needs_breakpoint = 0;
5180 trace_debug ("fast_tracepoint_collecting");
5182 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5183 &ipa_gdb_jump_pad_buffer))
5185 internal_error ("error extracting `gdb_jump_pad_buffer'");
5187 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5188 &ipa_gdb_jump_pad_buffer_end))
5190 internal_error ("error extracting `gdb_jump_pad_buffer_end'");
5193 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5194 &ipa_gdb_trampoline_buffer))
5196 internal_error ("error extracting `gdb_trampoline_buffer'");
5198 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5199 &ipa_gdb_trampoline_buffer_end))
5201 internal_error ("error extracting `gdb_trampoline_buffer_end'");
5204 if (ipa_gdb_jump_pad_buffer <= stop_pc
5205 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5207 /* We can tell which tracepoint(s) the thread is collecting by
5208 matching the jump pad address back to the tracepoint. */
5209 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5210 if (tpoint == NULL)
5212 warning ("in jump pad, but no matching tpoint?");
5213 return fast_tpoint_collect_result::not_collecting;
5215 else
5217 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5218 "adj_insn(%s, %s)",
5219 tpoint->number, paddress (tpoint->address),
5220 paddress (tpoint->jump_pad),
5221 paddress (tpoint->jump_pad_end),
5222 paddress (tpoint->adjusted_insn_addr),
5223 paddress (tpoint->adjusted_insn_addr_end));
5226 /* Definitely in the jump pad. May or may not need
5227 fast-exit-jump-pad breakpoint. */
5228 if (tpoint->jump_pad <= stop_pc
5229 && stop_pc < tpoint->adjusted_insn_addr)
5230 needs_breakpoint = 1;
5232 else if (ipa_gdb_trampoline_buffer <= stop_pc
5233 && stop_pc < ipa_gdb_trampoline_buffer_end)
5235 /* We can tell which tracepoint(s) the thread is collecting by
5236 matching the trampoline address back to the tracepoint. */
5237 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5238 if (tpoint == NULL)
5240 warning ("in trampoline, but no matching tpoint?");
5241 return fast_tpoint_collect_result::not_collecting;
5243 else
5245 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5246 tpoint->number, paddress (tpoint->address),
5247 paddress (tpoint->trampoline),
5248 paddress (tpoint->trampoline_end));
5251 /* Have not reached jump pad yet, but treat the trampoline as a
5252 part of the jump pad that is before the adjusted original
5253 instruction. */
5254 needs_breakpoint = 1;
5256 else
5258 collecting_t ipa_collecting_obj;
5260 /* If `collecting' is set/locked, then the THREAD_AREA thread
5261 may or not be the one holding the lock. We have to read the
5262 lock to find out. */
5264 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5265 &ipa_collecting))
5267 trace_debug ("fast_tracepoint_collecting:"
5268 " failed reading 'collecting' in the inferior");
5269 return fast_tpoint_collect_result::not_collecting;
5272 if (!ipa_collecting)
5274 trace_debug ("fast_tracepoint_collecting: not collecting"
5275 " (and nobody is).");
5276 return fast_tpoint_collect_result::not_collecting;
5279 /* Some thread is collecting. Check which. */
5280 if (read_inferior_memory (ipa_collecting,
5281 (unsigned char *) &ipa_collecting_obj,
5282 sizeof (ipa_collecting_obj)) != 0)
5283 goto again;
5285 if (ipa_collecting_obj.thread_area != thread_area)
5287 trace_debug ("fast_tracepoint_collecting: not collecting "
5288 "(another thread is)");
5289 return fast_tpoint_collect_result::not_collecting;
5292 tpoint
5293 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5294 if (tpoint == NULL)
5296 warning ("fast_tracepoint_collecting: collecting, "
5297 "but tpoint %s not found?",
5298 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5299 return fast_tpoint_collect_result::not_collecting;
5302 /* The thread is within `gdb_collect', skip over the rest of
5303 fast tracepoint collection quickly using a breakpoint. */
5304 needs_breakpoint = 1;
5307 /* The caller wants a bit of status detail. */
5308 if (status != NULL)
5310 status->tpoint_num = tpoint->number;
5311 status->tpoint_addr = tpoint->address;
5312 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5313 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5316 if (needs_breakpoint)
5318 /* Hasn't executed the original instruction yet. Set breakpoint
5319 there, and wait till it's hit, then single-step until exiting
5320 the jump pad. */
5322 trace_debug ("\
5323 fast_tracepoint_collecting, returning continue-until-break at %s",
5324 paddress (tpoint->adjusted_insn_addr));
5326 return fast_tpoint_collect_result::before_insn; /* continue */
5328 else
5330 /* Just single-step until exiting the jump pad. */
5332 trace_debug ("fast_tracepoint_collecting, returning "
5333 "need-single-step (%s-%s)",
5334 paddress (tpoint->adjusted_insn_addr),
5335 paddress (tpoint->adjusted_insn_addr_end));
5337 return fast_tpoint_collect_result::at_insn; /* single-step */
5341 #endif
5343 #ifdef IN_PROCESS_AGENT
5345 /* The global fast tracepoint collect lock. Points to a collecting_t
5346 object built on the stack by the jump pad, if presently locked;
5347 NULL if it isn't locked. Note that this lock *must* be set while
5348 executing any *function other than the jump pad. See
5349 fast_tracepoint_collecting. */
5350 extern "C" {
5351 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5354 /* This is needed for -Wmissing-declarations. */
5355 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5356 unsigned char *regs);
5358 /* This routine, called from the jump pad (in asm) is designed to be
5359 called from the jump pads of fast tracepoints, thus it is on the
5360 critical path. */
5362 IP_AGENT_EXPORT_FUNC void
5363 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5365 struct fast_tracepoint_ctx ctx;
5366 const struct target_desc *ipa_tdesc;
5368 /* Don't do anything until the trace run is completely set up. */
5369 if (!tracing)
5370 return;
5372 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5373 ctx.base.type = fast_tracepoint;
5374 ctx.regs = regs;
5375 ctx.regcache_initted = 0;
5376 /* Wrap the regblock in a register cache (in the stack, we don't
5377 want to malloc here). */
5378 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5379 if (ctx.regspace == NULL)
5381 trace_debug ("Trace buffer block allocation failed, skipping");
5382 return;
5385 for (ctx.tpoint = tpoint;
5386 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5387 ctx.tpoint = ctx.tpoint->next)
5389 if (!ctx.tpoint->enabled)
5390 continue;
5392 /* Multiple tracepoints of different types, such as fast tracepoint and
5393 static tracepoint, can be set at the same address. */
5394 if (ctx.tpoint->type != tpoint->type)
5395 continue;
5397 /* Test the condition if present, and collect if true. */
5398 if (ctx.tpoint->cond == NULL
5399 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5400 ctx.tpoint))
5402 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5403 ctx.tpoint->address, ctx.tpoint);
5405 /* Note that this will cause original insns to be written back
5406 to where we jumped from, but that's OK because we're jumping
5407 back to the next whole instruction. This will go badly if
5408 instruction restoration is not atomic though. */
5409 if (stopping_tracepoint
5410 || trace_buffer_is_full
5411 || expr_eval_result != expr_eval_no_error)
5413 stop_tracing ();
5414 break;
5417 else
5419 /* If there was a condition and it evaluated to false, the only
5420 way we would stop tracing is if there was an error during
5421 condition expression evaluation. */
5422 if (expr_eval_result != expr_eval_no_error)
5424 stop_tracing ();
5425 break;
5431 /* These global variables points to the corresponding functions. This is
5432 necessary on powerpc64, where asking for function symbol address from gdb
5433 results in returning the actual code pointer, instead of the descriptor
5434 pointer. */
5436 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5437 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5438 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5439 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5441 extern "C" {
5442 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5443 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5444 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5445 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5446 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5447 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5450 #endif
5452 #ifndef IN_PROCESS_AGENT
5454 CORE_ADDR
5455 get_raw_reg_func_addr (void)
5457 CORE_ADDR res;
5458 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5460 error ("error extracting get_raw_reg_ptr");
5461 return 0;
5463 return res;
5466 CORE_ADDR
5467 get_get_tsv_func_addr (void)
5469 CORE_ADDR res;
5470 if (read_inferior_data_pointer (
5471 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5473 error ("error extracting get_trace_state_variable_value_ptr");
5474 return 0;
5476 return res;
5479 CORE_ADDR
5480 get_set_tsv_func_addr (void)
5482 CORE_ADDR res;
5483 if (read_inferior_data_pointer (
5484 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5486 error ("error extracting set_trace_state_variable_value_ptr");
5487 return 0;
5489 return res;
5492 static void
5493 compile_tracepoint_condition (struct tracepoint *tpoint,
5494 CORE_ADDR *jump_entry)
5496 CORE_ADDR entry_point = *jump_entry;
5497 enum eval_result_type err;
5499 trace_debug ("Starting condition compilation for tracepoint %d\n",
5500 tpoint->number);
5502 /* Initialize the global pointer to the code being built. */
5503 current_insn_ptr = *jump_entry;
5505 emit_prologue ();
5507 err = compile_bytecodes (tpoint->cond);
5509 if (err == expr_eval_no_error)
5511 emit_epilogue ();
5513 /* Record the beginning of the compiled code. */
5514 tpoint->compiled_cond = entry_point;
5516 trace_debug ("Condition compilation for tracepoint %d complete\n",
5517 tpoint->number);
5519 else
5521 /* Leave the unfinished code in situ, but don't point to it. */
5523 tpoint->compiled_cond = 0;
5525 trace_debug ("Condition compilation for tracepoint %d failed, "
5526 "error code %d",
5527 tpoint->number, err);
5530 /* Update the code pointer passed in. Note that we do this even if
5531 the compile fails, so that we can look at the partial results
5532 instead of letting them be overwritten. */
5533 *jump_entry = current_insn_ptr;
5535 /* Leave a gap, to aid dump decipherment. */
5536 *jump_entry += 16;
5539 /* The base pointer of the IPA's heap. This is the only memory the
5540 IPA is allowed to use. The IPA should _not_ call the inferior's
5541 `malloc' during operation. That'd be slow, and, most importantly,
5542 it may not be safe. We may be collecting a tracepoint in a signal
5543 handler, for example. */
5544 static CORE_ADDR target_tp_heap;
5546 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5547 to 8 bytes. */
5549 static CORE_ADDR
5550 target_malloc (ULONGEST size)
5552 CORE_ADDR ptr;
5554 if (target_tp_heap == 0)
5556 /* We have the pointer *address*, need what it points to. */
5557 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5558 &target_tp_heap))
5560 internal_error ("couldn't get target heap head pointer");
5564 ptr = target_tp_heap;
5565 target_tp_heap += size;
5567 /* Pad to 8-byte alignment. */
5568 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5570 return ptr;
5573 static CORE_ADDR
5574 download_agent_expr (struct agent_expr *expr)
5576 CORE_ADDR expr_addr;
5577 CORE_ADDR expr_bytes;
5579 expr_addr = target_malloc (sizeof (*expr));
5580 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5582 expr_bytes = target_malloc (expr->length);
5583 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
5584 expr_bytes);
5585 target_write_memory (expr_bytes, expr->bytes, expr->length);
5587 return expr_addr;
5590 /* Align V up to N bits. */
5591 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5593 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
5595 static void
5596 download_tracepoint_1 (struct tracepoint *tpoint)
5598 struct tracepoint target_tracepoint;
5599 CORE_ADDR tpptr = 0;
5601 gdb_assert (tpoint->type == fast_tracepoint);
5603 if (tpoint->cond != NULL && target_emit_ops () != NULL)
5605 CORE_ADDR jentry, jump_entry;
5607 jentry = jump_entry = get_jump_space_head ();
5609 if (tpoint->cond != NULL)
5611 /* Pad to 8-byte alignment. (needed?) */
5612 /* Actually this should be left for the target to
5613 decide. */
5614 jentry = UALIGN (jentry, 8);
5616 compile_tracepoint_condition (tpoint, &jentry);
5619 /* Pad to 8-byte alignment. */
5620 jentry = UALIGN (jentry, 8);
5621 claim_jump_space (jentry - jump_entry);
5624 target_tracepoint = *tpoint;
5626 tpptr = target_malloc (sizeof (*tpoint));
5627 tpoint->obj_addr_on_target = tpptr;
5629 /* Write the whole object. We'll fix up its pointers in a bit.
5630 Assume no next for now. This is fixed up above on the next
5631 iteration, if there's any. */
5632 target_tracepoint.next = NULL;
5633 /* Need to clear this here too, since we're downloading the
5634 tracepoints before clearing our own copy. */
5635 target_tracepoint.hit_count = 0;
5637 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
5638 sizeof (target_tracepoint));
5640 if (tpoint->cond)
5641 write_inferior_data_pointer (tpptr
5642 + offsetof (struct tracepoint, cond),
5643 download_agent_expr (tpoint->cond));
5645 if (tpoint->numactions)
5647 int i;
5648 CORE_ADDR actions_array;
5650 /* The pointers array. */
5651 actions_array
5652 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
5653 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
5654 actions),
5655 actions_array);
5657 /* Now for each pointer, download the action. */
5658 for (i = 0; i < tpoint->numactions; i++)
5660 struct tracepoint_action *action = tpoint->actions[i];
5661 CORE_ADDR ipa_action = tracepoint_action_download (action);
5663 if (ipa_action != 0)
5664 write_inferior_data_pointer (actions_array
5665 + i * sizeof (*tpoint->actions),
5666 ipa_action);
5671 #define IPA_PROTO_FAST_TRACE_FLAG 0
5672 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
5673 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
5674 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
5675 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
5677 /* Send a command to agent to download and install tracepoint TPOINT. */
5679 static int
5680 tracepoint_send_agent (struct tracepoint *tpoint)
5682 char buf[IPA_CMD_BUF_SIZE];
5683 char *p;
5684 int i, ret;
5686 p = buf;
5687 strcpy (p, "FastTrace:");
5688 p += 10;
5690 COPY_FIELD_TO_BUF (p, tpoint, number);
5691 COPY_FIELD_TO_BUF (p, tpoint, address);
5692 COPY_FIELD_TO_BUF (p, tpoint, type);
5693 COPY_FIELD_TO_BUF (p, tpoint, enabled);
5694 COPY_FIELD_TO_BUF (p, tpoint, step_count);
5695 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
5696 COPY_FIELD_TO_BUF (p, tpoint, numactions);
5697 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
5698 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
5699 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
5700 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
5702 /* condition */
5703 p = agent_expr_send (p, tpoint->cond);
5705 /* tracepoint_action */
5706 for (i = 0; i < tpoint->numactions; i++)
5708 struct tracepoint_action *action = tpoint->actions[i];
5710 p[0] = action->type;
5711 p = tracepoint_action_send (&p[1], action);
5714 get_jump_space_head ();
5715 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
5716 agent can use jump pad from it. */
5717 if (tpoint->type == fast_tracepoint)
5719 memcpy (p, &gdb_jump_pad_head, 8);
5720 p += 8;
5723 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
5724 if (ret)
5725 return ret;
5727 if (!startswith (buf, "OK"))
5728 return 1;
5730 /* The value of tracepoint's target address is stored in BUF. */
5731 memcpy (&tpoint->obj_addr_on_target,
5732 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
5734 if (tpoint->type == fast_tracepoint)
5736 unsigned char *insn
5737 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
5738 int fjump_size;
5740 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
5741 (unsigned int) tpoint->obj_addr_on_target,
5742 (unsigned int) gdb_jump_pad_head);
5744 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
5746 /* This has been done in agent. We should also set up record for it. */
5747 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
5748 /* Wire it in. */
5749 tpoint->handle
5750 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
5753 return 0;
5756 static void
5757 download_tracepoint (struct tracepoint *tpoint)
5759 struct tracepoint *tp, *tp_prev;
5761 if (tpoint->type != fast_tracepoint)
5762 return;
5764 download_tracepoint_1 (tpoint);
5766 /* Find the previous entry of TPOINT, which is fast tracepoint or
5767 static tracepoint. */
5768 tp_prev = NULL;
5769 for (tp = tracepoints; tp != tpoint; tp = tp->next)
5771 if (tp->type == fast_tracepoint)
5772 tp_prev = tp;
5775 if (tp_prev)
5777 CORE_ADDR tp_prev_target_next_addr;
5779 /* Insert TPOINT after TP_PREV in IPA. */
5780 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
5781 + offsetof (struct tracepoint, next),
5782 &tp_prev_target_next_addr))
5784 internal_error ("error reading `tp_prev->next'");
5787 /* tpoint->next = tp_prev->next */
5788 write_inferior_data_pointer (tpoint->obj_addr_on_target
5789 + offsetof (struct tracepoint, next),
5790 tp_prev_target_next_addr);
5791 /* tp_prev->next = tpoint */
5792 write_inferior_data_pointer (tp_prev->obj_addr_on_target
5793 + offsetof (struct tracepoint, next),
5794 tpoint->obj_addr_on_target);
5796 else
5797 /* First object in list, set the head pointer in the
5798 inferior. */
5799 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
5800 tpoint->obj_addr_on_target);
5804 static void
5805 download_trace_state_variables (void)
5807 CORE_ADDR ptr = 0, prev_ptr = 0;
5808 struct trace_state_variable *tsv;
5810 /* Start out empty. */
5811 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
5813 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
5815 struct trace_state_variable target_tsv;
5817 /* TSV's with a getter have been initialized equally in both the
5818 inferior and GDBserver. Skip them. */
5819 if (tsv->getter != NULL)
5820 continue;
5822 target_tsv = *tsv;
5824 prev_ptr = ptr;
5825 ptr = target_malloc (sizeof (*tsv));
5827 if (tsv == trace_state_variables)
5829 /* First object in list, set the head pointer in the
5830 inferior. */
5832 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
5833 ptr);
5835 else
5837 write_inferior_data_pointer (prev_ptr
5838 + offsetof (struct trace_state_variable,
5839 next),
5840 ptr);
5843 /* Write the whole object. We'll fix up its pointers in a bit.
5844 Assume no next, fixup when needed. */
5845 target_tsv.next = NULL;
5847 target_write_memory (ptr, (unsigned char *) &target_tsv,
5848 sizeof (target_tsv));
5850 if (tsv->name != NULL)
5852 size_t size = strlen (tsv->name) + 1;
5853 CORE_ADDR name_addr = target_malloc (size);
5854 target_write_memory (name_addr,
5855 (unsigned char *) tsv->name, size);
5856 write_inferior_data_pointer (ptr
5857 + offsetof (struct trace_state_variable,
5858 name),
5859 name_addr);
5862 gdb_assert (tsv->getter == NULL);
5865 if (prev_ptr != 0)
5867 /* Fixup the next pointer in the last item in the list. */
5868 write_inferior_data_pointer (prev_ptr
5869 + offsetof (struct trace_state_variable,
5870 next), 0);
5874 /* Upload complete trace frames out of the IP Agent's trace buffer
5875 into GDBserver's trace buffer. This always uploads either all or
5876 no trace frames. This is the counter part of
5877 `trace_alloc_trace_buffer'. See its description of the atomic
5878 syncing mechanism. */
5880 static void
5881 upload_fast_traceframes (void)
5883 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
5884 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
5885 CORE_ADDR tf;
5886 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
5887 unsigned int curr_tbctrl_idx;
5888 unsigned int ipa_trace_buffer_ctrl_curr;
5889 unsigned int ipa_trace_buffer_ctrl_curr_old;
5890 CORE_ADDR ipa_trace_buffer_ctrl_addr;
5891 struct breakpoint *about_to_request_buffer_space_bkpt;
5892 CORE_ADDR ipa_trace_buffer_lo;
5893 CORE_ADDR ipa_trace_buffer_hi;
5895 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5896 &ipa_traceframe_read_count_racy))
5898 /* This will happen in most targets if the current thread is
5899 running. */
5900 return;
5903 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5904 &ipa_traceframe_write_count_racy))
5905 return;
5907 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
5908 ipa_traceframe_write_count_racy
5909 - ipa_traceframe_read_count_racy,
5910 ipa_traceframe_write_count_racy,
5911 ipa_traceframe_read_count_racy);
5913 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
5914 return;
5916 about_to_request_buffer_space_bkpt
5917 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
5918 NULL);
5920 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5921 &ipa_trace_buffer_ctrl_curr))
5922 return;
5924 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
5926 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
5929 unsigned int prev, counter;
5931 /* Update the token, with new counters, and the GDBserver stamp
5932 bit. Always reuse the current TBC index. */
5933 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
5934 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
5936 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
5937 | (prev << 12)
5938 | counter
5939 | curr_tbctrl_idx);
5942 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5943 ipa_trace_buffer_ctrl_curr))
5944 return;
5946 trace_debug ("Lib: Committed %08x -> %08x",
5947 ipa_trace_buffer_ctrl_curr_old,
5948 ipa_trace_buffer_ctrl_curr);
5950 /* Re-read these, now that we've installed the
5951 `about_to_request_buffer_space' breakpoint/lock. A thread could
5952 have finished a traceframe between the last read of these
5953 counters and setting the breakpoint above. If we start
5954 uploading, we never want to leave this function with
5955 traceframe_read_count != 0, otherwise, GDBserver could end up
5956 incrementing the counter tokens more than once (due to event loop
5957 nesting), which would break the IP agent's "effective" detection
5958 (see trace_alloc_trace_buffer). */
5959 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5960 &ipa_traceframe_read_count))
5961 return;
5962 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5963 &ipa_traceframe_write_count))
5964 return;
5966 if (debug_threads)
5968 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
5969 ipa_traceframe_write_count - ipa_traceframe_read_count,
5970 ipa_traceframe_write_count, ipa_traceframe_read_count);
5972 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
5973 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
5974 trace_debug ("note that ipa_traceframe_count's parts changed");
5977 /* Get the address of the current TBC object (the IP agent has an
5978 array of 3 such objects). The index is stored in the TBC
5979 token. */
5980 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
5981 ipa_trace_buffer_ctrl_addr
5982 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
5984 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
5985 (unsigned char *) &ipa_trace_buffer_ctrl,
5986 sizeof (struct ipa_trace_buffer_control)))
5987 return;
5989 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
5990 &ipa_trace_buffer_lo))
5991 return;
5992 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
5993 &ipa_trace_buffer_hi))
5994 return;
5996 /* Offsets are easier to grok for debugging than raw addresses,
5997 especially for the small trace buffer sizes that are useful for
5998 testing. */
5999 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6000 "endfree=%d wrap=%d hi=%d",
6001 curr_tbctrl_idx,
6002 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6003 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6004 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6005 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6006 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6008 /* Note that the IPA's buffer is always circular. */
6010 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6012 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6013 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6015 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6016 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6017 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6018 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6019 : 0))
6021 tf = IPA_FIRST_TRACEFRAME ();
6023 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6025 struct tracepoint *tpoint;
6026 struct traceframe *tframe;
6027 unsigned char *block;
6028 struct traceframe ipa_tframe;
6030 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6031 offsetof (struct traceframe, data)))
6032 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6034 if (ipa_tframe.tpnum == 0)
6036 internal_error ("Uploading: No (more) fast traceframes, but"
6037 " ipa_traceframe_count == %u??\n",
6038 ipa_traceframe_write_count
6039 - ipa_traceframe_read_count);
6042 /* Note that this will be incorrect for multi-location
6043 tracepoints... */
6044 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6046 tframe = add_traceframe (tpoint);
6047 if (tframe == NULL)
6049 trace_buffer_is_full = 1;
6050 trace_debug ("Uploading: trace buffer is full");
6052 else
6054 /* Copy the whole set of blocks in one go for now. FIXME:
6055 split this in smaller blocks. */
6056 block = add_traceframe_block (tframe, tpoint,
6057 ipa_tframe.data_size);
6058 if (block != NULL)
6060 if (read_inferior_memory (tf
6061 + offsetof (struct traceframe, data),
6062 block, ipa_tframe.data_size))
6063 error ("Uploading: Couldn't read traceframe data at %s\n",
6064 paddress (tf + offsetof (struct traceframe, data)));
6067 trace_debug ("Uploading: traceframe didn't fit");
6068 finish_traceframe (tframe);
6071 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6073 /* If we freed the traceframe that wrapped around, go back
6074 to the non-wrap case. */
6075 if (tf < ipa_trace_buffer_ctrl.start)
6077 trace_debug ("Lib: Discarding past the wraparound");
6078 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6080 ipa_trace_buffer_ctrl.start = tf;
6081 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6082 ++ipa_traceframe_read_count;
6084 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6085 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6087 trace_debug ("Lib: buffer is fully empty. "
6088 "Trace buffer [%d] start=%d free=%d endfree=%d",
6089 curr_tbctrl_idx,
6090 (int) (ipa_trace_buffer_ctrl.start
6091 - ipa_trace_buffer_lo),
6092 (int) (ipa_trace_buffer_ctrl.free
6093 - ipa_trace_buffer_lo),
6094 (int) (ipa_trace_buffer_ctrl.end_free
6095 - ipa_trace_buffer_lo));
6097 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6098 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6099 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6100 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6103 trace_debug ("Uploaded a traceframe\n"
6104 "Lib: Trace buffer [%d] start=%d free=%d "
6105 "endfree=%d wrap=%d hi=%d",
6106 curr_tbctrl_idx,
6107 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6108 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6109 (int) (ipa_trace_buffer_ctrl.end_free
6110 - ipa_trace_buffer_lo),
6111 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6112 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6115 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6116 (unsigned char *) &ipa_trace_buffer_ctrl,
6117 sizeof (struct ipa_trace_buffer_control)))
6118 return;
6120 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6121 ipa_traceframe_read_count);
6123 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6125 target_pause_all (true);
6127 delete_breakpoint (about_to_request_buffer_space_bkpt);
6128 about_to_request_buffer_space_bkpt = NULL;
6130 target_unpause_all (true);
6132 if (trace_buffer_is_full)
6133 stop_tracing ();
6135 #endif
6137 #ifdef IN_PROCESS_AGENT
6139 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6141 #endif /* IN_PROCESS_AGENT */
6143 #ifndef IN_PROCESS_AGENT
6145 /* Ask the in-process agent to run a command. Since we don't want to
6146 have to handle the IPA hitting breakpoints while running the
6147 command, we pause all threads, remove all breakpoints, and then set
6148 the helper thread re-running. We communicate with the helper
6149 thread by means of direct memory xfering, and a socket for
6150 synchronization. */
6152 static int
6153 run_inferior_command (char *cmd, int len)
6155 int err = -1;
6156 int pid = current_thread->id.pid ();
6158 trace_debug ("run_inferior_command: running: %s", cmd);
6160 target_pause_all (false);
6161 uninsert_all_breakpoints ();
6163 err = agent_run_command (pid, cmd, len);
6165 reinsert_all_breakpoints ();
6166 target_unpause_all (false);
6168 return err;
6171 #else /* !IN_PROCESS_AGENT */
6173 #include <sys/socket.h>
6174 #include <sys/un.h>
6176 #ifndef UNIX_PATH_MAX
6177 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6178 #endif
6180 /* Where we put the socked used for synchronization. */
6181 #define SOCK_DIR P_tmpdir
6183 /* Thread ID of the helper thread. GDBserver reads this to know which
6184 is the help thread. This is an LWP id on Linux. */
6185 extern "C" {
6186 IP_AGENT_EXPORT_VAR int helper_thread_id;
6189 static int
6190 init_named_socket (const char *name)
6192 int result, fd;
6193 struct sockaddr_un addr;
6195 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6196 if (result == -1)
6198 warning ("socket creation failed: %s", safe_strerror (errno));
6199 return -1;
6202 addr.sun_family = AF_UNIX;
6204 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6206 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6207 return -1;
6210 strcpy (addr.sun_path, name);
6212 result = access (name, F_OK);
6213 if (result == 0)
6215 /* File exists. */
6216 result = unlink (name);
6217 if (result == -1)
6219 warning ("unlink failed: %s", safe_strerror (errno));
6220 close (fd);
6221 return -1;
6223 warning ("socket %s already exists; overwriting", name);
6226 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6227 if (result == -1)
6229 warning ("bind failed: %s", safe_strerror (errno));
6230 close (fd);
6231 return -1;
6234 result = listen (fd, 1);
6235 if (result == -1)
6237 warning ("listen: %s", safe_strerror (errno));
6238 close (fd);
6239 return -1;
6242 return fd;
6245 static char agent_socket_name[UNIX_PATH_MAX];
6247 static int
6248 gdb_agent_socket_init (void)
6250 int result, fd;
6252 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6253 SOCK_DIR, getpid ());
6254 if (result >= UNIX_PATH_MAX)
6256 trace_debug ("string overflow allocating socket name");
6257 return -1;
6260 fd = init_named_socket (agent_socket_name);
6261 if (fd < 0)
6262 warning ("Error initializing named socket (%s) for communication with the "
6263 "ust helper thread. Check that directory exists and that it "
6264 "is writable.", agent_socket_name);
6266 return fd;
6269 #include <sys/syscall.h>
6271 static void
6272 gdb_agent_remove_socket (void)
6274 unlink (agent_socket_name);
6277 /* Helper thread of agent. */
6279 static void *
6280 gdb_agent_helper_thread (void *arg)
6282 int listen_fd;
6284 atexit (gdb_agent_remove_socket);
6286 while (1)
6288 listen_fd = gdb_agent_socket_init ();
6290 if (helper_thread_id == 0)
6291 helper_thread_id = syscall (SYS_gettid);
6293 if (listen_fd == -1)
6295 warning ("could not create sync socket");
6296 break;
6299 while (1)
6301 socklen_t tmp;
6302 struct sockaddr_un sockaddr;
6303 int fd;
6304 char buf[1];
6305 int ret;
6306 int stop_loop = 0;
6308 tmp = sizeof (sockaddr);
6312 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
6314 /* It seems an ERESTARTSYS can escape out of accept. */
6315 while (fd == -512 || (fd == -1 && errno == EINTR));
6317 if (fd < 0)
6319 warning ("Accept returned %d, error: %s",
6320 fd, safe_strerror (errno));
6321 break;
6326 ret = read (fd, buf, 1);
6327 } while (ret == -1 && errno == EINTR);
6329 if (ret == -1)
6331 warning ("reading socket (fd=%d) failed with %s",
6332 fd, safe_strerror (errno));
6333 close (fd);
6334 break;
6337 if (cmd_buf[0])
6339 if (startswith (cmd_buf, "close"))
6341 stop_loop = 1;
6345 /* Fix compiler's warning: ignoring return value of 'write'. */
6346 ret = write (fd, buf, 1);
6347 close (fd);
6349 if (stop_loop)
6351 close (listen_fd);
6352 unlink (agent_socket_name);
6354 /* Sleep endlessly to wait the whole inferior stops. This
6355 thread can not exit because GDB or GDBserver may still need
6356 'current_thread' (representing this thread) to access
6357 inferior memory. Otherwise, this thread exits earlier than
6358 other threads, and 'current_thread' is set to NULL. */
6359 while (1)
6360 sleep (10);
6365 return NULL;
6368 #include <signal.h>
6369 #include <pthread.h>
6371 extern "C" {
6372 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
6375 static void
6376 gdb_agent_init (void)
6378 int res;
6379 pthread_t thread;
6380 sigset_t new_mask;
6381 sigset_t orig_mask;
6383 /* We want the helper thread to be as transparent as possible, so
6384 have it inherit an all-signals-blocked mask. */
6386 sigfillset (&new_mask);
6387 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
6388 if (res)
6389 perror_with_name ("pthread_sigmask (1)");
6391 res = pthread_create (&thread,
6392 NULL,
6393 gdb_agent_helper_thread,
6394 NULL);
6396 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
6397 if (res)
6398 perror_with_name ("pthread_sigmask (2)");
6400 while (helper_thread_id == 0)
6401 usleep (1);
6404 #include <sys/mman.h>
6406 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
6407 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
6408 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
6409 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
6410 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
6411 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
6413 /* Record the result of getting buffer space for fast tracepoint
6414 trampolines. Any error message is copied, since caller may not be
6415 using persistent storage. */
6417 void
6418 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
6420 gdb_trampoline_buffer = (char *) (uintptr_t) begin;
6421 gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
6422 if (errmsg)
6423 strncpy (gdb_trampoline_buffer_error, errmsg, 99);
6424 else
6425 strcpy (gdb_trampoline_buffer_error, "no buffer passed");
6428 static void __attribute__ ((constructor))
6429 initialize_tracepoint_ftlib (void)
6431 initialize_tracepoint ();
6433 gdb_agent_init ();
6436 #ifndef HAVE_GETAUXVAL
6437 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
6438 found, 0 is returned. This function is provided if glibc is too old. */
6440 unsigned long
6441 getauxval (unsigned long type)
6443 unsigned long data[2];
6444 FILE *f = fopen ("/proc/self/auxv", "r");
6445 unsigned long value = 0;
6447 if (f == NULL)
6448 return 0;
6450 while (fread (data, sizeof (data), 1, f) > 0)
6452 if (data[0] == type)
6454 value = data[1];
6455 break;
6459 fclose (f);
6460 return value;
6462 #endif
6464 #endif /* IN_PROCESS_AGENT */
6466 /* Return a timestamp, expressed as microseconds of the usual Unix
6467 time. (As the result is a 64-bit number, it will not overflow any
6468 time soon.) */
6470 static LONGEST
6471 get_timestamp (void)
6473 using namespace std::chrono;
6475 steady_clock::time_point now = steady_clock::now ();
6476 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
6479 void
6480 initialize_tracepoint (void)
6482 /* Start with the default size. */
6483 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
6485 /* Wire trace state variable 1 to be the timestamp. This will be
6486 uploaded to GDB upon connection and become one of its trace state
6487 variables. (In case you're wondering, if GDB already has a trace
6488 variable numbered 1, it will be renumbered.) */
6489 create_trace_state_variable (1, 0);
6490 set_trace_state_variable_name (1, "trace_timestamp");
6491 set_trace_state_variable_getter (1, get_timestamp);
6493 #ifdef IN_PROCESS_AGENT
6495 int pagesize;
6496 size_t jump_pad_size;
6498 pagesize = sysconf (_SC_PAGE_SIZE);
6499 if (pagesize == -1)
6500 perror_with_name ("sysconf");
6502 #define SCRATCH_BUFFER_NPAGES 20
6504 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
6506 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
6507 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
6508 if (gdb_jump_pad_buffer == NULL)
6509 perror_with_name ("mmap");
6510 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
6513 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
6515 /* It's not a fatal error for something to go wrong with trampoline
6516 buffer setup, but it can be mysterious, so create a channel to
6517 report back on what went wrong, using a fixed size since we may
6518 not be able to allocate space later when the problem occurs. */
6519 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
6521 strcpy (gdb_trampoline_buffer_error, "No errors reported");
6523 initialize_low_tracepoint ();
6524 #endif