gdb/python: implement Python find_exec_by_build_id hook
[binutils-gdb.git] / gdbserver / tracepoint.cc
blobf7b0a3ee1c13e795f2917877f0449bf23666d5f4
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 ust_loaded IPA_SYM_EXPORTED_NAME (ust_loaded)
129 # define helper_thread_id IPA_SYM_EXPORTED_NAME (helper_thread_id)
130 # define cmd_buf IPA_SYM_EXPORTED_NAME (cmd_buf)
131 # define ipa_tdesc_idx IPA_SYM_EXPORTED_NAME (ipa_tdesc_idx)
132 #endif
134 #ifndef IN_PROCESS_AGENT
136 /* Addresses of in-process agent's symbols GDBserver cares about. */
138 struct ipa_sym_addresses
140 CORE_ADDR addr_gdb_tp_heap_buffer;
141 CORE_ADDR addr_gdb_jump_pad_buffer;
142 CORE_ADDR addr_gdb_jump_pad_buffer_end;
143 CORE_ADDR addr_gdb_trampoline_buffer;
144 CORE_ADDR addr_gdb_trampoline_buffer_end;
145 CORE_ADDR addr_gdb_trampoline_buffer_error;
146 CORE_ADDR addr_collecting;
147 CORE_ADDR addr_gdb_collect_ptr;
148 CORE_ADDR addr_stop_tracing;
149 CORE_ADDR addr_flush_trace_buffer;
150 CORE_ADDR addr_about_to_request_buffer_space;
151 CORE_ADDR addr_trace_buffer_is_full;
152 CORE_ADDR addr_stopping_tracepoint;
153 CORE_ADDR addr_expr_eval_result;
154 CORE_ADDR addr_error_tracepoint;
155 CORE_ADDR addr_tracepoints;
156 CORE_ADDR addr_tracing;
157 CORE_ADDR addr_trace_buffer_ctrl;
158 CORE_ADDR addr_trace_buffer_ctrl_curr;
159 CORE_ADDR addr_trace_buffer_lo;
160 CORE_ADDR addr_trace_buffer_hi;
161 CORE_ADDR addr_traceframe_read_count;
162 CORE_ADDR addr_traceframe_write_count;
163 CORE_ADDR addr_traceframes_created;
164 CORE_ADDR addr_trace_state_variables;
165 CORE_ADDR addr_get_raw_reg_ptr;
166 CORE_ADDR addr_get_trace_state_variable_value_ptr;
167 CORE_ADDR addr_set_trace_state_variable_value_ptr;
168 CORE_ADDR addr_ust_loaded;
169 CORE_ADDR addr_ipa_tdesc_idx;
172 static struct
174 const char *name;
175 int offset;
176 } symbol_list[] = {
177 IPA_SYM(gdb_tp_heap_buffer),
178 IPA_SYM(gdb_jump_pad_buffer),
179 IPA_SYM(gdb_jump_pad_buffer_end),
180 IPA_SYM(gdb_trampoline_buffer),
181 IPA_SYM(gdb_trampoline_buffer_end),
182 IPA_SYM(gdb_trampoline_buffer_error),
183 IPA_SYM(collecting),
184 IPA_SYM(gdb_collect_ptr),
185 IPA_SYM(stop_tracing),
186 IPA_SYM(flush_trace_buffer),
187 IPA_SYM(about_to_request_buffer_space),
188 IPA_SYM(trace_buffer_is_full),
189 IPA_SYM(stopping_tracepoint),
190 IPA_SYM(expr_eval_result),
191 IPA_SYM(error_tracepoint),
192 IPA_SYM(tracepoints),
193 IPA_SYM(tracing),
194 IPA_SYM(trace_buffer_ctrl),
195 IPA_SYM(trace_buffer_ctrl_curr),
196 IPA_SYM(trace_buffer_lo),
197 IPA_SYM(trace_buffer_hi),
198 IPA_SYM(traceframe_read_count),
199 IPA_SYM(traceframe_write_count),
200 IPA_SYM(traceframes_created),
201 IPA_SYM(trace_state_variables),
202 IPA_SYM(get_raw_reg_ptr),
203 IPA_SYM(get_trace_state_variable_value_ptr),
204 IPA_SYM(set_trace_state_variable_value_ptr),
205 IPA_SYM(ust_loaded),
206 IPA_SYM(ipa_tdesc_idx),
209 static struct ipa_sym_addresses ipa_sym_addrs;
211 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
213 /* Returns true if both the in-process agent library and the static
214 tracepoints libraries are loaded in the inferior, and agent has
215 capability on static tracepoints. */
217 static int
218 in_process_agent_supports_ust (void)
220 int loaded = 0;
222 if (!agent_loaded_p ())
224 warning ("In-process agent not loaded");
225 return 0;
228 if (agent_capability_check (AGENT_CAPA_STATIC_TRACE))
230 /* Agent understands static tracepoint, then check whether UST is in
231 fact loaded in the inferior. */
232 if (read_inferior_integer (ipa_sym_addrs.addr_ust_loaded, &loaded))
234 warning ("Error reading ust_loaded in lib");
235 return 0;
238 return loaded;
240 else
241 return 0;
244 static void
245 write_e_ipa_not_loaded (char *buffer)
247 sprintf (buffer,
248 "E.In-process agent library not loaded in process. "
249 "Fast and static tracepoints unavailable.");
252 /* Write an error to BUFFER indicating that UST isn't loaded in the
253 inferior. */
255 static void
256 write_e_ust_not_loaded (char *buffer)
258 #ifdef HAVE_UST
259 sprintf (buffer,
260 "E.UST library not loaded in process. "
261 "Static tracepoints unavailable.");
262 #else
263 sprintf (buffer, "E.GDBserver was built without static tracepoints support");
264 #endif
267 /* If the in-process agent library isn't loaded in the inferior, write
268 an error to BUFFER, and return 1. Otherwise, return 0. */
270 static int
271 maybe_write_ipa_not_loaded (char *buffer)
273 if (!agent_loaded_p ())
275 write_e_ipa_not_loaded (buffer);
276 return 1;
278 return 0;
281 /* If the in-process agent library and the ust (static tracepoints)
282 library aren't loaded in the inferior, write an error to BUFFER,
283 and return 1. Otherwise, return 0. */
285 static int
286 maybe_write_ipa_ust_not_loaded (char *buffer)
288 if (!agent_loaded_p ())
290 write_e_ipa_not_loaded (buffer);
291 return 1;
293 else if (!in_process_agent_supports_ust ())
295 write_e_ust_not_loaded (buffer);
296 return 1;
298 return 0;
301 /* Cache all future symbols that the tracepoints module might request.
302 We can not request symbols at arbitrary states in the remote
303 protocol, only when the client tells us that new symbols are
304 available. So when we load the in-process library, make sure to
305 check the entire list. */
307 void
308 tracepoint_look_up_symbols (void)
310 int i;
312 if (agent_loaded_p ())
313 return;
315 for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
317 CORE_ADDR *addrp =
318 (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
320 if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
322 threads_debug_printf ("symbol `%s' not found", symbol_list[i].name);
323 return;
327 agent_look_up_symbols (NULL);
330 #endif
332 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
333 of the "stop_tracing" function. When this breakpoint is hit,
334 tracing stopped in the IPA for some reason. E.g., due to
335 tracepoint reaching the pass count, hitting conditional expression
336 evaluation error, etc.
338 The IPA's trace buffer is never in circular tracing mode: instead,
339 GDBserver's is, and whenever the in-process buffer fills, it calls
340 "flush_trace_buffer", which triggers an internal breakpoint.
341 GDBserver reacts to this breakpoint by pulling the meanwhile
342 collected data. Old frames discarding is always handled on the
343 GDBserver side. */
345 #ifdef IN_PROCESS_AGENT
346 /* See target.h. */
349 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
351 memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
352 return 0;
355 /* Call this in the functions where GDBserver places a breakpoint, so
356 that the compiler doesn't try to be clever and skip calling the
357 function at all. This is necessary, even if we tell the compiler
358 to not inline said functions. */
360 #if defined(__GNUC__)
361 # define UNKNOWN_SIDE_EFFECTS() asm ("")
362 #else
363 # define UNKNOWN_SIDE_EFFECTS() do {} while (0)
364 #endif
366 /* This is needed for -Wmissing-declarations. */
367 IP_AGENT_EXPORT_FUNC void stop_tracing (void);
369 IP_AGENT_EXPORT_FUNC void
370 stop_tracing (void)
372 /* GDBserver places breakpoint here. */
373 UNKNOWN_SIDE_EFFECTS();
376 /* This is needed for -Wmissing-declarations. */
377 IP_AGENT_EXPORT_FUNC void flush_trace_buffer (void);
379 IP_AGENT_EXPORT_FUNC void
380 flush_trace_buffer (void)
382 /* GDBserver places breakpoint here. */
383 UNKNOWN_SIDE_EFFECTS();
386 #endif
388 #ifndef IN_PROCESS_AGENT
389 static int
390 tracepoint_handler (CORE_ADDR address)
392 trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
393 paddress (address));
394 return 0;
397 /* Breakpoint at "stop_tracing" in the inferior lib. */
398 static struct breakpoint *stop_tracing_bkpt;
399 static int stop_tracing_handler (CORE_ADDR);
401 /* Breakpoint at "flush_trace_buffer" in the inferior lib. */
402 static struct breakpoint *flush_trace_buffer_bkpt;
403 static int flush_trace_buffer_handler (CORE_ADDR);
405 static void download_trace_state_variables (void);
406 static void upload_fast_traceframes (void);
408 static int run_inferior_command (char *cmd, int len);
410 static int
411 read_inferior_integer (CORE_ADDR symaddr, int *val)
413 return read_inferior_memory (symaddr, (unsigned char *) val,
414 sizeof (*val));
417 struct tracepoint;
418 static int tracepoint_send_agent (struct tracepoint *tpoint);
420 static int
421 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
423 return read_inferior_memory (symaddr, (unsigned char *) val,
424 sizeof (*val));
427 static int
428 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
430 void *pval = (void *) (uintptr_t) val;
431 int ret;
433 ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
434 *val = (uintptr_t) pval;
435 return ret;
438 static int
439 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
441 void *pval = (void *) (uintptr_t) val;
442 return target_write_memory (symaddr,
443 (unsigned char *) &pval, sizeof (pval));
446 static int
447 write_inferior_integer (CORE_ADDR symaddr, int val)
449 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
452 static int
453 write_inferior_int8 (CORE_ADDR symaddr, int8_t val)
455 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
458 static int
459 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
461 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
464 static CORE_ADDR target_malloc (ULONGEST size);
466 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD) \
467 do { \
468 memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
469 BUF += sizeof ((OBJ)->FIELD); \
470 } while (0)
472 #endif
474 /* Base action. Concrete actions inherit this. */
476 struct tracepoint_action
478 char type;
481 /* An 'M' (collect memory) action. */
482 struct collect_memory_action
484 struct tracepoint_action base;
486 ULONGEST addr;
487 ULONGEST len;
488 int32_t basereg;
491 /* An 'R' (collect registers) action. */
493 struct collect_registers_action
495 struct tracepoint_action base;
498 /* An 'X' (evaluate expression) action. */
500 struct eval_expr_action
502 struct tracepoint_action base;
504 struct agent_expr *expr;
507 /* An 'L' (collect static trace data) action. */
508 struct collect_static_trace_data_action
510 struct tracepoint_action base;
513 #ifndef IN_PROCESS_AGENT
514 static CORE_ADDR
515 m_tracepoint_action_download (const struct tracepoint_action *action)
517 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_memory_action));
519 target_write_memory (ipa_action, (unsigned char *) action,
520 sizeof (struct collect_memory_action));
522 return ipa_action;
524 static char *
525 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
527 struct collect_memory_action *maction
528 = (struct collect_memory_action *) action;
530 COPY_FIELD_TO_BUF (buffer, maction, addr);
531 COPY_FIELD_TO_BUF (buffer, maction, len);
532 COPY_FIELD_TO_BUF (buffer, maction, basereg);
534 return buffer;
537 static CORE_ADDR
538 r_tracepoint_action_download (const struct tracepoint_action *action)
540 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_registers_action));
542 target_write_memory (ipa_action, (unsigned char *) action,
543 sizeof (struct collect_registers_action));
545 return ipa_action;
548 static char *
549 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
551 return buffer;
554 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
556 static CORE_ADDR
557 x_tracepoint_action_download (const struct tracepoint_action *action)
559 CORE_ADDR ipa_action = target_malloc (sizeof (struct eval_expr_action));
560 CORE_ADDR expr;
562 target_write_memory (ipa_action, (unsigned char *) action,
563 sizeof (struct eval_expr_action));
564 expr = download_agent_expr (((struct eval_expr_action *) action)->expr);
565 write_inferior_data_pointer (ipa_action
566 + offsetof (struct eval_expr_action, expr),
567 expr);
569 return ipa_action;
572 /* Copy agent expression AEXPR to buffer pointed by P. If AEXPR is NULL,
573 copy 0 to P. Return updated header of buffer. */
575 static char *
576 agent_expr_send (char *p, const struct agent_expr *aexpr)
578 /* Copy the length of condition first, and then copy its
579 content. */
580 if (aexpr == NULL)
582 memset (p, 0, 4);
583 p += 4;
585 else
587 memcpy (p, &aexpr->length, 4);
588 p +=4;
590 memcpy (p, aexpr->bytes, aexpr->length);
591 p += aexpr->length;
593 return p;
596 static char *
597 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
599 struct eval_expr_action *eaction = (struct eval_expr_action *) action;
601 return agent_expr_send (buffer, eaction->expr);
604 static CORE_ADDR
605 l_tracepoint_action_download (const struct tracepoint_action *action)
607 CORE_ADDR ipa_action
608 = target_malloc (sizeof (struct collect_static_trace_data_action));
610 target_write_memory (ipa_action, (unsigned char *) action,
611 sizeof (struct collect_static_trace_data_action));
613 return ipa_action;
616 static char *
617 l_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
619 return buffer;
622 static char *
623 tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
625 switch (action->type)
627 case 'M':
628 return m_tracepoint_action_send (buffer, action);
629 case 'R':
630 return r_tracepoint_action_send (buffer, action);
631 case 'X':
632 return x_tracepoint_action_send (buffer, action);
633 case 'L':
634 return l_tracepoint_action_send (buffer, action);
636 error ("Unknown trace action '%c'.", action->type);
639 static CORE_ADDR
640 tracepoint_action_download (const struct tracepoint_action *action)
642 switch (action->type)
644 case 'M':
645 return m_tracepoint_action_download (action);
646 case 'R':
647 return r_tracepoint_action_download (action);
648 case 'X':
649 return x_tracepoint_action_download (action);
650 case 'L':
651 return l_tracepoint_action_download (action);
653 error ("Unknown trace action '%c'.", action->type);
655 #endif
657 /* This structure describes a piece of the source-level definition of
658 the tracepoint. The contents are not interpreted by the target,
659 but preserved verbatim for uploading upon reconnection. */
661 struct source_string
663 /* The type of string, such as "cond" for a conditional. */
664 char *type;
666 /* The source-level string itself. For the sake of target
667 debugging, we store it in plaintext, even though it is always
668 transmitted in hex. */
669 char *str;
671 /* Link to the next one in the list. We link them in the order
672 received, in case some make up an ordered list of commands or
673 some such. */
674 struct source_string *next;
677 enum tracepoint_type
679 /* Trap based tracepoint. */
680 trap_tracepoint,
682 /* A fast tracepoint implemented with a jump instead of a trap. */
683 fast_tracepoint,
685 /* A static tracepoint, implemented by a program call into a tracing
686 library. */
687 static_tracepoint
690 struct tracepoint_hit_ctx;
692 typedef enum eval_result_type (*condfn) (unsigned char *,
693 ULONGEST *);
695 /* The definition of a tracepoint. */
697 /* Tracepoints may have multiple locations, each at a different
698 address. This can occur with optimizations, template
699 instantiation, etc. Since the locations may be in different
700 scopes, the conditions and actions may be different for each
701 location. Our target version of tracepoints is more like GDB's
702 notion of "breakpoint locations", but we have almost nothing that
703 is not per-location, so we bother having two kinds of objects. The
704 key consequence is that numbers are not unique, and that it takes
705 both number and address to identify a tracepoint uniquely. */
707 struct tracepoint
709 /* The number of the tracepoint, as specified by GDB. Several
710 tracepoint objects here may share a number. */
711 uint32_t number;
713 /* Address at which the tracepoint is supposed to trigger. Several
714 tracepoints may share an address. */
715 CORE_ADDR address;
717 /* Tracepoint type. */
718 enum tracepoint_type type;
720 /* True if the tracepoint is currently enabled. */
721 int8_t enabled;
723 /* The number of single steps that will be performed after each
724 tracepoint hit. */
725 uint64_t step_count;
727 /* The number of times the tracepoint may be hit before it will
728 terminate the entire tracing run. */
729 uint64_t pass_count;
731 /* Pointer to the agent expression that is the tracepoint's
732 conditional, or NULL if the tracepoint is unconditional. */
733 struct agent_expr *cond;
735 /* The list of actions to take when the tracepoint triggers. */
736 uint32_t numactions;
737 struct tracepoint_action **actions;
739 /* Count of the times we've hit this tracepoint during the run.
740 Note that while-stepping steps are not counted as "hits". */
741 uint64_t hit_count;
743 /* Cached sum of the sizes of traceframes created by this point. */
744 uint64_t traceframe_usage;
746 CORE_ADDR compiled_cond;
748 /* Link to the next tracepoint in the list. */
749 struct tracepoint *next;
751 #ifndef IN_PROCESS_AGENT
752 /* The list of actions to take when the tracepoint triggers, in
753 string/packet form. */
754 char **actions_str;
756 /* The collection of strings that describe the tracepoint as it was
757 entered into GDB. These are not used by the target, but are
758 reported back to GDB upon reconnection. */
759 struct source_string *source_strings;
761 /* The number of bytes displaced by fast tracepoints. It may subsume
762 multiple instructions, for multi-byte fast tracepoints. This
763 field is only valid for fast tracepoints. */
764 uint32_t orig_size;
766 /* Only for fast tracepoints. */
767 CORE_ADDR obj_addr_on_target;
769 /* Address range where the original instruction under a fast
770 tracepoint was relocated to. (_end is actually one byte past
771 the end). */
772 CORE_ADDR adjusted_insn_addr;
773 CORE_ADDR adjusted_insn_addr_end;
775 /* The address range of the piece of the jump pad buffer that was
776 assigned to this fast tracepoint. (_end is actually one byte
777 past the end).*/
778 CORE_ADDR jump_pad;
779 CORE_ADDR jump_pad_end;
781 /* The address range of the piece of the trampoline buffer that was
782 assigned to this fast tracepoint. (_end is actually one byte
783 past the end). */
784 CORE_ADDR trampoline;
785 CORE_ADDR trampoline_end;
787 /* The list of actions to take while in a stepping loop. These
788 fields are only valid for patch-based tracepoints. */
789 int num_step_actions;
790 struct tracepoint_action **step_actions;
791 /* Same, but in string/packet form. */
792 char **step_actions_str;
794 /* Handle returned by the breakpoint or tracepoint module when we
795 inserted the trap or jump, or hooked into a static tracepoint.
796 NULL if we haven't inserted it yet. */
797 void *handle;
798 #endif
802 #ifndef IN_PROCESS_AGENT
804 /* Given `while-stepping', a thread may be collecting data for more
805 than one tracepoint simultaneously. On the other hand, the same
806 tracepoint with a while-stepping action may be hit by more than one
807 thread simultaneously (but not quite, each thread could be handling
808 a different step). Each thread holds a list of these objects,
809 representing the current step of each while-stepping action being
810 collected. */
812 struct wstep_state
814 struct wstep_state *next;
816 /* The tracepoint number. */
817 int tp_number;
818 /* The tracepoint's address. */
819 CORE_ADDR tp_address;
821 /* The number of the current step in this 'while-stepping'
822 action. */
823 long current_step;
826 #endif
828 extern "C" {
830 /* The linked list of all tracepoints. Marked explicitly as used as
831 the in-process library doesn't use it for the fast tracepoints
832 support. */
833 IP_AGENT_EXPORT_VAR struct tracepoint *tracepoints;
835 /* The first tracepoint to exceed its pass count. */
837 IP_AGENT_EXPORT_VAR struct tracepoint *stopping_tracepoint;
839 /* True if the trace buffer is full or otherwise no longer usable. */
841 IP_AGENT_EXPORT_VAR int trace_buffer_is_full;
843 /* The first error that occurred during expression evaluation. */
845 /* Stored as an int to avoid the IPA ABI being dependent on whatever
846 the compiler decides to use for the enum's underlying type. Holds
847 enum eval_result_type values. */
848 IP_AGENT_EXPORT_VAR int expr_eval_result = expr_eval_no_error;
852 #ifndef IN_PROCESS_AGENT
854 /* Pointer to the last tracepoint in the list, new tracepoints are
855 linked in at the end. */
857 static struct tracepoint *last_tracepoint;
859 static const char * const eval_result_names[] =
861 #define AX_RESULT_TYPE(ENUM,STR) STR,
862 #include "ax-result-types.def"
863 #undef AX_RESULT_TYPE
866 #endif
868 /* The tracepoint in which the error occurred. */
870 extern "C" {
871 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
874 struct trace_state_variable
876 /* This is the name of the variable as used in GDB. The target
877 doesn't use the name, but needs to have it for saving and
878 reconnection purposes. */
879 char *name;
881 /* This number identifies the variable uniquely. Numbers may be
882 assigned either by the target (in the case of builtin variables),
883 or by GDB, and are presumed unique during the course of a trace
884 experiment. */
885 int number;
887 /* The variable's initial value, a 64-bit signed integer always. */
888 LONGEST initial_value;
890 /* The variable's value, a 64-bit signed integer always. */
891 LONGEST value;
893 /* Pointer to a getter function, used to supply computed values. */
894 LONGEST (*getter) (void);
896 /* Link to the next variable. */
897 struct trace_state_variable *next;
900 /* Linked list of all trace state variables. */
902 #ifdef IN_PROCESS_AGENT
903 static struct trace_state_variable *alloced_trace_state_variables;
904 #endif
906 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
908 /* The results of tracing go into a fixed-size space known as the
909 "trace buffer". Because usage follows a limited number of
910 patterns, we manage it ourselves rather than with malloc. Basic
911 rules are that we create only one trace frame at a time, each is
912 variable in size, they are never moved once created, and we only
913 discard if we are doing a circular buffer, and then only the oldest
914 ones. Each trace frame includes its own size, so we don't need to
915 link them together, and the trace frame number is relative to the
916 first one, so we don't need to record numbers. A trace frame also
917 records the number of the tracepoint that created it. The data
918 itself is a series of blocks, each introduced by a single character
919 and with a defined format. Each type of block has enough
920 type/length info to allow scanners to jump quickly from one block
921 to the next without reading each byte in the block. */
923 /* Trace buffer management would be simple - advance a free pointer
924 from beginning to end, then stop - were it not for the circular
925 buffer option, which is a useful way to prevent a trace run from
926 stopping prematurely because the buffer filled up. In the circular
927 case, the location of the first trace frame (trace_buffer_start)
928 moves as old trace frames are discarded. Also, since we grow trace
929 frames incrementally as actions are performed, we wrap around to
930 the beginning of the trace buffer. This is per-block, so each
931 block within a trace frame remains contiguous. Things get messy
932 when the wrapped-around trace frame is the one being discarded; the
933 free space ends up in two parts at opposite ends of the buffer. */
935 #ifndef ATTR_PACKED
936 # if defined(__GNUC__)
937 # define ATTR_PACKED __attribute__ ((packed))
938 # else
939 # define ATTR_PACKED /* nothing */
940 # endif
941 #endif
943 /* The data collected at a tracepoint hit. This object should be as
944 small as possible, since there may be a great many of them. We do
945 not need to keep a frame number, because they are all sequential
946 and there are no deletions; so the Nth frame in the buffer is
947 always frame number N. */
949 struct traceframe
951 /* Number of the tracepoint that collected this traceframe. A value
952 of 0 indicates the current end of the trace buffer. We make this
953 a 16-bit field because it's never going to happen that GDB's
954 numbering of tracepoints reaches 32,000. */
955 int tpnum : 16;
957 /* The size of the data in this trace frame. We limit this to 32
958 bits, even on a 64-bit target, because it's just implausible that
959 one is validly going to collect 4 gigabytes of data at a single
960 tracepoint hit. */
961 unsigned int data_size : 32;
963 /* The base of the trace data, which is contiguous from this point. */
964 unsigned char data[0];
966 } ATTR_PACKED;
968 /* The size of the EOB marker, in bytes. A traceframe with zeroed
969 fields (and no data) marks the end of trace data. */
970 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
972 /* This flag is true if the trace buffer is circular, meaning that
973 when it fills, the oldest trace frames are discarded in order to
974 make room. */
976 #ifndef IN_PROCESS_AGENT
977 static int circular_trace_buffer;
978 #endif
980 /* Size of the trace buffer. */
982 static LONGEST trace_buffer_size;
984 extern "C" {
986 /* Pointer to the block of memory that traceframes all go into. */
988 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
990 /* Pointer to the end of the trace buffer, more precisely to the byte
991 after the end of the buffer. */
993 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
997 /* Control structure holding the read/write/etc. pointers into the
998 trace buffer. We need more than one of these to implement a
999 transaction-like mechanism to guarantees that both GDBserver and the
1000 in-process agent can try to change the trace buffer
1001 simultaneously. */
1003 struct trace_buffer_control
1005 /* Pointer to the first trace frame in the buffer. In the
1006 non-circular case, this is equal to trace_buffer_lo, otherwise it
1007 moves around in the buffer. */
1008 unsigned char *start;
1010 /* Pointer to the free part of the trace buffer. Note that we clear
1011 several bytes at and after this pointer, so that traceframe
1012 scans/searches terminate properly. */
1013 unsigned char *free;
1015 /* Pointer to the byte after the end of the free part. Note that
1016 this may be smaller than trace_buffer_free in the circular case,
1017 and means that the free part is in two pieces. Initially it is
1018 equal to trace_buffer_hi, then is generally equivalent to
1019 trace_buffer_start. */
1020 unsigned char *end_free;
1022 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
1023 this is the point at which the trace data breaks, and resumes at
1024 trace_buffer_lo. */
1025 unsigned char *wrap;
1028 /* Same as above, to be used by GDBserver when updating the in-process
1029 agent. */
1030 struct ipa_trace_buffer_control
1032 uintptr_t start;
1033 uintptr_t free;
1034 uintptr_t end_free;
1035 uintptr_t wrap;
1039 /* We have possibly both GDBserver and an inferior thread accessing
1040 the same IPA trace buffer memory. The IPA is the producer (tries
1041 to put new frames in the buffer), while GDBserver occasionally
1042 consumes them, that is, flushes the IPA's buffer into its own
1043 buffer. Both sides need to update the trace buffer control
1044 pointers (current head, tail, etc.). We can't use a global lock to
1045 synchronize the accesses, as otherwise we could deadlock GDBserver
1046 (if the thread holding the lock stops for a signal, say). So
1047 instead of that, we use a transaction scheme where GDBserver writes
1048 always prevail over the IPAs writes, and, we have the IPA detect
1049 the commit failure/overwrite, and retry the whole attempt. This is
1050 mainly implemented by having a global token object that represents
1051 who wrote last to the buffer control structure. We need to freeze
1052 any inferior writing to the buffer while GDBserver touches memory,
1053 so that the inferior can correctly detect that GDBserver had been
1054 there, otherwise, it could mistakingly think its commit was
1055 successful; that's implemented by simply having GDBserver set a
1056 breakpoint the inferior hits if it is the critical region.
1058 There are three cycling trace buffer control structure copies
1059 (buffer head, tail, etc.), with the token object including an index
1060 indicating which is current live copy. The IPA tentatively builds
1061 an updated copy in a non-current control structure, while GDBserver
1062 always clobbers the current version directly. The IPA then tries
1063 to atomically "commit" its version; if GDBserver clobbered the
1064 structure meanwhile, that will fail, and the IPA restarts the
1065 allocation process.
1067 Listing the step in further detail, we have:
1069 In-process agent (producer):
1071 - passes by `about_to_request_buffer_space' breakpoint/lock
1073 - reads current token, extracts current trace buffer control index,
1074 and starts tentatively updating the rightmost one (0->1, 1->2,
1075 2->0). Note that only one inferior thread is executing this code
1076 at any given time, due to an outer lock in the jump pads.
1078 - updates counters, and tries to commit the token.
1080 - passes by second `about_to_request_buffer_space' breakpoint/lock,
1081 leaving the sync region.
1083 - checks if the update was effective.
1085 - if trace buffer was found full, hits flush_trace_buffer
1086 breakpoint, and restarts later afterwards.
1088 GDBserver (consumer):
1090 - sets `about_to_request_buffer_space' breakpoint/lock.
1092 - updates the token unconditionally, using the current buffer
1093 control index, since it knows that the IP agent always writes to
1094 the rightmost, and due to the breakpoint, at most one IP thread
1095 can try to update the trace buffer concurrently to GDBserver, so
1096 there will be no danger of trace buffer control index wrap making
1097 the IPA write to the same index as GDBserver.
1099 - flushes the IP agent's trace buffer completely, and updates the
1100 current trace buffer control structure. GDBserver *always* wins.
1102 - removes the `about_to_request_buffer_space' breakpoint.
1104 The token is stored in the `trace_buffer_ctrl_curr' variable.
1105 Internally, it's bits are defined as:
1107 |-------------+-----+-------------+--------+-------------+--------------|
1108 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1109 |-------------+-----+-------------+--------+-------------+--------------|
1110 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1111 |-------------+-----+-------------+--------+-------------+--------------|
1113 GSB - GDBserver Stamp Bit
1114 PC - Previous Counter
1115 CC - Current Counter
1116 TBCI - Trace Buffer Control Index
1119 An IPA update of `trace_buffer_ctrl_curr' does:
1121 - read CC from the current token, save as PC.
1122 - updates pointers
1123 - atomically tries to write PC+1,CC
1125 A GDBserver update of `trace_buffer_ctrl_curr' does:
1127 - reads PC and CC from the current token.
1128 - updates pointers
1129 - writes GSB,PC,CC
1132 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1133 for the counters described below. The cleared bits are used to
1134 hold the index of the items of the `trace_buffer_ctrl' array that
1135 is "current". */
1136 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1138 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1139 counter, and the `current' counter. */
1141 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1142 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1144 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1145 always stamps this bit as set. */
1146 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1148 #ifdef IN_PROCESS_AGENT
1149 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1150 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1152 # define TRACE_BUFFER_CTRL_CURR \
1153 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1155 #else
1157 /* The GDBserver side agent only needs one instance of this object, as
1158 it doesn't need to sync with itself. Define it as array anyway so
1159 that the rest of the code base doesn't need to care for the
1160 difference. */
1161 static trace_buffer_control trace_buffer_ctrl[1];
1162 # define TRACE_BUFFER_CTRL_CURR 0
1163 #endif
1165 /* These are convenience macros used to access the current trace
1166 buffer control in effect. */
1167 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1168 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1169 #define trace_buffer_end_free \
1170 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1171 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1174 /* Macro that returns a pointer to the first traceframe in the buffer. */
1176 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1178 /* Macro that returns a pointer to the next traceframe in the buffer.
1179 If the computed location is beyond the wraparound point, subtract
1180 the offset of the wraparound. */
1182 #define NEXT_TRACEFRAME_1(TF) \
1183 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1185 #define NEXT_TRACEFRAME(TF) \
1186 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1187 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1188 ? (trace_buffer_wrap - trace_buffer_lo) \
1189 : 0)))
1191 /* The difference between these counters represents the total number
1192 of complete traceframes present in the trace buffer. The IP agent
1193 writes to the write count, GDBserver writes to read count. */
1195 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1196 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1198 /* Convenience macro. */
1200 #define traceframe_count \
1201 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1203 /* The count of all traceframes created in the current run, including
1204 ones that were discarded to make room. */
1206 IP_AGENT_EXPORT_VAR int traceframes_created;
1208 #ifndef IN_PROCESS_AGENT
1210 /* Read-only regions are address ranges whose contents don't change,
1211 and so can be read from target memory even while looking at a trace
1212 frame. Without these, disassembly for instance will likely fail,
1213 because the program code is not usually collected into a trace
1214 frame. This data structure does not need to be very complicated or
1215 particularly efficient, it's only going to be used occasionally,
1216 and only by some commands. */
1218 struct readonly_region
1220 /* The bounds of the region. */
1221 CORE_ADDR start, end;
1223 /* Link to the next one. */
1224 struct readonly_region *next;
1227 /* Linked list of readonly regions. This list stays in effect from
1228 one tstart to the next. */
1230 static struct readonly_region *readonly_regions;
1232 #endif
1234 /* The global that controls tracing overall. */
1236 IP_AGENT_EXPORT_VAR int tracing;
1238 #ifndef IN_PROCESS_AGENT
1240 /* Controls whether tracing should continue after GDB disconnects. */
1242 int disconnected_tracing;
1244 /* The reason for the last tracing run to have stopped. We initialize
1245 to a distinct string so that GDB can distinguish between "stopped
1246 after running" and "stopped because never run" cases. */
1248 static const char *tracing_stop_reason = "tnotrun";
1250 static int tracing_stop_tpnum;
1252 /* 64-bit timestamps for the trace run's start and finish, expressed
1253 in microseconds from the Unix epoch. */
1255 static LONGEST tracing_start_time;
1256 static LONGEST tracing_stop_time;
1258 /* The (optional) user-supplied name of the user that started the run.
1259 This is an arbitrary string, and may be NULL. */
1261 static char *tracing_user_name;
1263 /* Optional user-supplied text describing the run. This is
1264 an arbitrary string, and may be NULL. */
1266 static char *tracing_notes;
1268 /* Optional user-supplied text explaining a tstop command. This is an
1269 arbitrary string, and may be NULL. */
1271 static char *tracing_stop_note;
1273 #endif
1275 /* Functions local to this file. */
1277 /* Base "class" for tracepoint type specific data to be passed down to
1278 collect_data_at_tracepoint. */
1279 struct tracepoint_hit_ctx
1281 enum tracepoint_type type;
1284 #ifdef IN_PROCESS_AGENT
1286 /* Fast/jump tracepoint specific data to be passed down to
1287 collect_data_at_tracepoint. */
1288 struct fast_tracepoint_ctx
1290 struct tracepoint_hit_ctx base;
1292 struct regcache regcache;
1293 int regcache_initted;
1294 unsigned char *regspace;
1296 unsigned char *regs;
1297 struct tracepoint *tpoint;
1300 /* Static tracepoint specific data to be passed down to
1301 collect_data_at_tracepoint. */
1302 struct static_tracepoint_ctx
1304 struct tracepoint_hit_ctx base;
1306 /* The regcache corresponding to the registers state at the time of
1307 the tracepoint hit. Initialized lazily, from REGS. */
1308 struct regcache regcache;
1309 int regcache_initted;
1311 /* The buffer space REGCACHE above uses. We use a separate buffer
1312 instead of letting the regcache malloc for both signal safety and
1313 performance reasons; this is allocated on the stack instead. */
1314 unsigned char *regspace;
1316 /* The register buffer as passed on by lttng/ust. */
1317 struct registers *regs;
1319 /* The "printf" formatter and the args the user passed to the marker
1320 call. We use this to be able to collect "static trace data"
1321 ($_sdata). */
1322 const char *fmt;
1323 va_list *args;
1325 /* The GDB tracepoint matching the probed marker that was "hit". */
1326 struct tracepoint *tpoint;
1329 #else
1331 /* Static tracepoint specific data to be passed down to
1332 collect_data_at_tracepoint. */
1333 struct trap_tracepoint_ctx
1335 struct tracepoint_hit_ctx base;
1337 struct regcache *regcache;
1340 #endif
1342 #ifndef IN_PROCESS_AGENT
1343 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1344 static int traceframe_read_tsv (int num, LONGEST *val);
1345 #endif
1347 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1348 struct tracepoint *tpoint);
1350 #ifndef IN_PROCESS_AGENT
1351 static void clear_readonly_regions (void);
1352 static void clear_installed_tracepoints (void);
1353 #endif
1355 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1356 CORE_ADDR stop_pc,
1357 struct tracepoint *tpoint);
1358 #ifndef IN_PROCESS_AGENT
1359 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1360 CORE_ADDR stop_pc,
1361 struct tracepoint *tpoint, int current_step);
1362 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1363 CORE_ADDR *jump_entry);
1364 #endif
1365 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1366 CORE_ADDR stop_pc,
1367 struct tracepoint *tpoint,
1368 struct traceframe *tframe,
1369 struct tracepoint_action *taction);
1371 #ifndef IN_PROCESS_AGENT
1372 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1374 static void install_tracepoint (struct tracepoint *, char *own_buf);
1375 static void download_tracepoint (struct tracepoint *);
1376 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1377 static void clone_fast_tracepoint (struct tracepoint *to,
1378 const struct tracepoint *from);
1379 #endif
1381 static LONGEST get_timestamp (void);
1383 #if defined(__GNUC__)
1384 # define memory_barrier() asm volatile ("" : : : "memory")
1385 #else
1386 # define memory_barrier() do {} while (0)
1387 #endif
1389 /* We only build the IPA if this builtin is supported, and there are
1390 no uses of this in GDBserver itself, so we're safe in defining this
1391 unconditionally. */
1392 #define cmpxchg(mem, oldval, newval) \
1393 __sync_val_compare_and_swap (mem, oldval, newval)
1395 /* Record that an error occurred during expression evaluation. */
1397 static void
1398 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1399 enum eval_result_type rtype)
1401 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1402 tpoint->number, paddress (tpoint->address), which, rtype);
1404 #ifdef IN_PROCESS_AGENT
1405 /* Only record the first error we get. */
1406 if (cmpxchg (&expr_eval_result,
1407 expr_eval_no_error,
1408 rtype) != expr_eval_no_error)
1409 return;
1410 #else
1411 if (expr_eval_result != expr_eval_no_error)
1412 return;
1413 #endif
1415 error_tracepoint = tpoint;
1418 /* Trace buffer management. */
1420 static void
1421 clear_trace_buffer (void)
1423 trace_buffer_start = trace_buffer_lo;
1424 trace_buffer_free = trace_buffer_lo;
1425 trace_buffer_end_free = trace_buffer_hi;
1426 trace_buffer_wrap = trace_buffer_hi;
1427 /* A traceframe with zeroed fields marks the end of trace data. */
1428 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1429 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1430 traceframe_read_count = traceframe_write_count = 0;
1431 traceframes_created = 0;
1434 #ifndef IN_PROCESS_AGENT
1436 static void
1437 clear_inferior_trace_buffer (void)
1439 CORE_ADDR ipa_trace_buffer_lo;
1440 CORE_ADDR ipa_trace_buffer_hi;
1441 struct traceframe ipa_traceframe = { 0 };
1442 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1444 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1445 &ipa_trace_buffer_lo);
1446 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1447 &ipa_trace_buffer_hi);
1449 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1450 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1451 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1452 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1454 /* A traceframe with zeroed fields marks the end of trace data. */
1455 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1456 (unsigned char *) &ipa_trace_buffer_ctrl,
1457 sizeof (ipa_trace_buffer_ctrl));
1459 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1461 /* A traceframe with zeroed fields marks the end of trace data. */
1462 target_write_memory (ipa_trace_buffer_lo,
1463 (unsigned char *) &ipa_traceframe,
1464 sizeof (ipa_traceframe));
1466 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1467 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1468 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1471 #endif
1473 static void
1474 init_trace_buffer (LONGEST bufsize)
1476 size_t alloc_size;
1478 trace_buffer_size = bufsize;
1480 /* Make sure to internally allocate at least space for the EOB
1481 marker. */
1482 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1483 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1484 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1486 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1488 clear_trace_buffer ();
1491 #ifdef IN_PROCESS_AGENT
1493 /* This is needed for -Wmissing-declarations. */
1494 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1496 IP_AGENT_EXPORT_FUNC void
1497 about_to_request_buffer_space (void)
1499 /* GDBserver places breakpoint here while it goes about to flush
1500 data at random times. */
1501 UNKNOWN_SIDE_EFFECTS();
1504 #endif
1506 /* Carve out a piece of the trace buffer, returning NULL in case of
1507 failure. */
1509 static void *
1510 trace_buffer_alloc (size_t amt)
1512 unsigned char *rslt;
1513 struct trace_buffer_control *tbctrl;
1514 unsigned int curr;
1515 #ifdef IN_PROCESS_AGENT
1516 unsigned int prev, prev_filtered;
1517 unsigned int commit_count;
1518 unsigned int commit;
1519 unsigned int readout;
1520 #else
1521 struct traceframe *oldest;
1522 unsigned char *new_start;
1523 #endif
1525 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1526 (long) amt, (long) sizeof (struct traceframe));
1528 /* Account for the EOB marker. */
1529 amt += TRACEFRAME_EOB_MARKER_SIZE;
1531 #ifdef IN_PROCESS_AGENT
1532 again:
1533 memory_barrier ();
1535 /* Read the current token and extract the index to try to write to,
1536 storing it in CURR. */
1537 prev = trace_buffer_ctrl_curr;
1538 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1539 curr = prev_filtered + 1;
1540 if (curr > 2)
1541 curr = 0;
1543 about_to_request_buffer_space ();
1545 /* Start out with a copy of the current state. GDBserver may be
1546 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1547 be able to commit anyway if that happens. */
1548 trace_buffer_ctrl[curr]
1549 = trace_buffer_ctrl[prev_filtered];
1550 trace_debug ("trying curr=%u", curr);
1551 #else
1552 /* The GDBserver's agent doesn't need all that syncing, and always
1553 updates TCB 0 (there's only one, mind you). */
1554 curr = 0;
1555 #endif
1556 tbctrl = &trace_buffer_ctrl[curr];
1558 /* Offsets are easier to grok for debugging than raw addresses,
1559 especially for the small trace buffer sizes that are useful for
1560 testing. */
1561 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1562 curr,
1563 (int) (tbctrl->start - trace_buffer_lo),
1564 (int) (tbctrl->free - trace_buffer_lo),
1565 (int) (tbctrl->end_free - trace_buffer_lo),
1566 (int) (tbctrl->wrap - trace_buffer_lo),
1567 (int) (trace_buffer_hi - trace_buffer_lo));
1569 /* The algorithm here is to keep trying to get a contiguous block of
1570 the requested size, possibly discarding older traceframes to free
1571 up space. Since free space might come in one or two pieces,
1572 depending on whether discarded traceframes wrapped around at the
1573 high end of the buffer, we test both pieces after each
1574 discard. */
1575 while (1)
1577 /* First, if we have two free parts, try the upper one first. */
1578 if (tbctrl->end_free < tbctrl->free)
1580 if (tbctrl->free + amt <= trace_buffer_hi)
1581 /* We have enough in the upper part. */
1582 break;
1583 else
1585 /* Our high part of free space wasn't enough. Give up
1586 on it for now, set wraparound. We will recover the
1587 space later, if/when the wrapped-around traceframe is
1588 discarded. */
1589 trace_debug ("Upper part too small, setting wraparound");
1590 tbctrl->wrap = tbctrl->free;
1591 tbctrl->free = trace_buffer_lo;
1595 /* The normal case. */
1596 if (tbctrl->free + amt <= tbctrl->end_free)
1597 break;
1599 #ifdef IN_PROCESS_AGENT
1600 /* The IP Agent's buffer is always circular. It isn't used
1601 currently, but `circular_trace_buffer' could represent
1602 GDBserver's mode. If we didn't find space, ask GDBserver to
1603 flush. */
1605 flush_trace_buffer ();
1606 memory_barrier ();
1607 if (tracing)
1609 trace_debug ("gdbserver flushed buffer, retrying");
1610 goto again;
1613 /* GDBserver cancelled the tracing. Bail out as well. */
1614 return NULL;
1615 #else
1616 /* If we're here, then neither part is big enough, and
1617 non-circular trace buffers are now full. */
1618 if (!circular_trace_buffer)
1620 trace_debug ("Not enough space in the trace buffer");
1621 return NULL;
1624 trace_debug ("Need more space in the trace buffer");
1626 /* If we have a circular buffer, we can try discarding the
1627 oldest traceframe and see if that helps. */
1628 oldest = FIRST_TRACEFRAME ();
1629 if (oldest->tpnum == 0)
1631 /* Not good; we have no traceframes to free. Perhaps we're
1632 asking for a block that is larger than the buffer? In
1633 any case, give up. */
1634 trace_debug ("No traceframes to discard");
1635 return NULL;
1638 /* We don't run this code in the in-process agent currently.
1639 E.g., we could leave the in-process agent in autonomous
1640 circular mode if we only have fast tracepoints. If we do
1641 that, then this bit becomes racy with GDBserver, which also
1642 writes to this counter. */
1643 --traceframe_write_count;
1645 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1646 /* If we freed the traceframe that wrapped around, go back
1647 to the non-wrap case. */
1648 if (new_start < tbctrl->start)
1650 trace_debug ("Discarding past the wraparound");
1651 tbctrl->wrap = trace_buffer_hi;
1653 tbctrl->start = new_start;
1654 tbctrl->end_free = tbctrl->start;
1656 trace_debug ("Discarded a traceframe\n"
1657 "Trace buffer [%d], start=%d free=%d "
1658 "endfree=%d wrap=%d hi=%d",
1659 curr,
1660 (int) (tbctrl->start - trace_buffer_lo),
1661 (int) (tbctrl->free - trace_buffer_lo),
1662 (int) (tbctrl->end_free - trace_buffer_lo),
1663 (int) (tbctrl->wrap - trace_buffer_lo),
1664 (int) (trace_buffer_hi - trace_buffer_lo));
1666 /* Now go back around the loop. The discard might have resulted
1667 in either one or two pieces of free space, so we want to try
1668 both before freeing any more traceframes. */
1669 #endif
1672 /* If we get here, we know we can provide the asked-for space. */
1674 rslt = tbctrl->free;
1676 /* Adjust the request back down, now that we know we have space for
1677 the marker, but don't commit to AMT yet, we may still need to
1678 restart the operation if GDBserver touches the trace buffer
1679 (obviously only important in the in-process agent's version). */
1680 tbctrl->free += (amt - sizeof (struct traceframe));
1682 /* Or not. If GDBserver changed the trace buffer behind our back,
1683 we get to restart a new allocation attempt. */
1685 #ifdef IN_PROCESS_AGENT
1686 /* Build the tentative token. */
1687 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1688 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1689 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1690 | commit_count
1691 | curr);
1693 /* Try to commit it. */
1694 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1695 if (readout != prev)
1697 trace_debug ("GDBserver has touched the trace buffer, restarting."
1698 " (prev=%08x, commit=%08x, readout=%08x)",
1699 prev, commit, readout);
1700 goto again;
1703 /* Hold your horses here. Even if that change was committed,
1704 GDBserver could come in, and clobber it. We need to hold to be
1705 able to tell if GDBserver clobbers before or after we committed
1706 the change. Whenever GDBserver goes about touching the IPA
1707 buffer, it sets a breakpoint in this routine, so we have a sync
1708 point here. */
1709 about_to_request_buffer_space ();
1711 /* Check if the change has been effective, even if GDBserver stopped
1712 us at the breakpoint. */
1715 unsigned int refetch;
1717 memory_barrier ();
1719 refetch = trace_buffer_ctrl_curr;
1721 if (refetch == commit
1722 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1724 /* effective */
1725 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1726 "readout=%08x, refetch=%08x)",
1727 prev, commit, readout, refetch);
1729 else
1731 trace_debug ("GDBserver has touched the trace buffer, not effective."
1732 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1733 prev, commit, readout, refetch);
1734 goto again;
1737 #endif
1739 /* We have a new piece of the trace buffer. Hurray! */
1741 /* Add an EOB marker just past this allocation. */
1742 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1743 ((struct traceframe *) tbctrl->free)->data_size = 0;
1745 /* Adjust the request back down, now that we know we have space for
1746 the marker. */
1747 amt -= sizeof (struct traceframe);
1749 if (debug_threads)
1751 trace_debug ("Allocated %d bytes", (int) amt);
1752 trace_debug ("Trace buffer [%d] start=%d free=%d "
1753 "endfree=%d wrap=%d hi=%d",
1754 curr,
1755 (int) (tbctrl->start - trace_buffer_lo),
1756 (int) (tbctrl->free - trace_buffer_lo),
1757 (int) (tbctrl->end_free - trace_buffer_lo),
1758 (int) (tbctrl->wrap - trace_buffer_lo),
1759 (int) (trace_buffer_hi - trace_buffer_lo));
1762 return rslt;
1765 #ifndef IN_PROCESS_AGENT
1767 /* Return the total free space. This is not necessarily the largest
1768 block we can allocate, because of the two-part case. */
1770 static int
1771 free_space (void)
1773 if (trace_buffer_free <= trace_buffer_end_free)
1774 return trace_buffer_end_free - trace_buffer_free;
1775 else
1776 return ((trace_buffer_end_free - trace_buffer_lo)
1777 + (trace_buffer_hi - trace_buffer_free));
1780 /* An 'S' in continuation packets indicates remainder are for
1781 while-stepping. */
1783 static int seen_step_action_flag;
1785 /* Create a tracepoint (location) with given number and address. Add this
1786 new tracepoint to list and sort this list. */
1788 static struct tracepoint *
1789 add_tracepoint (int num, CORE_ADDR addr)
1791 struct tracepoint *tpoint, **tp_next;
1793 tpoint = XNEW (struct tracepoint);
1794 tpoint->number = num;
1795 tpoint->address = addr;
1796 tpoint->numactions = 0;
1797 tpoint->actions = NULL;
1798 tpoint->actions_str = NULL;
1799 tpoint->cond = NULL;
1800 tpoint->num_step_actions = 0;
1801 tpoint->step_actions = NULL;
1802 tpoint->step_actions_str = NULL;
1803 /* Start all off as regular (slow) tracepoints. */
1804 tpoint->type = trap_tracepoint;
1805 tpoint->orig_size = -1;
1806 tpoint->source_strings = NULL;
1807 tpoint->compiled_cond = 0;
1808 tpoint->handle = NULL;
1809 tpoint->next = NULL;
1811 /* Find a place to insert this tracepoint into list in order to keep
1812 the tracepoint list still in the ascending order. There may be
1813 multiple tracepoints at the same address as TPOINT's, and this
1814 guarantees TPOINT is inserted after all the tracepoints which are
1815 set at the same address. For example, fast tracepoints A, B, C are
1816 set at the same address, and D is to be insert at the same place as
1817 well,
1819 -->| A |--> | B |-->| C |->...
1821 One jump pad was created for tracepoint A, B, and C, and the target
1822 address of A is referenced/used in jump pad. So jump pad will let
1823 inferior jump to A. If D is inserted in front of A, like this,
1825 -->| D |-->| A |--> | B |-->| C |->...
1827 without updating jump pad, D is not reachable during collect, which
1828 is wrong. As we can see, the order of B, C and D doesn't matter, but
1829 A should always be the `first' one. */
1830 for (tp_next = &tracepoints;
1831 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1832 tp_next = &(*tp_next)->next)
1834 tpoint->next = *tp_next;
1835 *tp_next = tpoint;
1836 last_tracepoint = tpoint;
1838 seen_step_action_flag = 0;
1840 return tpoint;
1843 #ifndef IN_PROCESS_AGENT
1845 /* Return the tracepoint with the given number and address, or NULL. */
1847 static struct tracepoint *
1848 find_tracepoint (int id, CORE_ADDR addr)
1850 struct tracepoint *tpoint;
1852 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1853 if (tpoint->number == id && tpoint->address == addr)
1854 return tpoint;
1856 return NULL;
1859 /* Remove TPOINT from global list. */
1861 static void
1862 remove_tracepoint (struct tracepoint *tpoint)
1864 struct tracepoint *tp, *tp_prev;
1866 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1867 tp_prev = tp, tp = tp->next)
1870 if (tp)
1872 if (tp_prev)
1873 tp_prev->next = tp->next;
1874 else
1875 tracepoints = tp->next;
1877 xfree (tp);
1881 /* There may be several tracepoints with the same number (because they
1882 are "locations", in GDB parlance); return the next one after the
1883 given tracepoint, or search from the beginning of the list if the
1884 first argument is NULL. */
1886 static struct tracepoint *
1887 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1889 struct tracepoint *tpoint;
1891 if (prev_tp)
1892 tpoint = prev_tp->next;
1893 else
1894 tpoint = tracepoints;
1895 for (; tpoint; tpoint = tpoint->next)
1896 if (tpoint->number == num)
1897 return tpoint;
1899 return NULL;
1902 #endif
1904 /* Append another action to perform when the tracepoint triggers. */
1906 static void
1907 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1909 const char *act;
1911 if (*packet == 'S')
1913 seen_step_action_flag = 1;
1914 ++packet;
1917 act = packet;
1919 while (*act)
1921 const char *act_start = act;
1922 struct tracepoint_action *action = NULL;
1924 switch (*act)
1926 case 'M':
1928 struct collect_memory_action *maction =
1929 XNEW (struct collect_memory_action);
1930 ULONGEST basereg;
1931 int is_neg;
1933 maction->base.type = *act;
1934 action = &maction->base;
1936 ++act;
1937 is_neg = (*act == '-');
1938 if (*act == '-')
1939 ++act;
1940 act = unpack_varlen_hex (act, &basereg);
1941 ++act;
1942 act = unpack_varlen_hex (act, &maction->addr);
1943 ++act;
1944 act = unpack_varlen_hex (act, &maction->len);
1945 maction->basereg = (is_neg
1946 ? - (int) basereg
1947 : (int) basereg);
1948 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1949 pulongest (maction->len),
1950 paddress (maction->addr), maction->basereg);
1951 break;
1953 case 'R':
1955 struct collect_registers_action *raction =
1956 XNEW (struct collect_registers_action);
1958 raction->base.type = *act;
1959 action = &raction->base;
1961 trace_debug ("Want to collect registers");
1962 ++act;
1963 /* skip past hex digits of mask for now */
1964 while (isxdigit(*act))
1965 ++act;
1966 break;
1968 case 'L':
1970 struct collect_static_trace_data_action *raction =
1971 XNEW (struct collect_static_trace_data_action);
1973 raction->base.type = *act;
1974 action = &raction->base;
1976 trace_debug ("Want to collect static trace data");
1977 ++act;
1978 break;
1980 case 'S':
1981 trace_debug ("Unexpected step action, ignoring");
1982 ++act;
1983 break;
1984 case 'X':
1986 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1988 xaction->base.type = *act;
1989 action = &xaction->base;
1991 trace_debug ("Want to evaluate expression");
1992 xaction->expr = gdb_parse_agent_expr (&act);
1993 break;
1995 default:
1996 trace_debug ("unknown trace action '%c', ignoring...", *act);
1997 break;
1998 case '-':
1999 break;
2002 if (action == NULL)
2003 break;
2005 if (seen_step_action_flag)
2007 tpoint->num_step_actions++;
2009 tpoint->step_actions
2010 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
2011 tpoint->num_step_actions);
2012 tpoint->step_actions_str
2013 = XRESIZEVEC (char *, tpoint->step_actions_str,
2014 tpoint->num_step_actions);
2015 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
2016 tpoint->step_actions_str[tpoint->num_step_actions - 1]
2017 = savestring (act_start, act - act_start);
2019 else
2021 tpoint->numactions++;
2022 tpoint->actions
2023 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
2024 tpoint->numactions);
2025 tpoint->actions_str
2026 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
2027 tpoint->actions[tpoint->numactions - 1] = action;
2028 tpoint->actions_str[tpoint->numactions - 1]
2029 = savestring (act_start, act - act_start);
2034 #endif
2036 /* Find or create a trace state variable with the given number. */
2038 static struct trace_state_variable *
2039 get_trace_state_variable (int num)
2041 struct trace_state_variable *tsv;
2043 #ifdef IN_PROCESS_AGENT
2044 /* Search for an existing variable. */
2045 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
2046 if (tsv->number == num)
2047 return tsv;
2048 #endif
2050 /* Search for an existing variable. */
2051 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
2052 if (tsv->number == num)
2053 return tsv;
2055 return NULL;
2058 /* Find or create a trace state variable with the given number. */
2060 static struct trace_state_variable *
2061 create_trace_state_variable (int num, int gdb)
2063 struct trace_state_variable *tsv;
2065 tsv = get_trace_state_variable (num);
2066 if (tsv != NULL)
2067 return tsv;
2069 /* Create a new variable. */
2070 tsv = XNEW (struct trace_state_variable);
2071 tsv->number = num;
2072 tsv->initial_value = 0;
2073 tsv->value = 0;
2074 tsv->getter = NULL;
2075 tsv->name = NULL;
2076 #ifdef IN_PROCESS_AGENT
2077 if (!gdb)
2079 tsv->next = alloced_trace_state_variables;
2080 alloced_trace_state_variables = tsv;
2082 else
2083 #endif
2085 tsv->next = trace_state_variables;
2086 trace_state_variables = tsv;
2088 return tsv;
2091 /* This is needed for -Wmissing-declarations. */
2092 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
2094 IP_AGENT_EXPORT_FUNC LONGEST
2095 get_trace_state_variable_value (int num)
2097 struct trace_state_variable *tsv;
2099 tsv = get_trace_state_variable (num);
2101 if (!tsv)
2103 trace_debug ("No trace state variable %d, skipping value get", num);
2104 return 0;
2107 /* Call a getter function if we have one. While it's tempting to
2108 set up something to only call the getter once per tracepoint hit,
2109 it could run afoul of thread races. Better to let the getter
2110 handle it directly, if necessary to worry about it. */
2111 if (tsv->getter)
2112 tsv->value = (tsv->getter) ();
2114 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2115 num, plongest (tsv->value));
2117 return tsv->value;
2120 /* This is needed for -Wmissing-declarations. */
2121 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
2122 LONGEST val);
2124 IP_AGENT_EXPORT_FUNC void
2125 set_trace_state_variable_value (int num, LONGEST val)
2127 struct trace_state_variable *tsv;
2129 tsv = get_trace_state_variable (num);
2131 if (!tsv)
2133 trace_debug ("No trace state variable %d, skipping value set", num);
2134 return;
2137 tsv->value = val;
2140 LONGEST
2141 agent_get_trace_state_variable_value (int num)
2143 return get_trace_state_variable_value (num);
2146 void
2147 agent_set_trace_state_variable_value (int num, LONGEST val)
2149 set_trace_state_variable_value (num, val);
2152 static void
2153 set_trace_state_variable_name (int num, const char *name)
2155 struct trace_state_variable *tsv;
2157 tsv = get_trace_state_variable (num);
2159 if (!tsv)
2161 trace_debug ("No trace state variable %d, skipping name set", num);
2162 return;
2165 tsv->name = (char *) name;
2168 static void
2169 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2171 struct trace_state_variable *tsv;
2173 tsv = get_trace_state_variable (num);
2175 if (!tsv)
2177 trace_debug ("No trace state variable %d, skipping getter set", num);
2178 return;
2181 tsv->getter = getter;
2184 /* Add a raw traceframe for the given tracepoint. */
2186 static struct traceframe *
2187 add_traceframe (struct tracepoint *tpoint)
2189 struct traceframe *tframe;
2191 tframe
2192 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2194 if (tframe == NULL)
2195 return NULL;
2197 tframe->tpnum = tpoint->number;
2198 tframe->data_size = 0;
2200 return tframe;
2203 /* Add a block to the traceframe currently being worked on. */
2205 static unsigned char *
2206 add_traceframe_block (struct traceframe *tframe,
2207 struct tracepoint *tpoint, int amt)
2209 unsigned char *block;
2211 if (!tframe)
2212 return NULL;
2214 block = (unsigned char *) trace_buffer_alloc (amt);
2216 if (!block)
2217 return NULL;
2219 gdb_assert (tframe->tpnum == tpoint->number);
2221 tframe->data_size += amt;
2222 tpoint->traceframe_usage += amt;
2224 return block;
2227 /* Flag that the current traceframe is finished. */
2229 static void
2230 finish_traceframe (struct traceframe *tframe)
2232 ++traceframe_write_count;
2233 ++traceframes_created;
2236 #ifndef IN_PROCESS_AGENT
2238 /* Given a traceframe number NUM, find the NUMth traceframe in the
2239 buffer. */
2241 static struct traceframe *
2242 find_traceframe (int num)
2244 struct traceframe *tframe;
2245 int tfnum = 0;
2247 for (tframe = FIRST_TRACEFRAME ();
2248 tframe->tpnum != 0;
2249 tframe = NEXT_TRACEFRAME (tframe))
2251 if (tfnum == num)
2252 return tframe;
2253 ++tfnum;
2256 return NULL;
2259 static CORE_ADDR
2260 get_traceframe_address (struct traceframe *tframe)
2262 CORE_ADDR addr;
2263 struct tracepoint *tpoint;
2265 addr = traceframe_get_pc (tframe);
2267 if (addr)
2268 return addr;
2270 /* Fallback strategy, will be incorrect for while-stepping frames
2271 and multi-location tracepoints. */
2272 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2273 return tpoint->address;
2276 /* Search for the next traceframe whose address is inside or outside
2277 the given range. */
2279 static struct traceframe *
2280 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2281 int *tfnump)
2283 client_state &cs = get_client_state ();
2284 struct traceframe *tframe;
2285 CORE_ADDR tfaddr;
2287 *tfnump = cs.current_traceframe + 1;
2288 tframe = find_traceframe (*tfnump);
2289 /* The search is not supposed to wrap around. */
2290 if (!tframe)
2292 *tfnump = -1;
2293 return NULL;
2296 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2298 tfaddr = get_traceframe_address (tframe);
2299 if (inside_p
2300 ? (lo <= tfaddr && tfaddr <= hi)
2301 : (lo > tfaddr || tfaddr > hi))
2302 return tframe;
2303 ++*tfnump;
2306 *tfnump = -1;
2307 return NULL;
2310 /* Search for the next traceframe recorded by the given tracepoint.
2311 Note that for multi-location tracepoints, this will find whatever
2312 location appears first. */
2314 static struct traceframe *
2315 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2317 client_state &cs = get_client_state ();
2318 struct traceframe *tframe;
2320 *tfnump = cs.current_traceframe + 1;
2321 tframe = find_traceframe (*tfnump);
2322 /* The search is not supposed to wrap around. */
2323 if (!tframe)
2325 *tfnump = -1;
2326 return NULL;
2329 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2331 if (tframe->tpnum == num)
2332 return tframe;
2333 ++*tfnump;
2336 *tfnump = -1;
2337 return NULL;
2340 #endif
2342 #ifndef IN_PROCESS_AGENT
2344 /* Clear all past trace state. */
2346 static void
2347 cmd_qtinit (char *packet)
2349 client_state &cs = get_client_state ();
2350 struct trace_state_variable *tsv, *prev, *next;
2352 /* Can't do this command without a pid attached. */
2353 if (current_thread == NULL)
2355 write_enn (packet);
2356 return;
2359 /* Make sure we don't try to read from a trace frame. */
2360 cs.current_traceframe = -1;
2362 stop_tracing ();
2364 trace_debug ("Initializing the trace");
2366 clear_installed_tracepoints ();
2367 clear_readonly_regions ();
2369 tracepoints = NULL;
2370 last_tracepoint = NULL;
2372 /* Clear out any leftover trace state variables. Ones with target
2373 defined getters should be kept however. */
2374 prev = NULL;
2375 tsv = trace_state_variables;
2376 while (tsv)
2378 trace_debug ("Looking at var %d", tsv->number);
2379 if (tsv->getter == NULL)
2381 next = tsv->next;
2382 if (prev)
2383 prev->next = next;
2384 else
2385 trace_state_variables = next;
2386 trace_debug ("Deleting var %d", tsv->number);
2387 free (tsv);
2388 tsv = next;
2390 else
2392 prev = tsv;
2393 tsv = tsv->next;
2397 clear_trace_buffer ();
2398 clear_inferior_trace_buffer ();
2400 write_ok (packet);
2403 /* Unprobe the UST marker at ADDRESS. */
2405 static void
2406 unprobe_marker_at (CORE_ADDR address)
2408 char cmd[IPA_CMD_BUF_SIZE];
2410 sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
2411 run_inferior_command (cmd, strlen (cmd) + 1);
2414 /* Restore the program to its pre-tracing state. This routine may be called
2415 in error situations, so it needs to be careful about only restoring
2416 from known-valid bits. */
2418 static void
2419 clear_installed_tracepoints (void)
2421 struct tracepoint *tpoint;
2422 struct tracepoint *prev_stpoint;
2424 target_pause_all (true);
2426 prev_stpoint = NULL;
2428 /* Restore any bytes overwritten by tracepoints. */
2429 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2431 /* Catch the case where we might try to remove a tracepoint that
2432 was never actually installed. */
2433 if (tpoint->handle == NULL)
2435 trace_debug ("Tracepoint %d at 0x%s was "
2436 "never installed, nothing to clear",
2437 tpoint->number, paddress (tpoint->address));
2438 continue;
2441 switch (tpoint->type)
2443 case trap_tracepoint:
2445 struct breakpoint *bp
2446 = (struct breakpoint *) tpoint->handle;
2448 delete_breakpoint (bp);
2450 break;
2451 case fast_tracepoint:
2453 struct fast_tracepoint_jump *jump
2454 = (struct fast_tracepoint_jump *) tpoint->handle;
2456 delete_fast_tracepoint_jump (jump);
2458 break;
2459 case static_tracepoint:
2460 if (prev_stpoint != NULL
2461 && prev_stpoint->address == tpoint->address)
2462 /* Nothing to do. We already unprobed a tracepoint set at
2463 this marker address (and there can only be one probe
2464 per marker). */
2466 else
2468 unprobe_marker_at (tpoint->address);
2469 prev_stpoint = tpoint;
2471 break;
2474 tpoint->handle = NULL;
2477 target_unpause_all (true);
2480 /* Parse a packet that defines a tracepoint. */
2482 static void
2483 cmd_qtdp (char *own_buf)
2485 int tppacket;
2486 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2487 int trail_hyphen = 0;
2488 ULONGEST num;
2489 ULONGEST addr;
2490 ULONGEST count;
2491 struct tracepoint *tpoint;
2492 const char *packet = own_buf;
2494 packet += strlen ("QTDP:");
2496 /* A hyphen at the beginning marks a packet specifying actions for a
2497 tracepoint already supplied. */
2498 tppacket = 1;
2499 if (*packet == '-')
2501 tppacket = 0;
2502 ++packet;
2504 packet = unpack_varlen_hex (packet, &num);
2505 ++packet; /* skip a colon */
2506 packet = unpack_varlen_hex (packet, &addr);
2507 ++packet; /* skip a colon */
2509 /* See if we already have this tracepoint. */
2510 tpoint = find_tracepoint (num, addr);
2512 if (tppacket)
2514 /* Duplicate tracepoints are never allowed. */
2515 if (tpoint)
2517 trace_debug ("Tracepoint error: tracepoint %d"
2518 " at 0x%s already exists",
2519 (int) num, paddress (addr));
2520 write_enn (own_buf);
2521 return;
2524 tpoint = add_tracepoint (num, addr);
2526 tpoint->enabled = (*packet == 'E');
2527 ++packet; /* skip 'E' */
2528 ++packet; /* skip a colon */
2529 packet = unpack_varlen_hex (packet, &count);
2530 tpoint->step_count = count;
2531 ++packet; /* skip a colon */
2532 packet = unpack_varlen_hex (packet, &count);
2533 tpoint->pass_count = count;
2534 /* See if we have any of the additional optional fields. */
2535 while (*packet == ':')
2537 ++packet;
2538 if (*packet == 'F')
2540 tpoint->type = fast_tracepoint;
2541 ++packet;
2542 packet = unpack_varlen_hex (packet, &count);
2543 tpoint->orig_size = count;
2545 else if (*packet == 'S')
2547 tpoint->type = static_tracepoint;
2548 ++packet;
2550 else if (*packet == 'X')
2552 tpoint->cond = gdb_parse_agent_expr (&packet);
2554 else if (*packet == '-')
2555 break;
2556 else if (*packet == '\0')
2557 break;
2558 else
2559 trace_debug ("Unknown optional tracepoint field");
2561 if (*packet == '-')
2563 trail_hyphen = 1;
2564 trace_debug ("Also has actions\n");
2567 trace_debug ("Defined %stracepoint %d at 0x%s, "
2568 "enabled %d step %" PRIu64 " pass %" PRIu64,
2569 tpoint->type == fast_tracepoint ? "fast "
2570 : tpoint->type == static_tracepoint ? "static " : "",
2571 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2572 tpoint->step_count, tpoint->pass_count);
2574 else if (tpoint)
2575 add_tracepoint_action (tpoint, packet);
2576 else
2578 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2579 (int) num, paddress (addr));
2580 write_enn (own_buf);
2581 return;
2584 /* Install tracepoint during tracing only once for each tracepoint location.
2585 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2586 determine the last QTDP packet for one tracepoint location by checking
2587 trailing hyphen in QTDP packet. */
2588 if (tracing && !trail_hyphen)
2590 struct tracepoint *tp = NULL;
2592 /* Pause all threads temporarily while we patch tracepoints. */
2593 target_pause_all (false);
2595 /* download_tracepoint will update global `tracepoints'
2596 list, so it is unsafe to leave threads in jump pad. */
2597 target_stabilize_threads ();
2599 /* Freeze threads. */
2600 target_pause_all (true);
2603 if (tpoint->type != trap_tracepoint)
2605 /* Find another fast or static tracepoint at the same address. */
2606 for (tp = tracepoints; tp; tp = tp->next)
2608 if (tp->address == tpoint->address && tp->type == tpoint->type
2609 && tp->number != tpoint->number)
2610 break;
2613 /* TPOINT is installed at the same address as TP. */
2614 if (tp)
2616 if (tpoint->type == fast_tracepoint)
2617 clone_fast_tracepoint (tpoint, tp);
2618 else if (tpoint->type == static_tracepoint)
2619 tpoint->handle = (void *) -1;
2623 if (use_agent && tpoint->type == fast_tracepoint
2624 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2626 /* Download and install fast tracepoint by agent. */
2627 if (tracepoint_send_agent (tpoint) == 0)
2628 write_ok (own_buf);
2629 else
2631 write_enn (own_buf);
2632 remove_tracepoint (tpoint);
2635 else
2637 download_tracepoint (tpoint);
2639 if (tpoint->type == trap_tracepoint || tp == NULL)
2641 install_tracepoint (tpoint, own_buf);
2642 if (strcmp (own_buf, "OK") != 0)
2643 remove_tracepoint (tpoint);
2645 else
2646 write_ok (own_buf);
2649 target_unpause_all (true);
2650 return;
2653 write_ok (own_buf);
2656 static void
2657 cmd_qtdpsrc (char *own_buf)
2659 ULONGEST num, addr, start, slen;
2660 struct tracepoint *tpoint;
2661 const char *packet = own_buf;
2662 const char *saved;
2663 char *srctype, *src;
2664 size_t nbytes;
2665 struct source_string *last, *newlast;
2667 packet += strlen ("QTDPsrc:");
2669 packet = unpack_varlen_hex (packet, &num);
2670 ++packet; /* skip a colon */
2671 packet = unpack_varlen_hex (packet, &addr);
2672 ++packet; /* skip a colon */
2674 /* See if we already have this tracepoint. */
2675 tpoint = find_tracepoint (num, addr);
2677 if (!tpoint)
2679 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2680 (int) num, paddress (addr));
2681 write_enn (own_buf);
2682 return;
2685 saved = packet;
2686 packet = strchr (packet, ':');
2687 srctype = (char *) xmalloc (packet - saved + 1);
2688 memcpy (srctype, saved, packet - saved);
2689 srctype[packet - saved] = '\0';
2690 ++packet;
2691 packet = unpack_varlen_hex (packet, &start);
2692 ++packet; /* skip a colon */
2693 packet = unpack_varlen_hex (packet, &slen);
2694 ++packet; /* skip a colon */
2695 src = (char *) xmalloc (slen + 1);
2696 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2697 src[nbytes] = '\0';
2699 newlast = XNEW (struct source_string);
2700 newlast->type = srctype;
2701 newlast->str = src;
2702 newlast->next = NULL;
2703 /* Always add a source string to the end of the list;
2704 this keeps sequences of actions/commands in the right
2705 order. */
2706 if (tpoint->source_strings)
2708 for (last = tpoint->source_strings; last->next; last = last->next)
2710 last->next = newlast;
2712 else
2713 tpoint->source_strings = newlast;
2715 write_ok (own_buf);
2718 static void
2719 cmd_qtdv (char *own_buf)
2721 ULONGEST num, val, builtin;
2722 char *varname;
2723 size_t nbytes;
2724 struct trace_state_variable *tsv;
2725 const char *packet = own_buf;
2727 packet += strlen ("QTDV:");
2729 packet = unpack_varlen_hex (packet, &num);
2730 ++packet; /* skip a colon */
2731 packet = unpack_varlen_hex (packet, &val);
2732 ++packet; /* skip a colon */
2733 packet = unpack_varlen_hex (packet, &builtin);
2734 ++packet; /* skip a colon */
2736 nbytes = strlen (packet) / 2;
2737 varname = (char *) xmalloc (nbytes + 1);
2738 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2739 varname[nbytes] = '\0';
2741 tsv = create_trace_state_variable (num, 1);
2742 tsv->initial_value = (LONGEST) val;
2743 tsv->name = varname;
2745 set_trace_state_variable_value (num, (LONGEST) val);
2747 write_ok (own_buf);
2750 static void
2751 cmd_qtenable_disable (char *own_buf, int enable)
2753 const char *packet = own_buf;
2754 ULONGEST num, addr;
2755 struct tracepoint *tp;
2757 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2758 packet = unpack_varlen_hex (packet, &num);
2759 ++packet; /* skip a colon */
2760 packet = unpack_varlen_hex (packet, &addr);
2762 tp = find_tracepoint (num, addr);
2764 if (tp)
2766 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2768 trace_debug ("Tracepoint %d at 0x%s is already %s",
2769 (int) num, paddress (addr),
2770 enable ? "enabled" : "disabled");
2771 write_ok (own_buf);
2772 return;
2775 trace_debug ("%s tracepoint %d at 0x%s",
2776 enable ? "Enabling" : "Disabling",
2777 (int) num, paddress (addr));
2779 tp->enabled = enable;
2781 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
2783 int offset = offsetof (struct tracepoint, enabled);
2784 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2786 int ret = write_inferior_int8 (obj_addr, enable);
2787 if (ret)
2789 trace_debug ("Cannot write enabled flag into "
2790 "inferior process memory");
2791 write_enn (own_buf);
2792 return;
2796 write_ok (own_buf);
2798 else
2800 trace_debug ("Tracepoint %d at 0x%s not found",
2801 (int) num, paddress (addr));
2802 write_enn (own_buf);
2806 static void
2807 cmd_qtv (char *own_buf)
2809 client_state &cs = get_client_state ();
2810 ULONGEST num;
2811 LONGEST val = 0;
2812 int err;
2813 char *packet = own_buf;
2815 packet += strlen ("qTV:");
2816 unpack_varlen_hex (packet, &num);
2818 if (cs.current_traceframe >= 0)
2820 err = traceframe_read_tsv ((int) num, &val);
2821 if (err)
2823 strcpy (own_buf, "U");
2824 return;
2827 /* Only make tsv's be undefined before the first trace run. After a
2828 trace run is over, the user might want to see the last value of
2829 the tsv, and it might not be available in a traceframe. */
2830 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2832 strcpy (own_buf, "U");
2833 return;
2835 else
2836 val = get_trace_state_variable_value (num);
2838 sprintf (own_buf, "V%s", phex_nz (val, 0));
2841 /* Clear out the list of readonly regions. */
2843 static void
2844 clear_readonly_regions (void)
2846 struct readonly_region *roreg;
2848 while (readonly_regions)
2850 roreg = readonly_regions;
2851 readonly_regions = readonly_regions->next;
2852 free (roreg);
2856 /* Parse the collection of address ranges whose contents GDB believes
2857 to be unchanging and so can be read directly from target memory
2858 even while looking at a traceframe. */
2860 static void
2861 cmd_qtro (char *own_buf)
2863 ULONGEST start, end;
2864 struct readonly_region *roreg;
2865 const char *packet = own_buf;
2867 trace_debug ("Want to mark readonly regions");
2869 clear_readonly_regions ();
2871 packet += strlen ("QTro");
2873 while (*packet == ':')
2875 ++packet; /* skip a colon */
2876 packet = unpack_varlen_hex (packet, &start);
2877 ++packet; /* skip a comma */
2878 packet = unpack_varlen_hex (packet, &end);
2880 roreg = XNEW (struct readonly_region);
2881 roreg->start = start;
2882 roreg->end = end;
2883 roreg->next = readonly_regions;
2884 readonly_regions = roreg;
2885 trace_debug ("Added readonly region from 0x%s to 0x%s",
2886 paddress (roreg->start), paddress (roreg->end));
2889 write_ok (own_buf);
2892 /* Test to see if the given range is in our list of readonly ranges.
2893 We only test for being entirely within a range, GDB is not going to
2894 send a single memory packet that spans multiple regions. */
2897 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2899 struct readonly_region *roreg;
2901 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2902 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2903 return 1;
2905 return 0;
2908 static CORE_ADDR gdb_jump_pad_head;
2910 /* Return the address of the next free jump space. */
2912 static CORE_ADDR
2913 get_jump_space_head (void)
2915 if (gdb_jump_pad_head == 0)
2917 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2918 &gdb_jump_pad_head))
2920 internal_error ("error extracting jump_pad_buffer");
2924 return gdb_jump_pad_head;
2927 /* Reserve USED bytes from the jump space. */
2929 static void
2930 claim_jump_space (ULONGEST used)
2932 trace_debug ("claim_jump_space reserves %s bytes at %s",
2933 pulongest (used), paddress (gdb_jump_pad_head));
2934 gdb_jump_pad_head += used;
2937 static CORE_ADDR trampoline_buffer_head = 0;
2938 static CORE_ADDR trampoline_buffer_tail;
2940 /* Reserve USED bytes from the trampoline buffer and return the
2941 address of the start of the reserved space in TRAMPOLINE. Returns
2942 non-zero if the space is successfully claimed. */
2945 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2947 if (!trampoline_buffer_head)
2949 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2950 &trampoline_buffer_tail))
2952 internal_error ("error extracting trampoline_buffer");
2955 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2956 &trampoline_buffer_head))
2958 internal_error ("error extracting trampoline_buffer_end");
2962 /* Start claiming space from the top of the trampoline space. If
2963 the space is located at the bottom of the virtual address space,
2964 this reduces the possibility that corruption will occur if a null
2965 pointer is used to write to memory. */
2966 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2968 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2969 pulongest (used));
2970 return 0;
2973 trampoline_buffer_head -= used;
2975 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2976 pulongest (used), paddress (trampoline_buffer_head));
2978 *trampoline = trampoline_buffer_head;
2979 return 1;
2982 /* Returns non-zero if there is space allocated for use in trampolines
2983 for fast tracepoints. */
2986 have_fast_tracepoint_trampoline_buffer (char *buf)
2988 CORE_ADDR trampoline_end, errbuf;
2990 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2991 &trampoline_end))
2993 internal_error ("error extracting trampoline_buffer_end");
2996 if (buf)
2998 buf[0] = '\0';
2999 strcpy (buf, "was claiming");
3000 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
3001 &errbuf))
3003 internal_error ("error extracting errbuf");
3006 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
3009 return trampoline_end != 0;
3012 /* Ask the IPA to probe the marker at ADDRESS. Returns -1 if running
3013 the command fails, or 0 otherwise. If the command ran
3014 successfully, but probing the marker failed, ERROUT will be filled
3015 with the error to reply to GDB, and -1 is also returned. This
3016 allows directly passing IPA errors to GDB. */
3018 static int
3019 probe_marker_at (CORE_ADDR address, char *errout)
3021 char cmd[IPA_CMD_BUF_SIZE];
3022 int err;
3024 sprintf (cmd, "probe_marker_at:%s", paddress (address));
3025 err = run_inferior_command (cmd, strlen (cmd) + 1);
3027 if (err == 0)
3029 if (*cmd == 'E')
3031 strcpy (errout, cmd);
3032 return -1;
3036 return err;
3039 static void
3040 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
3042 to->jump_pad = from->jump_pad;
3043 to->jump_pad_end = from->jump_pad_end;
3044 to->trampoline = from->trampoline;
3045 to->trampoline_end = from->trampoline_end;
3046 to->adjusted_insn_addr = from->adjusted_insn_addr;
3047 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
3048 to->handle = from->handle;
3050 gdb_assert (from->handle);
3051 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
3054 #define MAX_JUMP_SIZE 20
3056 /* Install fast tracepoint. Return 0 if successful, otherwise return
3057 non-zero. */
3059 static int
3060 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
3062 CORE_ADDR jentry, jump_entry;
3063 CORE_ADDR trampoline;
3064 CORE_ADDR collect;
3065 ULONGEST trampoline_size;
3066 int err = 0;
3067 /* The jump to the jump pad of the last fast tracepoint
3068 installed. */
3069 unsigned char fjump[MAX_JUMP_SIZE];
3070 ULONGEST fjump_size;
3072 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
3074 trace_debug ("Requested a fast tracepoint on an instruction "
3075 "that is of less than the minimum length.");
3076 return 0;
3079 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
3080 &collect))
3082 error ("error extracting gdb_collect_ptr");
3083 return 1;
3086 jentry = jump_entry = get_jump_space_head ();
3088 trampoline = 0;
3089 trampoline_size = 0;
3091 /* Install the jump pad. */
3092 err = target_install_fast_tracepoint_jump_pad
3093 (tpoint->obj_addr_on_target, tpoint->address, collect,
3094 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
3095 &trampoline, &trampoline_size, fjump, &fjump_size,
3096 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
3098 if (err)
3099 return 1;
3101 /* Wire it in. */
3102 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
3103 fjump_size);
3105 if (tpoint->handle != NULL)
3107 tpoint->jump_pad = jump_entry;
3108 tpoint->jump_pad_end = jentry;
3109 tpoint->trampoline = trampoline;
3110 tpoint->trampoline_end = trampoline + trampoline_size;
3112 /* Pad to 8-byte alignment. */
3113 jentry = ((jentry + 7) & ~0x7);
3114 claim_jump_space (jentry - jump_entry);
3117 return 0;
3121 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
3123 static void
3124 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
3126 tpoint->handle = NULL;
3127 *own_buf = '\0';
3129 if (tpoint->type == trap_tracepoint)
3131 /* Tracepoints are installed as memory breakpoints. Just go
3132 ahead and install the trap. The breakpoints module
3133 handles duplicated breakpoints, and the memory read
3134 routine handles un-patching traps from memory reads. */
3135 tpoint->handle = set_breakpoint_at (tpoint->address,
3136 tracepoint_handler);
3138 else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
3140 if (!agent_loaded_p ())
3142 trace_debug ("Requested a %s tracepoint, but fast "
3143 "tracepoints aren't supported.",
3144 tpoint->type == static_tracepoint ? "static" : "fast");
3145 write_e_ipa_not_loaded (own_buf);
3146 return;
3148 if (tpoint->type == static_tracepoint
3149 && !in_process_agent_supports_ust ())
3151 trace_debug ("Requested a static tracepoint, but static "
3152 "tracepoints are not supported.");
3153 write_e_ust_not_loaded (own_buf);
3154 return;
3157 if (tpoint->type == fast_tracepoint)
3158 install_fast_tracepoint (tpoint, own_buf);
3159 else
3161 if (probe_marker_at (tpoint->address, own_buf) == 0)
3162 tpoint->handle = (void *) -1;
3166 else
3167 internal_error ("Unknown tracepoint type");
3169 if (tpoint->handle == NULL)
3171 if (*own_buf == '\0')
3172 write_enn (own_buf);
3174 else
3175 write_ok (own_buf);
3178 static void download_tracepoint_1 (struct tracepoint *tpoint);
3180 static void
3181 cmd_qtstart (char *packet)
3183 struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
3184 CORE_ADDR tpptr = 0, prev_tpptr = 0;
3186 trace_debug ("Starting the trace");
3188 /* Pause all threads temporarily while we patch tracepoints. */
3189 target_pause_all (false);
3191 /* Get threads out of jump pads. Safe to do here, since this is a
3192 top level command. And, required to do here, since we're
3193 deleting/rewriting jump pads. */
3195 target_stabilize_threads ();
3197 /* Freeze threads. */
3198 target_pause_all (true);
3200 /* Sync the fast tracepoints list in the inferior ftlib. */
3201 if (agent_loaded_p ())
3202 download_trace_state_variables ();
3204 /* No previous fast tpoint yet. */
3205 prev_ftpoint = NULL;
3207 /* No previous static tpoint yet. */
3208 prev_stpoint = NULL;
3210 *packet = '\0';
3212 if (agent_loaded_p ())
3214 /* Tell IPA about the correct tdesc. */
3215 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
3216 target_get_ipa_tdesc_idx ()))
3217 error ("Error setting ipa_tdesc_idx variable in lib");
3220 /* Start out empty. */
3221 if (agent_loaded_p ())
3222 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
3224 /* Download and install tracepoints. */
3225 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3227 /* Ensure all the hit counts start at zero. */
3228 tpoint->hit_count = 0;
3229 tpoint->traceframe_usage = 0;
3231 if (tpoint->type == trap_tracepoint)
3233 /* Tracepoints are installed as memory breakpoints. Just go
3234 ahead and install the trap. The breakpoints module
3235 handles duplicated breakpoints, and the memory read
3236 routine handles un-patching traps from memory reads. */
3237 tpoint->handle = set_breakpoint_at (tpoint->address,
3238 tracepoint_handler);
3240 else if (tpoint->type == fast_tracepoint
3241 || tpoint->type == static_tracepoint)
3243 if (maybe_write_ipa_not_loaded (packet))
3245 trace_debug ("Requested a %s tracepoint, but fast "
3246 "tracepoints aren't supported.",
3247 tpoint->type == static_tracepoint
3248 ? "static" : "fast");
3249 break;
3252 if (tpoint->type == fast_tracepoint)
3254 int use_agent_p
3255 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3257 if (prev_ftpoint != NULL
3258 && prev_ftpoint->address == tpoint->address)
3260 if (use_agent_p)
3261 tracepoint_send_agent (tpoint);
3262 else
3263 download_tracepoint_1 (tpoint);
3265 clone_fast_tracepoint (tpoint, prev_ftpoint);
3267 else
3269 /* Tracepoint is installed successfully? */
3270 int installed = 0;
3272 /* Download and install fast tracepoint by agent. */
3273 if (use_agent_p)
3274 installed = !tracepoint_send_agent (tpoint);
3275 else
3277 download_tracepoint_1 (tpoint);
3278 installed = !install_fast_tracepoint (tpoint, packet);
3281 if (installed)
3282 prev_ftpoint = tpoint;
3285 else
3287 if (!in_process_agent_supports_ust ())
3289 trace_debug ("Requested a static tracepoint, but static "
3290 "tracepoints are not supported.");
3291 break;
3294 download_tracepoint_1 (tpoint);
3295 /* Can only probe a given marker once. */
3296 if (prev_stpoint != NULL
3297 && prev_stpoint->address == tpoint->address)
3298 tpoint->handle = (void *) -1;
3299 else
3301 if (probe_marker_at (tpoint->address, packet) == 0)
3303 tpoint->handle = (void *) -1;
3305 /* So that we can handle multiple static tracepoints
3306 at the same address easily. */
3307 prev_stpoint = tpoint;
3312 prev_tpptr = tpptr;
3313 tpptr = tpoint->obj_addr_on_target;
3315 if (tpoint == tracepoints)
3316 /* First object in list, set the head pointer in the
3317 inferior. */
3318 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3319 else
3320 write_inferior_data_pointer (prev_tpptr
3321 + offsetof (struct tracepoint, next),
3322 tpptr);
3325 /* Any failure in the inner loop is sufficient cause to give
3326 up. */
3327 if (tpoint->handle == NULL)
3328 break;
3331 /* Any error in tracepoint insertion is unacceptable; better to
3332 address the problem now, than end up with a useless or misleading
3333 trace run. */
3334 if (tpoint != NULL)
3336 clear_installed_tracepoints ();
3337 if (*packet == '\0')
3338 write_enn (packet);
3339 target_unpause_all (true);
3340 return;
3343 stopping_tracepoint = NULL;
3344 trace_buffer_is_full = 0;
3345 expr_eval_result = expr_eval_no_error;
3346 error_tracepoint = NULL;
3347 tracing_start_time = get_timestamp ();
3349 /* Tracing is now active, hits will now start being logged. */
3350 tracing = 1;
3352 if (agent_loaded_p ())
3354 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3356 internal_error ("Error setting tracing variable in lib");
3359 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3362 internal_error ("Error clearing stopping_tracepoint variable"
3363 " in lib");
3366 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3368 internal_error ("Error clearing trace_buffer_is_full variable"
3369 " in lib");
3372 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3373 stop_tracing_handler);
3374 if (stop_tracing_bkpt == NULL)
3375 error ("Error setting stop_tracing breakpoint");
3377 flush_trace_buffer_bkpt
3378 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3379 flush_trace_buffer_handler);
3380 if (flush_trace_buffer_bkpt == NULL)
3381 error ("Error setting flush_trace_buffer breakpoint");
3384 target_unpause_all (true);
3386 write_ok (packet);
3389 /* End a tracing run, filling in a stop reason to report back to GDB,
3390 and removing the tracepoints from the code. */
3392 void
3393 stop_tracing (void)
3395 if (!tracing)
3397 trace_debug ("Tracing is already off, ignoring");
3398 return;
3401 trace_debug ("Stopping the trace");
3403 /* Pause all threads before removing fast jumps from memory,
3404 breakpoints, and touching IPA state variables (inferior memory).
3405 Some thread may hit the internal tracing breakpoints, or be
3406 collecting this moment, but that's ok, we don't release the
3407 tpoint object's memory or the jump pads here (we only do that
3408 when we're sure we can move all threads out of the jump pads).
3409 We can't now, since we may be getting here due to the inferior
3410 agent calling us. */
3411 target_pause_all (true);
3413 /* Stop logging. Tracepoints can still be hit, but they will not be
3414 recorded. */
3415 tracing = 0;
3416 if (agent_loaded_p ())
3418 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3420 internal_error ("Error clearing tracing variable in lib");
3424 tracing_stop_time = get_timestamp ();
3425 tracing_stop_reason = "t???";
3426 tracing_stop_tpnum = 0;
3427 if (stopping_tracepoint)
3429 trace_debug ("Stopping the trace because "
3430 "tracepoint %d was hit %" PRIu64 " times",
3431 stopping_tracepoint->number,
3432 stopping_tracepoint->pass_count);
3433 tracing_stop_reason = "tpasscount";
3434 tracing_stop_tpnum = stopping_tracepoint->number;
3436 else if (trace_buffer_is_full)
3438 trace_debug ("Stopping the trace because the trace buffer is full");
3439 tracing_stop_reason = "tfull";
3441 else if (expr_eval_result != expr_eval_no_error)
3443 trace_debug ("Stopping the trace because of an expression eval error");
3444 tracing_stop_reason = eval_result_names[expr_eval_result];
3445 tracing_stop_tpnum = error_tracepoint->number;
3447 #ifndef IN_PROCESS_AGENT
3448 else if (!gdb_connected ())
3450 trace_debug ("Stopping the trace because GDB disconnected");
3451 tracing_stop_reason = "tdisconnected";
3453 #endif
3454 else
3456 trace_debug ("Stopping the trace because of a tstop command");
3457 tracing_stop_reason = "tstop";
3460 stopping_tracepoint = NULL;
3461 error_tracepoint = NULL;
3463 /* Clear out the tracepoints. */
3464 clear_installed_tracepoints ();
3466 if (agent_loaded_p ())
3468 /* Pull in fast tracepoint trace frames from the inferior lib
3469 buffer into our buffer, even if our buffer is already full,
3470 because we want to present the full number of created frames
3471 in addition to what fit in the trace buffer. */
3472 upload_fast_traceframes ();
3475 if (stop_tracing_bkpt != NULL)
3477 delete_breakpoint (stop_tracing_bkpt);
3478 stop_tracing_bkpt = NULL;
3481 if (flush_trace_buffer_bkpt != NULL)
3483 delete_breakpoint (flush_trace_buffer_bkpt);
3484 flush_trace_buffer_bkpt = NULL;
3487 target_unpause_all (true);
3490 static int
3491 stop_tracing_handler (CORE_ADDR addr)
3493 trace_debug ("lib hit stop_tracing");
3495 /* Don't actually handle it here. When we stop tracing we remove
3496 breakpoints from the inferior, and that is not allowed in a
3497 breakpoint handler (as the caller is walking the breakpoint
3498 list). */
3499 return 0;
3502 static int
3503 flush_trace_buffer_handler (CORE_ADDR addr)
3505 trace_debug ("lib hit flush_trace_buffer");
3506 return 0;
3509 static void
3510 cmd_qtstop (char *packet)
3512 stop_tracing ();
3513 write_ok (packet);
3516 static void
3517 cmd_qtdisconnected (char *own_buf)
3519 ULONGEST setting;
3520 char *packet = own_buf;
3522 packet += strlen ("QTDisconnected:");
3524 unpack_varlen_hex (packet, &setting);
3526 write_ok (own_buf);
3528 disconnected_tracing = setting;
3531 static void
3532 cmd_qtframe (char *own_buf)
3534 client_state &cs = get_client_state ();
3535 ULONGEST frame, pc, lo, hi, num;
3536 int tfnum, tpnum;
3537 struct traceframe *tframe;
3538 const char *packet = own_buf;
3540 packet += strlen ("QTFrame:");
3542 if (startswith (packet, "pc:"))
3544 packet += strlen ("pc:");
3545 unpack_varlen_hex (packet, &pc);
3546 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3547 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3549 else if (startswith (packet, "range:"))
3551 packet += strlen ("range:");
3552 packet = unpack_varlen_hex (packet, &lo);
3553 ++packet;
3554 unpack_varlen_hex (packet, &hi);
3555 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3556 paddress (lo), paddress (hi));
3557 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3559 else if (startswith (packet, "outside:"))
3561 packet += strlen ("outside:");
3562 packet = unpack_varlen_hex (packet, &lo);
3563 ++packet;
3564 unpack_varlen_hex (packet, &hi);
3565 trace_debug ("Want to find next traceframe "
3566 "outside the range 0x%s to 0x%s",
3567 paddress (lo), paddress (hi));
3568 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3570 else if (startswith (packet, "tdp:"))
3572 packet += strlen ("tdp:");
3573 unpack_varlen_hex (packet, &num);
3574 tpnum = (int) num;
3575 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3576 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3578 else
3580 unpack_varlen_hex (packet, &frame);
3581 tfnum = (int) frame;
3582 if (tfnum == -1)
3584 trace_debug ("Want to stop looking at traceframes");
3585 cs.current_traceframe = -1;
3586 write_ok (own_buf);
3587 return;
3589 trace_debug ("Want to look at traceframe %d", tfnum);
3590 tframe = find_traceframe (tfnum);
3593 if (tframe)
3595 cs.current_traceframe = tfnum;
3596 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3598 else
3599 sprintf (own_buf, "F-1");
3602 static void
3603 cmd_qtstatus (char *packet)
3605 char *stop_reason_rsp = NULL;
3606 char *buf1, *buf2, *buf3;
3607 const char *str;
3608 int slen;
3610 /* Translate the plain text of the notes back into hex for
3611 transmission. */
3613 str = (tracing_user_name ? tracing_user_name : "");
3614 slen = strlen (str);
3615 buf1 = (char *) alloca (slen * 2 + 1);
3616 bin2hex ((gdb_byte *) str, buf1, slen);
3618 str = (tracing_notes ? tracing_notes : "");
3619 slen = strlen (str);
3620 buf2 = (char *) alloca (slen * 2 + 1);
3621 bin2hex ((gdb_byte *) str, buf2, slen);
3623 str = (tracing_stop_note ? tracing_stop_note : "");
3624 slen = strlen (str);
3625 buf3 = (char *) alloca (slen * 2 + 1);
3626 bin2hex ((gdb_byte *) str, buf3, slen);
3628 trace_debug ("Returning trace status as %d, stop reason %s",
3629 tracing, tracing_stop_reason);
3631 if (agent_loaded_p ())
3633 target_pause_all (true);
3635 upload_fast_traceframes ();
3637 target_unpause_all (true);
3640 stop_reason_rsp = (char *) tracing_stop_reason;
3642 /* The user visible error string in terror needs to be hex encoded.
3643 We leave it as plain string in `tracing_stop_reason' to ease
3644 debugging. */
3645 if (startswith (stop_reason_rsp, "terror:"))
3647 const char *result_name;
3648 int hexstr_len;
3649 char *p;
3651 result_name = stop_reason_rsp + strlen ("terror:");
3652 hexstr_len = strlen (result_name) * 2;
3653 p = stop_reason_rsp
3654 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3655 strcpy (p, "terror:");
3656 p += strlen (p);
3657 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3660 /* If this was a forced stop, include any stop note that was supplied. */
3661 if (strcmp (stop_reason_rsp, "tstop") == 0)
3663 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3664 strcpy (stop_reason_rsp, "tstop:");
3665 strcat (stop_reason_rsp, buf3);
3668 sprintf (packet,
3669 "T%d;"
3670 "%s:%x;"
3671 "tframes:%x;tcreated:%x;"
3672 "tfree:%x;tsize:%s;"
3673 "circular:%d;"
3674 "disconn:%d;"
3675 "starttime:%s;stoptime:%s;"
3676 "username:%s;notes:%s:",
3677 tracing ? 1 : 0,
3678 stop_reason_rsp, tracing_stop_tpnum,
3679 traceframe_count, traceframes_created,
3680 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3681 circular_trace_buffer,
3682 disconnected_tracing,
3683 phex_nz (tracing_start_time, sizeof (tracing_start_time)),
3684 phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
3685 buf1, buf2);
3688 static void
3689 cmd_qtp (char *own_buf)
3691 ULONGEST num, addr;
3692 struct tracepoint *tpoint;
3693 const char *packet = own_buf;
3695 packet += strlen ("qTP:");
3697 packet = unpack_varlen_hex (packet, &num);
3698 ++packet; /* skip a colon */
3699 packet = unpack_varlen_hex (packet, &addr);
3701 /* See if we already have this tracepoint. */
3702 tpoint = find_tracepoint (num, addr);
3704 if (!tpoint)
3706 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3707 (int) num, paddress (addr));
3708 write_enn (own_buf);
3709 return;
3712 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3713 tpoint->traceframe_usage);
3716 /* State variables to help return all the tracepoint bits. */
3717 static struct tracepoint *cur_tpoint;
3718 static unsigned int cur_action;
3719 static unsigned int cur_step_action;
3720 static struct source_string *cur_source_string;
3721 static struct trace_state_variable *cur_tsv;
3723 /* Compose a response that is an imitation of the syntax by which the
3724 tracepoint was originally downloaded. */
3726 static void
3727 response_tracepoint (char *packet, struct tracepoint *tpoint)
3729 char *buf;
3731 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3732 paddress (tpoint->address),
3733 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3734 tpoint->pass_count);
3735 if (tpoint->type == fast_tracepoint)
3736 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3737 else if (tpoint->type == static_tracepoint)
3738 sprintf (packet + strlen (packet), ":S");
3740 if (tpoint->cond)
3742 buf = gdb_unparse_agent_expr (tpoint->cond);
3743 sprintf (packet + strlen (packet), ":X%x,%s",
3744 tpoint->cond->length, buf);
3745 free (buf);
3749 /* Compose a response that is an imitation of the syntax by which the
3750 tracepoint action was originally downloaded (with the difference
3751 that due to the way we store the actions, this will output a packet
3752 per action, while GDB could have combined more than one action
3753 per-packet. */
3755 static void
3756 response_action (char *packet, struct tracepoint *tpoint,
3757 char *taction, int step)
3759 sprintf (packet, "%c%x:%s:%s",
3760 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3761 taction);
3764 /* Compose a response that is an imitation of the syntax by which the
3765 tracepoint source piece was originally downloaded. */
3767 static void
3768 response_source (char *packet,
3769 struct tracepoint *tpoint, struct source_string *src)
3771 char *buf;
3772 int len;
3774 len = strlen (src->str);
3775 buf = (char *) alloca (len * 2 + 1);
3776 bin2hex ((gdb_byte *) src->str, buf, len);
3778 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3779 tpoint->number, paddress (tpoint->address),
3780 src->type, 0, len, buf);
3783 /* Return the first piece of tracepoint definition, and initialize the
3784 state machine that will iterate through all the tracepoint
3785 bits. */
3787 static void
3788 cmd_qtfp (char *packet)
3790 trace_debug ("Returning first tracepoint definition piece");
3792 cur_tpoint = tracepoints;
3793 cur_action = cur_step_action = 0;
3794 cur_source_string = NULL;
3796 if (cur_tpoint)
3797 response_tracepoint (packet, cur_tpoint);
3798 else
3799 strcpy (packet, "l");
3802 /* Return additional pieces of tracepoint definition. Each action and
3803 stepping action must go into its own packet, because of packet size
3804 limits, and so we use state variables to deliver one piece at a
3805 time. */
3807 static void
3808 cmd_qtsp (char *packet)
3810 trace_debug ("Returning subsequent tracepoint definition piece");
3812 if (!cur_tpoint)
3814 /* This case would normally never occur, but be prepared for
3815 GDB misbehavior. */
3816 strcpy (packet, "l");
3818 else if (cur_action < cur_tpoint->numactions)
3820 response_action (packet, cur_tpoint,
3821 cur_tpoint->actions_str[cur_action], 0);
3822 ++cur_action;
3824 else if (cur_step_action < cur_tpoint->num_step_actions)
3826 response_action (packet, cur_tpoint,
3827 cur_tpoint->step_actions_str[cur_step_action], 1);
3828 ++cur_step_action;
3830 else if ((cur_source_string
3831 ? cur_source_string->next
3832 : cur_tpoint->source_strings))
3834 if (cur_source_string)
3835 cur_source_string = cur_source_string->next;
3836 else
3837 cur_source_string = cur_tpoint->source_strings;
3838 response_source (packet, cur_tpoint, cur_source_string);
3840 else
3842 cur_tpoint = cur_tpoint->next;
3843 cur_action = cur_step_action = 0;
3844 cur_source_string = NULL;
3845 if (cur_tpoint)
3846 response_tracepoint (packet, cur_tpoint);
3847 else
3848 strcpy (packet, "l");
3852 /* Compose a response that is an imitation of the syntax by which the
3853 trace state variable was originally downloaded. */
3855 static void
3856 response_tsv (char *packet, struct trace_state_variable *tsv)
3858 char *buf = (char *) "";
3859 int namelen;
3861 if (tsv->name)
3863 namelen = strlen (tsv->name);
3864 buf = (char *) alloca (namelen * 2 + 1);
3865 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3868 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3869 tsv->getter ? 1 : 0, buf);
3872 /* Return the first trace state variable definition, and initialize
3873 the state machine that will iterate through all the tsv bits. */
3875 static void
3876 cmd_qtfv (char *packet)
3878 trace_debug ("Returning first trace state variable definition");
3880 cur_tsv = trace_state_variables;
3882 if (cur_tsv)
3883 response_tsv (packet, cur_tsv);
3884 else
3885 strcpy (packet, "l");
3888 /* Return additional trace state variable definitions. */
3890 static void
3891 cmd_qtsv (char *packet)
3893 trace_debug ("Returning additional trace state variable definition");
3895 if (cur_tsv)
3897 cur_tsv = cur_tsv->next;
3898 if (cur_tsv)
3899 response_tsv (packet, cur_tsv);
3900 else
3901 strcpy (packet, "l");
3903 else
3904 strcpy (packet, "l");
3907 /* Return the first static tracepoint marker, and initialize the state
3908 machine that will iterate through all the static tracepoints
3909 markers. */
3911 static void
3912 cmd_qtfstm (char *packet)
3914 if (!maybe_write_ipa_ust_not_loaded (packet))
3915 run_inferior_command (packet, strlen (packet) + 1);
3918 /* Return additional static tracepoints markers. */
3920 static void
3921 cmd_qtsstm (char *packet)
3923 if (!maybe_write_ipa_ust_not_loaded (packet))
3924 run_inferior_command (packet, strlen (packet) + 1);
3927 /* Return the definition of the static tracepoint at a given address.
3928 Result packet is the same as qTsST's. */
3930 static void
3931 cmd_qtstmat (char *packet)
3933 if (!maybe_write_ipa_ust_not_loaded (packet))
3934 run_inferior_command (packet, strlen (packet) + 1);
3937 /* Sent the agent a command to close it. */
3939 void
3940 gdb_agent_about_to_close (int pid)
3942 char buf[IPA_CMD_BUF_SIZE];
3944 if (!maybe_write_ipa_not_loaded (buf))
3946 scoped_restore_current_thread restore_thread;
3948 /* Find any thread which belongs to process PID. */
3949 switch_to_thread (find_any_thread_of_pid (pid));
3951 strcpy (buf, "close");
3953 run_inferior_command (buf, strlen (buf) + 1);
3957 /* Return the minimum instruction size needed for fast tracepoints as a
3958 hexadecimal number. */
3960 static void
3961 cmd_qtminftpilen (char *packet)
3963 if (current_thread == NULL)
3965 /* Indicate that the minimum length is currently unknown. */
3966 strcpy (packet, "0");
3967 return;
3970 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3973 /* Respond to qTBuffer packet with a block of raw data from the trace
3974 buffer. GDB may ask for a lot, but we are allowed to reply with
3975 only as much as will fit within packet limits or whatever. */
3977 static void
3978 cmd_qtbuffer (char *own_buf)
3980 ULONGEST offset, num, tot;
3981 unsigned char *tbp;
3982 const char *packet = own_buf;
3984 packet += strlen ("qTBuffer:");
3986 packet = unpack_varlen_hex (packet, &offset);
3987 ++packet; /* skip a comma */
3988 unpack_varlen_hex (packet, &num);
3990 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3991 (int) num, phex_nz (offset, 0));
3993 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3995 /* If we're right at the end, reply specially that we're done. */
3996 if (offset == tot)
3998 strcpy (own_buf, "l");
3999 return;
4002 /* Object to any other out-of-bounds request. */
4003 if (offset > tot)
4005 write_enn (own_buf);
4006 return;
4009 /* Compute the pointer corresponding to the given offset, accounting
4010 for wraparound. */
4011 tbp = trace_buffer_start + offset;
4012 if (tbp >= trace_buffer_wrap)
4013 tbp -= (trace_buffer_wrap - trace_buffer_lo);
4015 /* Trim to the remaining bytes if we're close to the end. */
4016 if (num > tot - offset)
4017 num = tot - offset;
4019 /* Trim to available packet size. */
4020 if (num >= (PBUFSIZ - 16) / 2 )
4021 num = (PBUFSIZ - 16) / 2;
4023 bin2hex (tbp, own_buf, num);
4026 static void
4027 cmd_bigqtbuffer_circular (char *own_buf)
4029 ULONGEST val;
4030 char *packet = own_buf;
4032 packet += strlen ("QTBuffer:circular:");
4034 unpack_varlen_hex (packet, &val);
4035 circular_trace_buffer = val;
4036 trace_debug ("Trace buffer is now %s",
4037 circular_trace_buffer ? "circular" : "linear");
4038 write_ok (own_buf);
4041 static void
4042 cmd_bigqtbuffer_size (char *own_buf)
4044 ULONGEST val;
4045 LONGEST sval;
4046 char *packet = own_buf;
4048 /* Can't change the size during a tracing run. */
4049 if (tracing)
4051 write_enn (own_buf);
4052 return;
4055 packet += strlen ("QTBuffer:size:");
4057 /* -1 is sent as literal "-1". */
4058 if (strcmp (packet, "-1") == 0)
4059 sval = DEFAULT_TRACE_BUFFER_SIZE;
4060 else
4062 unpack_varlen_hex (packet, &val);
4063 sval = (LONGEST) val;
4066 init_trace_buffer (sval);
4067 trace_debug ("Trace buffer is now %s bytes",
4068 plongest (trace_buffer_size));
4069 write_ok (own_buf);
4072 static void
4073 cmd_qtnotes (char *own_buf)
4075 size_t nbytes;
4076 char *saved, *user, *notes, *stopnote;
4077 char *packet = own_buf;
4079 packet += strlen ("QTNotes:");
4081 while (*packet)
4083 if (startswith (packet, "user:"))
4085 packet += strlen ("user:");
4086 saved = packet;
4087 packet = strchr (packet, ';');
4088 nbytes = (packet - saved) / 2;
4089 user = (char *) xmalloc (nbytes + 1);
4090 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
4091 user[nbytes] = '\0';
4092 ++packet; /* skip the semicolon */
4093 trace_debug ("User is '%s'", user);
4094 xfree (tracing_user_name);
4095 tracing_user_name = user;
4097 else if (startswith (packet, "notes:"))
4099 packet += strlen ("notes:");
4100 saved = packet;
4101 packet = strchr (packet, ';');
4102 nbytes = (packet - saved) / 2;
4103 notes = (char *) xmalloc (nbytes + 1);
4104 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
4105 notes[nbytes] = '\0';
4106 ++packet; /* skip the semicolon */
4107 trace_debug ("Notes is '%s'", notes);
4108 xfree (tracing_notes);
4109 tracing_notes = notes;
4111 else if (startswith (packet, "tstop:"))
4113 packet += strlen ("tstop:");
4114 saved = packet;
4115 packet = strchr (packet, ';');
4116 nbytes = (packet - saved) / 2;
4117 stopnote = (char *) xmalloc (nbytes + 1);
4118 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
4119 stopnote[nbytes] = '\0';
4120 ++packet; /* skip the semicolon */
4121 trace_debug ("tstop note is '%s'", stopnote);
4122 xfree (tracing_stop_note);
4123 tracing_stop_note = stopnote;
4125 else
4126 break;
4129 write_ok (own_buf);
4133 handle_tracepoint_general_set (char *packet)
4135 if (strcmp ("QTinit", packet) == 0)
4137 cmd_qtinit (packet);
4138 return 1;
4140 else if (startswith (packet, "QTDP:"))
4142 cmd_qtdp (packet);
4143 return 1;
4145 else if (startswith (packet, "QTDPsrc:"))
4147 cmd_qtdpsrc (packet);
4148 return 1;
4150 else if (startswith (packet, "QTEnable:"))
4152 cmd_qtenable_disable (packet, 1);
4153 return 1;
4155 else if (startswith (packet, "QTDisable:"))
4157 cmd_qtenable_disable (packet, 0);
4158 return 1;
4160 else if (startswith (packet, "QTDV:"))
4162 cmd_qtdv (packet);
4163 return 1;
4165 else if (startswith (packet, "QTro:"))
4167 cmd_qtro (packet);
4168 return 1;
4170 else if (strcmp ("QTStart", packet) == 0)
4172 cmd_qtstart (packet);
4173 return 1;
4175 else if (strcmp ("QTStop", packet) == 0)
4177 cmd_qtstop (packet);
4178 return 1;
4180 else if (startswith (packet, "QTDisconnected:"))
4182 cmd_qtdisconnected (packet);
4183 return 1;
4185 else if (startswith (packet, "QTFrame:"))
4187 cmd_qtframe (packet);
4188 return 1;
4190 else if (startswith (packet, "QTBuffer:circular:"))
4192 cmd_bigqtbuffer_circular (packet);
4193 return 1;
4195 else if (startswith (packet, "QTBuffer:size:"))
4197 cmd_bigqtbuffer_size (packet);
4198 return 1;
4200 else if (startswith (packet, "QTNotes:"))
4202 cmd_qtnotes (packet);
4203 return 1;
4206 return 0;
4210 handle_tracepoint_query (char *packet)
4212 if (strcmp ("qTStatus", packet) == 0)
4214 cmd_qtstatus (packet);
4215 return 1;
4217 else if (startswith (packet, "qTP:"))
4219 cmd_qtp (packet);
4220 return 1;
4222 else if (strcmp ("qTfP", packet) == 0)
4224 cmd_qtfp (packet);
4225 return 1;
4227 else if (strcmp ("qTsP", packet) == 0)
4229 cmd_qtsp (packet);
4230 return 1;
4232 else if (strcmp ("qTfV", packet) == 0)
4234 cmd_qtfv (packet);
4235 return 1;
4237 else if (strcmp ("qTsV", packet) == 0)
4239 cmd_qtsv (packet);
4240 return 1;
4242 else if (startswith (packet, "qTV:"))
4244 cmd_qtv (packet);
4245 return 1;
4247 else if (startswith (packet, "qTBuffer:"))
4249 cmd_qtbuffer (packet);
4250 return 1;
4252 else if (strcmp ("qTfSTM", packet) == 0)
4254 cmd_qtfstm (packet);
4255 return 1;
4257 else if (strcmp ("qTsSTM", packet) == 0)
4259 cmd_qtsstm (packet);
4260 return 1;
4262 else if (startswith (packet, "qTSTMat:"))
4264 cmd_qtstmat (packet);
4265 return 1;
4267 else if (strcmp ("qTMinFTPILen", packet) == 0)
4269 cmd_qtminftpilen (packet);
4270 return 1;
4273 return 0;
4276 #endif
4277 #ifndef IN_PROCESS_AGENT
4279 /* Call this when thread TINFO has hit the tracepoint defined by
4280 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
4281 action. This adds a while-stepping collecting state item to the
4282 threads' collecting state list, so that we can keep track of
4283 multiple simultaneous while-stepping actions being collected by the
4284 same thread. This can happen in cases like:
4286 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
4287 ff0002 INSN2
4288 ff0003 INSN3 <-- TP2, collect $regs
4289 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
4290 ff0005 INSN5
4292 Notice that when instruction INSN5 is reached, the while-stepping
4293 actions of both TP1 and TP3 are still being collected, and that TP2
4294 had been collected meanwhile. The whole range of ff0001-ff0005
4295 should be single-stepped, due to at least TP1's while-stepping
4296 action covering the whole range. */
4298 static void
4299 add_while_stepping_state (struct thread_info *tinfo,
4300 int tp_number, CORE_ADDR tp_address)
4302 struct wstep_state *wstep = XNEW (struct wstep_state);
4304 wstep->next = tinfo->while_stepping;
4306 wstep->tp_number = tp_number;
4307 wstep->tp_address = tp_address;
4308 wstep->current_step = 0;
4310 tinfo->while_stepping = wstep;
4313 /* Release the while-stepping collecting state WSTEP. */
4315 static void
4316 release_while_stepping_state (struct wstep_state *wstep)
4318 free (wstep);
4321 /* Release all while-stepping collecting states currently associated
4322 with thread TINFO. */
4324 void
4325 release_while_stepping_state_list (struct thread_info *tinfo)
4327 struct wstep_state *head;
4329 while (tinfo->while_stepping)
4331 head = tinfo->while_stepping;
4332 tinfo->while_stepping = head->next;
4333 release_while_stepping_state (head);
4337 /* If TINFO was handling a 'while-stepping' action, the step has
4338 finished, so collect any step data needed, and check if any more
4339 steps are required. Return true if the thread was indeed
4340 collecting tracepoint data, false otherwise. */
4343 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
4345 struct tracepoint *tpoint;
4346 struct wstep_state *wstep;
4347 struct wstep_state **wstep_link;
4348 struct trap_tracepoint_ctx ctx;
4350 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4351 our buffer. */
4352 if (agent_loaded_p ())
4353 upload_fast_traceframes ();
4355 /* Check if we were indeed collecting data for one of more
4356 tracepoints with a 'while-stepping' count. */
4357 if (tinfo->while_stepping == NULL)
4358 return 0;
4360 if (!tracing)
4362 /* We're not even tracing anymore. Stop this thread from
4363 collecting. */
4364 release_while_stepping_state_list (tinfo);
4366 /* The thread had stopped due to a single-step request indeed
4367 explained by a tracepoint. */
4368 return 1;
4371 wstep = tinfo->while_stepping;
4372 wstep_link = &tinfo->while_stepping;
4374 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4375 target_pid_to_str (tinfo->id).c_str (),
4376 wstep->tp_number, paddress (wstep->tp_address));
4378 ctx.base.type = trap_tracepoint;
4379 ctx.regcache = get_thread_regcache (tinfo, 1);
4381 while (wstep != NULL)
4383 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4384 if (tpoint == NULL)
4386 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4387 wstep->tp_number, paddress (wstep->tp_address),
4388 target_pid_to_str (tinfo->id).c_str ());
4390 /* Unlink. */
4391 *wstep_link = wstep->next;
4392 release_while_stepping_state (wstep);
4393 wstep = *wstep_link;
4394 continue;
4397 /* We've just finished one step. */
4398 ++wstep->current_step;
4400 /* Collect data. */
4401 collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
4402 stop_pc, tpoint, wstep->current_step);
4404 if (wstep->current_step >= tpoint->step_count)
4406 /* The requested numbers of steps have occurred. */
4407 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4408 target_pid_to_str (tinfo->id).c_str (),
4409 wstep->tp_number, paddress (wstep->tp_address));
4411 /* Unlink the wstep. */
4412 *wstep_link = wstep->next;
4413 release_while_stepping_state (wstep);
4414 wstep = *wstep_link;
4416 /* Only check the hit count now, which ensure that we do all
4417 our stepping before stopping the run. */
4418 if (tpoint->pass_count > 0
4419 && tpoint->hit_count >= tpoint->pass_count
4420 && stopping_tracepoint == NULL)
4421 stopping_tracepoint = tpoint;
4423 else
4425 /* Keep single-stepping until the requested numbers of steps
4426 have occurred. */
4427 wstep_link = &wstep->next;
4428 wstep = *wstep_link;
4431 if (stopping_tracepoint
4432 || trace_buffer_is_full
4433 || expr_eval_result != expr_eval_no_error)
4435 stop_tracing ();
4436 break;
4440 return 1;
4443 /* Handle any internal tracing control breakpoint hits. That means,
4444 pull traceframes from the IPA to our buffer, and syncing both
4445 tracing agents when the IPA's tracing stops for some reason. */
4448 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
4450 /* Pull in fast tracepoint trace frames from the inferior in-process
4451 agent's buffer into our buffer. */
4453 if (!agent_loaded_p ())
4454 return 0;
4456 upload_fast_traceframes ();
4458 /* Check if the in-process agent had decided we should stop
4459 tracing. */
4460 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4462 int ipa_trace_buffer_is_full;
4463 CORE_ADDR ipa_stopping_tracepoint;
4464 int ipa_expr_eval_result;
4465 CORE_ADDR ipa_error_tracepoint;
4467 trace_debug ("lib stopped at stop_tracing");
4469 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4470 &ipa_trace_buffer_is_full);
4472 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4473 &ipa_stopping_tracepoint);
4474 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4476 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4477 &ipa_error_tracepoint);
4478 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4480 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4481 &ipa_expr_eval_result);
4482 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4484 trace_debug ("lib: trace_buffer_is_full: %d, "
4485 "stopping_tracepoint: %s, "
4486 "ipa_expr_eval_result: %d, "
4487 "error_tracepoint: %s, ",
4488 ipa_trace_buffer_is_full,
4489 paddress (ipa_stopping_tracepoint),
4490 ipa_expr_eval_result,
4491 paddress (ipa_error_tracepoint));
4493 if (ipa_trace_buffer_is_full)
4494 trace_debug ("lib stopped due to full buffer.");
4496 if (ipa_stopping_tracepoint)
4497 trace_debug ("lib stopped due to tpoint");
4499 if (ipa_error_tracepoint)
4500 trace_debug ("lib stopped due to error");
4502 if (ipa_stopping_tracepoint != 0)
4504 stopping_tracepoint
4505 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4507 else if (ipa_expr_eval_result != expr_eval_no_error)
4509 expr_eval_result = ipa_expr_eval_result;
4510 error_tracepoint
4511 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4513 stop_tracing ();
4514 return 1;
4516 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4518 trace_debug ("lib stopped at flush_trace_buffer");
4519 return 1;
4522 return 0;
4525 /* Return true if TINFO just hit a tracepoint. Collect data if
4526 so. */
4529 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
4531 struct tracepoint *tpoint;
4532 int ret = 0;
4533 struct trap_tracepoint_ctx ctx;
4535 /* Not tracing, don't handle. */
4536 if (!tracing)
4537 return 0;
4539 ctx.base.type = trap_tracepoint;
4540 ctx.regcache = get_thread_regcache (tinfo, 1);
4542 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4544 /* Note that we collect fast tracepoints here as well. We'll
4545 step over the fast tracepoint jump later, which avoids the
4546 double collect. However, we don't collect for static
4547 tracepoints here, because UST markers are compiled in program,
4548 and probes will be executed in program. So static tracepoints
4549 are collected there. */
4550 if (tpoint->enabled && stop_pc == tpoint->address
4551 && tpoint->type != static_tracepoint)
4553 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4554 target_pid_to_str (tinfo->id).c_str (),
4555 tpoint->number, paddress (tpoint->address));
4557 /* Test the condition if present, and collect if true. */
4558 if (!tpoint->cond
4559 || (condition_true_at_tracepoint
4560 ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
4561 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
4562 stop_pc, tpoint);
4564 if (stopping_tracepoint
4565 || trace_buffer_is_full
4566 || expr_eval_result != expr_eval_no_error)
4568 stop_tracing ();
4570 /* If the tracepoint had a 'while-stepping' action, then set
4571 the thread to collect this tracepoint on the following
4572 single-steps. */
4573 else if (tpoint->step_count > 0)
4575 add_while_stepping_state (tinfo,
4576 tpoint->number, tpoint->address);
4579 ret = 1;
4583 return ret;
4586 #endif
4588 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4589 struct ust_marker_data;
4590 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4591 struct traceframe *tframe);
4592 #endif
4594 /* Create a trace frame for the hit of the given tracepoint in the
4595 given thread. */
4597 static void
4598 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4599 struct tracepoint *tpoint)
4601 struct traceframe *tframe;
4602 int acti;
4604 /* Only count it as a hit when we actually collect data. */
4605 tpoint->hit_count++;
4607 /* If we've exceeded a defined pass count, record the event for
4608 later, and finish the collection for this hit. This test is only
4609 for nonstepping tracepoints, stepping tracepoints test at the end
4610 of their while-stepping loop. */
4611 if (tpoint->pass_count > 0
4612 && tpoint->hit_count >= tpoint->pass_count
4613 && tpoint->step_count == 0
4614 && stopping_tracepoint == NULL)
4615 stopping_tracepoint = tpoint;
4617 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4618 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4620 tframe = add_traceframe (tpoint);
4622 if (tframe)
4624 for (acti = 0; acti < tpoint->numactions; ++acti)
4626 #ifndef IN_PROCESS_AGENT
4627 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4628 tpoint->number, paddress (tpoint->address),
4629 tpoint->actions_str[acti]);
4630 #endif
4632 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4633 tpoint->actions[acti]);
4636 finish_traceframe (tframe);
4639 if (tframe == NULL && tracing)
4640 trace_buffer_is_full = 1;
4643 #ifndef IN_PROCESS_AGENT
4645 static void
4646 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4647 CORE_ADDR stop_pc,
4648 struct tracepoint *tpoint, int current_step)
4650 struct traceframe *tframe;
4651 int acti;
4653 trace_debug ("Making new step traceframe for "
4654 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4655 tpoint->number, paddress (tpoint->address),
4656 current_step, tpoint->step_count,
4657 tpoint->hit_count);
4659 tframe = add_traceframe (tpoint);
4661 if (tframe)
4663 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4665 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4666 tpoint->number, paddress (tpoint->address),
4667 tpoint->step_actions_str[acti]);
4669 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4670 tpoint->step_actions[acti]);
4673 finish_traceframe (tframe);
4676 if (tframe == NULL && tracing)
4677 trace_buffer_is_full = 1;
4680 #endif
4682 #ifdef IN_PROCESS_AGENT
4683 /* The target description index for IPA. Passed from gdbserver, used
4684 to select ipa_tdesc. */
4685 extern "C" {
4686 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
4688 #endif
4690 static struct regcache *
4691 get_context_regcache (struct tracepoint_hit_ctx *ctx)
4693 struct regcache *regcache = NULL;
4694 #ifdef IN_PROCESS_AGENT
4695 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
4697 if (ctx->type == fast_tracepoint)
4699 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4700 if (!fctx->regcache_initted)
4702 fctx->regcache_initted = 1;
4703 init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
4704 supply_regblock (&fctx->regcache, NULL);
4705 supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
4707 regcache = &fctx->regcache;
4709 #ifdef HAVE_UST
4710 if (ctx->type == static_tracepoint)
4712 struct static_tracepoint_ctx *sctx
4713 = (struct static_tracepoint_ctx *) ctx;
4715 if (!sctx->regcache_initted)
4717 sctx->regcache_initted = 1;
4718 init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
4719 supply_regblock (&sctx->regcache, NULL);
4720 /* Pass down the tracepoint address, because REGS doesn't
4721 include the PC, but we know what it must have been. */
4722 supply_static_tracepoint_registers (&sctx->regcache,
4723 (const unsigned char *)
4724 sctx->regs,
4725 sctx->tpoint->address);
4727 regcache = &sctx->regcache;
4729 #endif
4730 #else
4731 if (ctx->type == trap_tracepoint)
4733 struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
4734 regcache = tctx->regcache;
4736 #endif
4738 gdb_assert (regcache != NULL);
4740 return regcache;
4743 static void
4744 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4745 CORE_ADDR stop_pc,
4746 struct tracepoint *tpoint,
4747 struct traceframe *tframe,
4748 struct tracepoint_action *taction)
4750 enum eval_result_type err;
4752 switch (taction->type)
4754 case 'M':
4756 struct collect_memory_action *maction;
4757 struct eval_agent_expr_context ax_ctx;
4759 maction = (struct collect_memory_action *) taction;
4760 ax_ctx.regcache = NULL;
4761 ax_ctx.tframe = tframe;
4762 ax_ctx.tpoint = tpoint;
4764 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4765 pulongest (maction->len),
4766 paddress (maction->addr), maction->basereg);
4767 /* (should use basereg) */
4768 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4769 maction->len);
4770 break;
4772 case 'R':
4774 unsigned char *regspace;
4775 struct regcache tregcache;
4776 struct regcache *context_regcache;
4777 int regcache_size;
4779 trace_debug ("Want to collect registers");
4781 context_regcache = get_context_regcache (ctx);
4782 regcache_size = register_cache_size (context_regcache->tdesc);
4784 /* Collect all registers for now. */
4785 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4786 if (regspace == NULL)
4788 trace_debug ("Trace buffer block allocation failed, skipping");
4789 break;
4791 /* Identify a register block. */
4792 *regspace = 'R';
4794 /* Wrap the regblock in a register cache (in the stack, we
4795 don't want to malloc here). */
4796 init_register_cache (&tregcache, context_regcache->tdesc,
4797 regspace + 1);
4799 /* Copy the register data to the regblock. */
4800 regcache_cpy (&tregcache, context_regcache);
4802 #ifndef IN_PROCESS_AGENT
4803 /* On some platforms, trap-based tracepoints will have the PC
4804 pointing to the next instruction after the trap, but we
4805 don't want the user or GDB trying to guess whether the
4806 saved PC needs adjusting; so always record the adjusted
4807 stop_pc. Note that we can't use tpoint->address instead,
4808 since it will be wrong for while-stepping actions. This
4809 adjustment is a nop for fast tracepoints collected from the
4810 in-process lib (but not if GDBserver is collecting one
4811 preemptively), since the PC had already been adjusted to
4812 contain the tracepoint's address by the jump pad. */
4813 trace_debug ("Storing stop pc (0x%s) in regblock",
4814 paddress (stop_pc));
4816 /* This changes the regblock, not the thread's
4817 regcache. */
4818 regcache_write_pc (&tregcache, stop_pc);
4819 #endif
4821 break;
4822 case 'X':
4824 struct eval_expr_action *eaction;
4825 struct eval_agent_expr_context ax_ctx;
4827 eaction = (struct eval_expr_action *) taction;
4828 ax_ctx.regcache = get_context_regcache (ctx);
4829 ax_ctx.tframe = tframe;
4830 ax_ctx.tpoint = tpoint;
4832 trace_debug ("Want to evaluate expression");
4834 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4836 if (err != expr_eval_no_error)
4838 record_tracepoint_error (tpoint, "action expression", err);
4839 return;
4842 break;
4843 case 'L':
4845 #if defined IN_PROCESS_AGENT && defined HAVE_UST
4846 trace_debug ("Want to collect static trace data");
4847 collect_ust_data_at_tracepoint (ctx, tframe);
4848 #else
4849 trace_debug ("warning: collecting static trace data, "
4850 "but static tracepoints are not supported");
4851 #endif
4853 break;
4854 default:
4855 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4856 break;
4860 static int
4861 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4862 struct tracepoint *tpoint)
4864 ULONGEST value = 0;
4865 enum eval_result_type err;
4867 /* Presently, gdbserver doesn't run compiled conditions, only the
4868 IPA does. If the program stops at a fast tracepoint's address
4869 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4870 gdbserver preemptively collect the fast tracepoint. Later, on
4871 resume, gdbserver steps over the fast tracepoint like it steps
4872 over breakpoints, so that the IPA doesn't see that fast
4873 tracepoint. This avoids double collects of fast tracepoints in
4874 that stopping scenario. Having gdbserver itself handle the fast
4875 tracepoint gives the user a consistent view of when fast or trap
4876 tracepoints are collected, compared to an alternative where only
4877 trap tracepoints are collected on stop, and fast tracepoints on
4878 resume. When a fast tracepoint is being processed by gdbserver,
4879 it is always the non-compiled condition expression that is
4880 used. */
4881 #ifdef IN_PROCESS_AGENT
4882 if (tpoint->compiled_cond)
4884 struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
4885 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4887 else
4888 #endif
4890 struct eval_agent_expr_context ax_ctx;
4892 ax_ctx.regcache = get_context_regcache (ctx);
4893 ax_ctx.tframe = NULL;
4894 ax_ctx.tpoint = tpoint;
4896 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4898 if (err != expr_eval_no_error)
4900 record_tracepoint_error (tpoint, "condition", err);
4901 /* The error case must return false. */
4902 return 0;
4905 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4906 tpoint->number, paddress (tpoint->address),
4907 pulongest (value));
4908 return (value ? 1 : 0);
4911 /* See tracepoint.h. */
4914 agent_mem_read (struct eval_agent_expr_context *ctx,
4915 unsigned char *to, CORE_ADDR from, ULONGEST len)
4917 unsigned char *mspace;
4918 ULONGEST remaining = len;
4919 unsigned short blocklen;
4921 /* If a 'to' buffer is specified, use it. */
4922 if (to != NULL)
4923 return read_inferior_memory (from, to, len);
4925 /* Otherwise, create a new memory block in the trace buffer. */
4926 while (remaining > 0)
4928 size_t sp;
4930 blocklen = (remaining > 65535 ? 65535 : remaining);
4931 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4932 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4933 if (mspace == NULL)
4934 return 1;
4935 /* Identify block as a memory block. */
4936 *mspace = 'M';
4937 ++mspace;
4938 /* Record address and size. */
4939 memcpy (mspace, &from, sizeof (from));
4940 mspace += sizeof (from);
4941 memcpy (mspace, &blocklen, sizeof (blocklen));
4942 mspace += sizeof (blocklen);
4943 /* Record the memory block proper. */
4944 if (read_inferior_memory (from, mspace, blocklen) != 0)
4945 return 1;
4946 trace_debug ("%d bytes recorded", blocklen);
4947 remaining -= blocklen;
4948 from += blocklen;
4950 return 0;
4954 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4955 unsigned char *to, CORE_ADDR from, ULONGEST len)
4957 unsigned char *buf, *mspace;
4958 ULONGEST remaining = len;
4959 unsigned short blocklen, i;
4961 /* To save a bit of space, block lengths are 16-bit, so break large
4962 requests into multiple blocks. Bordering on overkill for strings,
4963 but it could happen that someone specifies a large max length. */
4964 while (remaining > 0)
4966 size_t sp;
4968 blocklen = (remaining > 65535 ? 65535 : remaining);
4969 /* We want working space to accumulate nonzero bytes, since
4970 traceframes must have a predecided size (otherwise it gets
4971 harder to wrap correctly for the circular case, etc). */
4972 buf = (unsigned char *) xmalloc (blocklen + 1);
4973 for (i = 0; i < blocklen; ++i)
4975 /* Read the string one byte at a time, in case the string is
4976 at the end of a valid memory area - we don't want a
4977 correctly-terminated string to engender segvio
4978 complaints. */
4979 read_inferior_memory (from + i, buf + i, 1);
4981 if (buf[i] == '\0')
4983 blocklen = i + 1;
4984 /* Make sure outer loop stops now too. */
4985 remaining = blocklen;
4986 break;
4989 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4990 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4991 if (mspace == NULL)
4993 xfree (buf);
4994 return 1;
4996 /* Identify block as a memory block. */
4997 *mspace = 'M';
4998 ++mspace;
4999 /* Record address and size. */
5000 memcpy ((void *) mspace, (void *) &from, sizeof (from));
5001 mspace += sizeof (from);
5002 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
5003 mspace += sizeof (blocklen);
5004 /* Copy the string contents. */
5005 memcpy ((void *) mspace, (void *) buf, blocklen);
5006 remaining -= blocklen;
5007 from += blocklen;
5008 xfree (buf);
5010 return 0;
5013 /* Record the value of a trace state variable. */
5016 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
5018 unsigned char *vspace;
5019 LONGEST val;
5021 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
5022 1 + sizeof (n) + sizeof (LONGEST));
5023 if (vspace == NULL)
5024 return 1;
5025 /* Identify block as a variable. */
5026 *vspace = 'V';
5027 /* Record variable's number and value. */
5028 memcpy (vspace + 1, &n, sizeof (n));
5029 val = get_trace_state_variable_value (n);
5030 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
5031 trace_debug ("Variable %d recorded", n);
5032 return 0;
5035 #ifndef IN_PROCESS_AGENT
5037 /* Callback for traceframe_walk_blocks, used to find a given block
5038 type in a traceframe. */
5040 static int
5041 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
5043 char *wantedp = (char *) data;
5045 if (*wantedp == blocktype)
5046 return 1;
5048 return 0;
5051 /* Walk over all traceframe blocks of the traceframe buffer starting
5052 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
5053 block found, passing in DATA unmodified. If CALLBACK returns true,
5054 this returns a pointer to where the block is found. Returns NULL
5055 if no callback call returned true, indicating that all blocks have
5056 been walked. */
5058 static unsigned char *
5059 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
5060 int tfnum,
5061 int (*callback) (char blocktype,
5062 unsigned char *dataptr,
5063 void *data),
5064 void *data)
5066 unsigned char *dataptr;
5068 if (datasize == 0)
5070 trace_debug ("traceframe %d has no data", tfnum);
5071 return NULL;
5074 /* Iterate through a traceframe's blocks, looking for a block of the
5075 requested type. */
5076 for (dataptr = database;
5077 dataptr < database + datasize;
5078 /* nothing */)
5080 char blocktype;
5081 unsigned short mlen;
5083 if (dataptr == trace_buffer_wrap)
5085 /* Adjust to reflect wrapping part of the frame around to
5086 the beginning. */
5087 datasize = dataptr - database;
5088 dataptr = database = trace_buffer_lo;
5091 blocktype = *dataptr++;
5093 if ((*callback) (blocktype, dataptr, data))
5094 return dataptr;
5096 switch (blocktype)
5098 case 'R':
5099 /* Skip over the registers block. */
5100 dataptr += current_target_desc ()->registers_size;
5101 break;
5102 case 'M':
5103 /* Skip over the memory block. */
5104 dataptr += sizeof (CORE_ADDR);
5105 memcpy (&mlen, dataptr, sizeof (mlen));
5106 dataptr += (sizeof (mlen) + mlen);
5107 break;
5108 case 'V':
5109 /* Skip over the TSV block. */
5110 dataptr += (sizeof (int) + sizeof (LONGEST));
5111 break;
5112 case 'S':
5113 /* Skip over the static trace data block. */
5114 memcpy (&mlen, dataptr, sizeof (mlen));
5115 dataptr += (sizeof (mlen) + mlen);
5116 break;
5117 default:
5118 trace_debug ("traceframe %d has unknown block type 0x%x",
5119 tfnum, blocktype);
5120 return NULL;
5124 return NULL;
5127 /* Look for the block of type TYPE_WANTED in the traceframe starting
5128 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
5129 number. */
5131 static unsigned char *
5132 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
5133 int tfnum, char type_wanted)
5135 return traceframe_walk_blocks (database, datasize, tfnum,
5136 match_blocktype, &type_wanted);
5139 static unsigned char *
5140 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
5142 unsigned char *regblock;
5144 regblock = traceframe_find_block_type (tframe->data,
5145 tframe->data_size,
5146 tfnum, 'R');
5148 if (regblock == NULL)
5149 trace_debug ("traceframe %d has no register data", tfnum);
5151 return regblock;
5154 /* Get registers from a traceframe. */
5157 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
5159 unsigned char *dataptr;
5160 struct tracepoint *tpoint;
5161 struct traceframe *tframe;
5163 tframe = find_traceframe (tfnum);
5165 if (tframe == NULL)
5167 trace_debug ("traceframe %d not found", tfnum);
5168 return 1;
5171 dataptr = traceframe_find_regblock (tframe, tfnum);
5172 if (dataptr == NULL)
5174 /* Mark registers unavailable. */
5175 supply_regblock (regcache, NULL);
5177 /* We can generally guess at a PC, although this will be
5178 misleading for while-stepping frames and multi-location
5179 tracepoints. */
5180 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
5181 if (tpoint != NULL)
5182 regcache_write_pc (regcache, tpoint->address);
5184 else
5185 supply_regblock (regcache, dataptr);
5187 return 0;
5190 static CORE_ADDR
5191 traceframe_get_pc (struct traceframe *tframe)
5193 struct regcache regcache;
5194 unsigned char *dataptr;
5195 const struct target_desc *tdesc = current_target_desc ();
5197 dataptr = traceframe_find_regblock (tframe, -1);
5198 if (dataptr == NULL)
5199 return 0;
5201 init_register_cache (&regcache, tdesc, dataptr);
5202 return regcache_read_pc (&regcache);
5205 /* Read a requested block of memory from a trace frame. */
5208 traceframe_read_mem (int tfnum, CORE_ADDR addr,
5209 unsigned char *buf, ULONGEST length,
5210 ULONGEST *nbytes)
5212 struct traceframe *tframe;
5213 unsigned char *database, *dataptr;
5214 unsigned int datasize;
5215 CORE_ADDR maddr;
5216 unsigned short mlen;
5218 trace_debug ("traceframe_read_mem");
5220 tframe = find_traceframe (tfnum);
5222 if (!tframe)
5224 trace_debug ("traceframe %d not found", tfnum);
5225 return 1;
5228 datasize = tframe->data_size;
5229 database = dataptr = &tframe->data[0];
5231 /* Iterate through a traceframe's blocks, looking for memory. */
5232 while ((dataptr = traceframe_find_block_type (dataptr,
5233 datasize
5234 - (dataptr - database),
5235 tfnum, 'M')) != NULL)
5237 memcpy (&maddr, dataptr, sizeof (maddr));
5238 dataptr += sizeof (maddr);
5239 memcpy (&mlen, dataptr, sizeof (mlen));
5240 dataptr += sizeof (mlen);
5241 trace_debug ("traceframe %d has %d bytes at %s",
5242 tfnum, mlen, paddress (maddr));
5244 /* If the block includes the first part of the desired range,
5245 return as much it has; GDB will re-request the remainder,
5246 which might be in a different block of this trace frame. */
5247 if (maddr <= addr && addr < (maddr + mlen))
5249 ULONGEST amt = (maddr + mlen) - addr;
5250 if (amt > length)
5251 amt = length;
5253 memcpy (buf, dataptr + (addr - maddr), amt);
5254 *nbytes = amt;
5255 return 0;
5258 /* Skip over this block. */
5259 dataptr += mlen;
5262 trace_debug ("traceframe %d has no memory data for the desired region",
5263 tfnum);
5265 *nbytes = 0;
5266 return 0;
5269 static int
5270 traceframe_read_tsv (int tsvnum, LONGEST *val)
5272 client_state &cs = get_client_state ();
5273 int tfnum;
5274 struct traceframe *tframe;
5275 unsigned char *database, *dataptr;
5276 unsigned int datasize;
5277 int vnum;
5278 int found = 0;
5280 trace_debug ("traceframe_read_tsv");
5282 tfnum = cs.current_traceframe;
5284 if (tfnum < 0)
5286 trace_debug ("no current traceframe");
5287 return 1;
5290 tframe = find_traceframe (tfnum);
5292 if (tframe == NULL)
5294 trace_debug ("traceframe %d not found", tfnum);
5295 return 1;
5298 datasize = tframe->data_size;
5299 database = dataptr = &tframe->data[0];
5301 /* Iterate through a traceframe's blocks, looking for the last
5302 matched tsv. */
5303 while ((dataptr = traceframe_find_block_type (dataptr,
5304 datasize
5305 - (dataptr - database),
5306 tfnum, 'V')) != NULL)
5308 memcpy (&vnum, dataptr, sizeof (vnum));
5309 dataptr += sizeof (vnum);
5311 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
5313 /* Check that this is the variable we want. */
5314 if (tsvnum == vnum)
5316 memcpy (val, dataptr, sizeof (*val));
5317 found = 1;
5320 /* Skip over this block. */
5321 dataptr += sizeof (LONGEST);
5324 if (!found)
5325 trace_debug ("traceframe %d has no data for variable %d",
5326 tfnum, tsvnum);
5327 return !found;
5330 /* Read a requested block of static tracepoint data from a trace
5331 frame. */
5334 traceframe_read_sdata (int tfnum, ULONGEST offset,
5335 unsigned char *buf, ULONGEST length,
5336 ULONGEST *nbytes)
5338 struct traceframe *tframe;
5339 unsigned char *database, *dataptr;
5340 unsigned int datasize;
5341 unsigned short mlen;
5343 trace_debug ("traceframe_read_sdata");
5345 tframe = find_traceframe (tfnum);
5347 if (!tframe)
5349 trace_debug ("traceframe %d not found", tfnum);
5350 return 1;
5353 datasize = tframe->data_size;
5354 database = &tframe->data[0];
5356 /* Iterate through a traceframe's blocks, looking for static
5357 tracepoint data. */
5358 dataptr = traceframe_find_block_type (database, datasize,
5359 tfnum, 'S');
5360 if (dataptr != NULL)
5362 memcpy (&mlen, dataptr, sizeof (mlen));
5363 dataptr += sizeof (mlen);
5364 if (offset < mlen)
5366 if (offset + length > mlen)
5367 length = mlen - offset;
5369 memcpy (buf, dataptr, length);
5370 *nbytes = length;
5372 else
5373 *nbytes = 0;
5374 return 0;
5377 trace_debug ("traceframe %d has no static trace data", tfnum);
5379 *nbytes = 0;
5380 return 0;
5383 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
5384 object. DATA is pointer to a string holding the traceframe-info
5385 object being built. */
5387 static int
5388 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
5390 std::string *buffer = (std::string *) data;
5392 switch (blocktype)
5394 case 'M':
5396 unsigned short mlen;
5397 CORE_ADDR maddr;
5399 memcpy (&maddr, dataptr, sizeof (maddr));
5400 dataptr += sizeof (maddr);
5401 memcpy (&mlen, dataptr, sizeof (mlen));
5402 dataptr += sizeof (mlen);
5403 string_xml_appendf (*buffer,
5404 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
5405 paddress (maddr), phex_nz (mlen, sizeof (mlen)));
5406 break;
5408 case 'V':
5410 int vnum;
5412 memcpy (&vnum, dataptr, sizeof (vnum));
5413 string_xml_appendf (*buffer, "<tvar id=\"%d\"/>\n", vnum);
5414 break;
5416 case 'R':
5417 case 'S':
5419 break;
5421 default:
5422 warning ("Unhandled trace block type (%d) '%c ' "
5423 "while building trace frame info.",
5424 blocktype, blocktype);
5425 break;
5428 return 0;
5431 /* Build a traceframe-info object for traceframe number TFNUM into
5432 BUFFER. */
5435 traceframe_read_info (int tfnum, std::string *buffer)
5437 struct traceframe *tframe;
5439 trace_debug ("traceframe_read_info");
5441 tframe = find_traceframe (tfnum);
5443 if (!tframe)
5445 trace_debug ("traceframe %d not found", tfnum);
5446 return 1;
5449 *buffer += "<traceframe-info>\n";
5450 traceframe_walk_blocks (tframe->data, tframe->data_size,
5451 tfnum, build_traceframe_info_xml, buffer);
5452 *buffer += "</traceframe-info>\n";
5453 return 0;
5456 /* Return the first fast tracepoint whose jump pad contains PC. */
5458 static struct tracepoint *
5459 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5461 struct tracepoint *tpoint;
5463 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5464 if (tpoint->type == fast_tracepoint)
5465 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5466 return tpoint;
5468 return NULL;
5471 /* Return the first fast tracepoint whose trampoline contains PC. */
5473 static struct tracepoint *
5474 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5476 struct tracepoint *tpoint;
5478 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5480 if (tpoint->type == fast_tracepoint
5481 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5482 return tpoint;
5485 return NULL;
5488 /* Return GDBserver's tracepoint that matches the IP Agent's
5489 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5490 address space. */
5492 static struct tracepoint *
5493 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5495 struct tracepoint *tpoint;
5497 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5498 if (tpoint->type == fast_tracepoint)
5499 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5500 return tpoint;
5502 return NULL;
5505 #endif
5507 /* The type of the object that is used to synchronize fast tracepoint
5508 collection. */
5510 typedef struct collecting_t
5512 /* The fast tracepoint number currently collecting. */
5513 uintptr_t tpoint;
5515 /* A number that GDBserver can use to identify the thread that is
5516 presently holding the collect lock. This need not (and usually
5517 is not) the thread id, as getting the current thread ID usually
5518 requires a system call, which we want to avoid like the plague.
5519 Usually this is thread's TCB, found in the TLS (pseudo-)
5520 register, which is readable with a single insn on several
5521 architectures. */
5522 uintptr_t thread_area;
5523 } collecting_t;
5525 #ifndef IN_PROCESS_AGENT
5527 void
5528 force_unlock_trace_buffer (void)
5530 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5533 /* Check if the thread identified by THREAD_AREA which is stopped at
5534 STOP_PC, is presently locking the fast tracepoint collection, and
5535 if so, gather some status of said collection. Returns 0 if the
5536 thread isn't collecting or in the jump pad at all. 1, if in the
5537 jump pad (or within gdb_collect) and hasn't executed the adjusted
5538 original insn yet (can set a breakpoint there and run to it). 2,
5539 if presently executing the adjusted original insn --- in which
5540 case, if we want to move the thread out of the jump pad, we need to
5541 single-step it until this function returns 0. */
5543 fast_tpoint_collect_result
5544 fast_tracepoint_collecting (CORE_ADDR thread_area,
5545 CORE_ADDR stop_pc,
5546 struct fast_tpoint_collect_status *status)
5548 CORE_ADDR ipa_collecting;
5549 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5550 CORE_ADDR ipa_gdb_trampoline_buffer;
5551 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5552 struct tracepoint *tpoint;
5553 int needs_breakpoint;
5555 /* The thread THREAD_AREA is either:
5557 0. not collecting at all, not within the jump pad, or within
5558 gdb_collect or one of its callees.
5560 1. in the jump pad and haven't reached gdb_collect
5562 2. within gdb_collect (out of the jump pad) (collect is set)
5564 3. we're in the jump pad, after gdb_collect having returned,
5565 possibly executing the adjusted insns.
5567 For cases 1 and 3, `collecting' may or not be set. The jump pad
5568 doesn't have any complicated jump logic, so we can tell if the
5569 thread is executing the adjust original insn or not by just
5570 matching STOP_PC with known jump pad addresses. If we it isn't
5571 yet executing the original insn, set a breakpoint there, and let
5572 the thread run to it, so to quickly step over a possible (many
5573 insns) gdb_collect call. Otherwise, or when the breakpoint is
5574 hit, only a few (small number of) insns are left to be executed
5575 in the jump pad. Single-step the thread until it leaves the
5576 jump pad. */
5578 again:
5579 tpoint = NULL;
5580 needs_breakpoint = 0;
5581 trace_debug ("fast_tracepoint_collecting");
5583 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5584 &ipa_gdb_jump_pad_buffer))
5586 internal_error ("error extracting `gdb_jump_pad_buffer'");
5588 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5589 &ipa_gdb_jump_pad_buffer_end))
5591 internal_error ("error extracting `gdb_jump_pad_buffer_end'");
5594 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5595 &ipa_gdb_trampoline_buffer))
5597 internal_error ("error extracting `gdb_trampoline_buffer'");
5599 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5600 &ipa_gdb_trampoline_buffer_end))
5602 internal_error ("error extracting `gdb_trampoline_buffer_end'");
5605 if (ipa_gdb_jump_pad_buffer <= stop_pc
5606 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5608 /* We can tell which tracepoint(s) the thread is collecting by
5609 matching the jump pad address back to the tracepoint. */
5610 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5611 if (tpoint == NULL)
5613 warning ("in jump pad, but no matching tpoint?");
5614 return fast_tpoint_collect_result::not_collecting;
5616 else
5618 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5619 "adj_insn(%s, %s)",
5620 tpoint->number, paddress (tpoint->address),
5621 paddress (tpoint->jump_pad),
5622 paddress (tpoint->jump_pad_end),
5623 paddress (tpoint->adjusted_insn_addr),
5624 paddress (tpoint->adjusted_insn_addr_end));
5627 /* Definitely in the jump pad. May or may not need
5628 fast-exit-jump-pad breakpoint. */
5629 if (tpoint->jump_pad <= stop_pc
5630 && stop_pc < tpoint->adjusted_insn_addr)
5631 needs_breakpoint = 1;
5633 else if (ipa_gdb_trampoline_buffer <= stop_pc
5634 && stop_pc < ipa_gdb_trampoline_buffer_end)
5636 /* We can tell which tracepoint(s) the thread is collecting by
5637 matching the trampoline address back to the tracepoint. */
5638 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5639 if (tpoint == NULL)
5641 warning ("in trampoline, but no matching tpoint?");
5642 return fast_tpoint_collect_result::not_collecting;
5644 else
5646 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5647 tpoint->number, paddress (tpoint->address),
5648 paddress (tpoint->trampoline),
5649 paddress (tpoint->trampoline_end));
5652 /* Have not reached jump pad yet, but treat the trampoline as a
5653 part of the jump pad that is before the adjusted original
5654 instruction. */
5655 needs_breakpoint = 1;
5657 else
5659 collecting_t ipa_collecting_obj;
5661 /* If `collecting' is set/locked, then the THREAD_AREA thread
5662 may or not be the one holding the lock. We have to read the
5663 lock to find out. */
5665 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5666 &ipa_collecting))
5668 trace_debug ("fast_tracepoint_collecting:"
5669 " failed reading 'collecting' in the inferior");
5670 return fast_tpoint_collect_result::not_collecting;
5673 if (!ipa_collecting)
5675 trace_debug ("fast_tracepoint_collecting: not collecting"
5676 " (and nobody is).");
5677 return fast_tpoint_collect_result::not_collecting;
5680 /* Some thread is collecting. Check which. */
5681 if (read_inferior_memory (ipa_collecting,
5682 (unsigned char *) &ipa_collecting_obj,
5683 sizeof (ipa_collecting_obj)) != 0)
5684 goto again;
5686 if (ipa_collecting_obj.thread_area != thread_area)
5688 trace_debug ("fast_tracepoint_collecting: not collecting "
5689 "(another thread is)");
5690 return fast_tpoint_collect_result::not_collecting;
5693 tpoint
5694 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5695 if (tpoint == NULL)
5697 warning ("fast_tracepoint_collecting: collecting, "
5698 "but tpoint %s not found?",
5699 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5700 return fast_tpoint_collect_result::not_collecting;
5703 /* The thread is within `gdb_collect', skip over the rest of
5704 fast tracepoint collection quickly using a breakpoint. */
5705 needs_breakpoint = 1;
5708 /* The caller wants a bit of status detail. */
5709 if (status != NULL)
5711 status->tpoint_num = tpoint->number;
5712 status->tpoint_addr = tpoint->address;
5713 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5714 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5717 if (needs_breakpoint)
5719 /* Hasn't executed the original instruction yet. Set breakpoint
5720 there, and wait till it's hit, then single-step until exiting
5721 the jump pad. */
5723 trace_debug ("\
5724 fast_tracepoint_collecting, returning continue-until-break at %s",
5725 paddress (tpoint->adjusted_insn_addr));
5727 return fast_tpoint_collect_result::before_insn; /* continue */
5729 else
5731 /* Just single-step until exiting the jump pad. */
5733 trace_debug ("fast_tracepoint_collecting, returning "
5734 "need-single-step (%s-%s)",
5735 paddress (tpoint->adjusted_insn_addr),
5736 paddress (tpoint->adjusted_insn_addr_end));
5738 return fast_tpoint_collect_result::at_insn; /* single-step */
5742 #endif
5744 #ifdef IN_PROCESS_AGENT
5746 /* The global fast tracepoint collect lock. Points to a collecting_t
5747 object built on the stack by the jump pad, if presently locked;
5748 NULL if it isn't locked. Note that this lock *must* be set while
5749 executing any *function other than the jump pad. See
5750 fast_tracepoint_collecting. */
5751 extern "C" {
5752 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5755 /* This is needed for -Wmissing-declarations. */
5756 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5757 unsigned char *regs);
5759 /* This routine, called from the jump pad (in asm) is designed to be
5760 called from the jump pads of fast tracepoints, thus it is on the
5761 critical path. */
5763 IP_AGENT_EXPORT_FUNC void
5764 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5766 struct fast_tracepoint_ctx ctx;
5767 const struct target_desc *ipa_tdesc;
5769 /* Don't do anything until the trace run is completely set up. */
5770 if (!tracing)
5771 return;
5773 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5774 ctx.base.type = fast_tracepoint;
5775 ctx.regs = regs;
5776 ctx.regcache_initted = 0;
5777 /* Wrap the regblock in a register cache (in the stack, we don't
5778 want to malloc here). */
5779 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5780 if (ctx.regspace == NULL)
5782 trace_debug ("Trace buffer block allocation failed, skipping");
5783 return;
5786 for (ctx.tpoint = tpoint;
5787 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5788 ctx.tpoint = ctx.tpoint->next)
5790 if (!ctx.tpoint->enabled)
5791 continue;
5793 /* Multiple tracepoints of different types, such as fast tracepoint and
5794 static tracepoint, can be set at the same address. */
5795 if (ctx.tpoint->type != tpoint->type)
5796 continue;
5798 /* Test the condition if present, and collect if true. */
5799 if (ctx.tpoint->cond == NULL
5800 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5801 ctx.tpoint))
5803 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
5804 ctx.tpoint->address, ctx.tpoint);
5806 /* Note that this will cause original insns to be written back
5807 to where we jumped from, but that's OK because we're jumping
5808 back to the next whole instruction. This will go badly if
5809 instruction restoration is not atomic though. */
5810 if (stopping_tracepoint
5811 || trace_buffer_is_full
5812 || expr_eval_result != expr_eval_no_error)
5814 stop_tracing ();
5815 break;
5818 else
5820 /* If there was a condition and it evaluated to false, the only
5821 way we would stop tracing is if there was an error during
5822 condition expression evaluation. */
5823 if (expr_eval_result != expr_eval_no_error)
5825 stop_tracing ();
5826 break;
5832 /* These global variables points to the corresponding functions. This is
5833 necessary on powerpc64, where asking for function symbol address from gdb
5834 results in returning the actual code pointer, instead of the descriptor
5835 pointer. */
5837 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5838 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5839 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5840 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5842 extern "C" {
5843 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5844 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5845 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5846 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5847 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5848 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5851 #endif
5853 #ifndef IN_PROCESS_AGENT
5855 CORE_ADDR
5856 get_raw_reg_func_addr (void)
5858 CORE_ADDR res;
5859 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5861 error ("error extracting get_raw_reg_ptr");
5862 return 0;
5864 return res;
5867 CORE_ADDR
5868 get_get_tsv_func_addr (void)
5870 CORE_ADDR res;
5871 if (read_inferior_data_pointer (
5872 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5874 error ("error extracting get_trace_state_variable_value_ptr");
5875 return 0;
5877 return res;
5880 CORE_ADDR
5881 get_set_tsv_func_addr (void)
5883 CORE_ADDR res;
5884 if (read_inferior_data_pointer (
5885 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5887 error ("error extracting set_trace_state_variable_value_ptr");
5888 return 0;
5890 return res;
5893 static void
5894 compile_tracepoint_condition (struct tracepoint *tpoint,
5895 CORE_ADDR *jump_entry)
5897 CORE_ADDR entry_point = *jump_entry;
5898 enum eval_result_type err;
5900 trace_debug ("Starting condition compilation for tracepoint %d\n",
5901 tpoint->number);
5903 /* Initialize the global pointer to the code being built. */
5904 current_insn_ptr = *jump_entry;
5906 emit_prologue ();
5908 err = compile_bytecodes (tpoint->cond);
5910 if (err == expr_eval_no_error)
5912 emit_epilogue ();
5914 /* Record the beginning of the compiled code. */
5915 tpoint->compiled_cond = entry_point;
5917 trace_debug ("Condition compilation for tracepoint %d complete\n",
5918 tpoint->number);
5920 else
5922 /* Leave the unfinished code in situ, but don't point to it. */
5924 tpoint->compiled_cond = 0;
5926 trace_debug ("Condition compilation for tracepoint %d failed, "
5927 "error code %d",
5928 tpoint->number, err);
5931 /* Update the code pointer passed in. Note that we do this even if
5932 the compile fails, so that we can look at the partial results
5933 instead of letting them be overwritten. */
5934 *jump_entry = current_insn_ptr;
5936 /* Leave a gap, to aid dump decipherment. */
5937 *jump_entry += 16;
5940 /* The base pointer of the IPA's heap. This is the only memory the
5941 IPA is allowed to use. The IPA should _not_ call the inferior's
5942 `malloc' during operation. That'd be slow, and, most importantly,
5943 it may not be safe. We may be collecting a tracepoint in a signal
5944 handler, for example. */
5945 static CORE_ADDR target_tp_heap;
5947 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5948 to 8 bytes. */
5950 static CORE_ADDR
5951 target_malloc (ULONGEST size)
5953 CORE_ADDR ptr;
5955 if (target_tp_heap == 0)
5957 /* We have the pointer *address*, need what it points to. */
5958 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5959 &target_tp_heap))
5961 internal_error ("couldn't get target heap head pointer");
5965 ptr = target_tp_heap;
5966 target_tp_heap += size;
5968 /* Pad to 8-byte alignment. */
5969 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5971 return ptr;
5974 static CORE_ADDR
5975 download_agent_expr (struct agent_expr *expr)
5977 CORE_ADDR expr_addr;
5978 CORE_ADDR expr_bytes;
5980 expr_addr = target_malloc (sizeof (*expr));
5981 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5983 expr_bytes = target_malloc (expr->length);
5984 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
5985 expr_bytes);
5986 target_write_memory (expr_bytes, expr->bytes, expr->length);
5988 return expr_addr;
5991 /* Align V up to N bits. */
5992 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5994 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
5996 static void
5997 download_tracepoint_1 (struct tracepoint *tpoint)
5999 struct tracepoint target_tracepoint;
6000 CORE_ADDR tpptr = 0;
6002 gdb_assert (tpoint->type == fast_tracepoint
6003 || tpoint->type == static_tracepoint);
6005 if (tpoint->cond != NULL && target_emit_ops () != NULL)
6007 CORE_ADDR jentry, jump_entry;
6009 jentry = jump_entry = get_jump_space_head ();
6011 if (tpoint->cond != NULL)
6013 /* Pad to 8-byte alignment. (needed?) */
6014 /* Actually this should be left for the target to
6015 decide. */
6016 jentry = UALIGN (jentry, 8);
6018 compile_tracepoint_condition (tpoint, &jentry);
6021 /* Pad to 8-byte alignment. */
6022 jentry = UALIGN (jentry, 8);
6023 claim_jump_space (jentry - jump_entry);
6026 target_tracepoint = *tpoint;
6028 tpptr = target_malloc (sizeof (*tpoint));
6029 tpoint->obj_addr_on_target = tpptr;
6031 /* Write the whole object. We'll fix up its pointers in a bit.
6032 Assume no next for now. This is fixed up above on the next
6033 iteration, if there's any. */
6034 target_tracepoint.next = NULL;
6035 /* Need to clear this here too, since we're downloading the
6036 tracepoints before clearing our own copy. */
6037 target_tracepoint.hit_count = 0;
6039 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
6040 sizeof (target_tracepoint));
6042 if (tpoint->cond)
6043 write_inferior_data_pointer (tpptr
6044 + offsetof (struct tracepoint, cond),
6045 download_agent_expr (tpoint->cond));
6047 if (tpoint->numactions)
6049 int i;
6050 CORE_ADDR actions_array;
6052 /* The pointers array. */
6053 actions_array
6054 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
6055 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
6056 actions),
6057 actions_array);
6059 /* Now for each pointer, download the action. */
6060 for (i = 0; i < tpoint->numactions; i++)
6062 struct tracepoint_action *action = tpoint->actions[i];
6063 CORE_ADDR ipa_action = tracepoint_action_download (action);
6065 if (ipa_action != 0)
6066 write_inferior_data_pointer (actions_array
6067 + i * sizeof (*tpoint->actions),
6068 ipa_action);
6073 #define IPA_PROTO_FAST_TRACE_FLAG 0
6074 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
6075 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
6076 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
6077 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
6079 /* Send a command to agent to download and install tracepoint TPOINT. */
6081 static int
6082 tracepoint_send_agent (struct tracepoint *tpoint)
6084 char buf[IPA_CMD_BUF_SIZE];
6085 char *p;
6086 int i, ret;
6088 p = buf;
6089 strcpy (p, "FastTrace:");
6090 p += 10;
6092 COPY_FIELD_TO_BUF (p, tpoint, number);
6093 COPY_FIELD_TO_BUF (p, tpoint, address);
6094 COPY_FIELD_TO_BUF (p, tpoint, type);
6095 COPY_FIELD_TO_BUF (p, tpoint, enabled);
6096 COPY_FIELD_TO_BUF (p, tpoint, step_count);
6097 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
6098 COPY_FIELD_TO_BUF (p, tpoint, numactions);
6099 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
6100 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
6101 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
6102 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
6104 /* condition */
6105 p = agent_expr_send (p, tpoint->cond);
6107 /* tracepoint_action */
6108 for (i = 0; i < tpoint->numactions; i++)
6110 struct tracepoint_action *action = tpoint->actions[i];
6112 p[0] = action->type;
6113 p = tracepoint_action_send (&p[1], action);
6116 get_jump_space_head ();
6117 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
6118 agent can use jump pad from it. */
6119 if (tpoint->type == fast_tracepoint)
6121 memcpy (p, &gdb_jump_pad_head, 8);
6122 p += 8;
6125 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
6126 if (ret)
6127 return ret;
6129 if (!startswith (buf, "OK"))
6130 return 1;
6132 /* The value of tracepoint's target address is stored in BUF. */
6133 memcpy (&tpoint->obj_addr_on_target,
6134 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
6136 if (tpoint->type == fast_tracepoint)
6138 unsigned char *insn
6139 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
6140 int fjump_size;
6142 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
6143 (unsigned int) tpoint->obj_addr_on_target,
6144 (unsigned int) gdb_jump_pad_head);
6146 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
6148 /* This has been done in agent. We should also set up record for it. */
6149 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
6150 /* Wire it in. */
6151 tpoint->handle
6152 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
6155 return 0;
6158 static void
6159 download_tracepoint (struct tracepoint *tpoint)
6161 struct tracepoint *tp, *tp_prev;
6163 if (tpoint->type != fast_tracepoint
6164 && tpoint->type != static_tracepoint)
6165 return;
6167 download_tracepoint_1 (tpoint);
6169 /* Find the previous entry of TPOINT, which is fast tracepoint or
6170 static tracepoint. */
6171 tp_prev = NULL;
6172 for (tp = tracepoints; tp != tpoint; tp = tp->next)
6174 if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
6175 tp_prev = tp;
6178 if (tp_prev)
6180 CORE_ADDR tp_prev_target_next_addr;
6182 /* Insert TPOINT after TP_PREV in IPA. */
6183 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
6184 + offsetof (struct tracepoint, next),
6185 &tp_prev_target_next_addr))
6187 internal_error ("error reading `tp_prev->next'");
6190 /* tpoint->next = tp_prev->next */
6191 write_inferior_data_pointer (tpoint->obj_addr_on_target
6192 + offsetof (struct tracepoint, next),
6193 tp_prev_target_next_addr);
6194 /* tp_prev->next = tpoint */
6195 write_inferior_data_pointer (tp_prev->obj_addr_on_target
6196 + offsetof (struct tracepoint, next),
6197 tpoint->obj_addr_on_target);
6199 else
6200 /* First object in list, set the head pointer in the
6201 inferior. */
6202 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
6203 tpoint->obj_addr_on_target);
6207 static void
6208 download_trace_state_variables (void)
6210 CORE_ADDR ptr = 0, prev_ptr = 0;
6211 struct trace_state_variable *tsv;
6213 /* Start out empty. */
6214 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
6216 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
6218 struct trace_state_variable target_tsv;
6220 /* TSV's with a getter have been initialized equally in both the
6221 inferior and GDBserver. Skip them. */
6222 if (tsv->getter != NULL)
6223 continue;
6225 target_tsv = *tsv;
6227 prev_ptr = ptr;
6228 ptr = target_malloc (sizeof (*tsv));
6230 if (tsv == trace_state_variables)
6232 /* First object in list, set the head pointer in the
6233 inferior. */
6235 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
6236 ptr);
6238 else
6240 write_inferior_data_pointer (prev_ptr
6241 + offsetof (struct trace_state_variable,
6242 next),
6243 ptr);
6246 /* Write the whole object. We'll fix up its pointers in a bit.
6247 Assume no next, fixup when needed. */
6248 target_tsv.next = NULL;
6250 target_write_memory (ptr, (unsigned char *) &target_tsv,
6251 sizeof (target_tsv));
6253 if (tsv->name != NULL)
6255 size_t size = strlen (tsv->name) + 1;
6256 CORE_ADDR name_addr = target_malloc (size);
6257 target_write_memory (name_addr,
6258 (unsigned char *) tsv->name, size);
6259 write_inferior_data_pointer (ptr
6260 + offsetof (struct trace_state_variable,
6261 name),
6262 name_addr);
6265 gdb_assert (tsv->getter == NULL);
6268 if (prev_ptr != 0)
6270 /* Fixup the next pointer in the last item in the list. */
6271 write_inferior_data_pointer (prev_ptr
6272 + offsetof (struct trace_state_variable,
6273 next), 0);
6277 /* Upload complete trace frames out of the IP Agent's trace buffer
6278 into GDBserver's trace buffer. This always uploads either all or
6279 no trace frames. This is the counter part of
6280 `trace_alloc_trace_buffer'. See its description of the atomic
6281 syncing mechanism. */
6283 static void
6284 upload_fast_traceframes (void)
6286 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
6287 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
6288 CORE_ADDR tf;
6289 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
6290 unsigned int curr_tbctrl_idx;
6291 unsigned int ipa_trace_buffer_ctrl_curr;
6292 unsigned int ipa_trace_buffer_ctrl_curr_old;
6293 CORE_ADDR ipa_trace_buffer_ctrl_addr;
6294 struct breakpoint *about_to_request_buffer_space_bkpt;
6295 CORE_ADDR ipa_trace_buffer_lo;
6296 CORE_ADDR ipa_trace_buffer_hi;
6298 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6299 &ipa_traceframe_read_count_racy))
6301 /* This will happen in most targets if the current thread is
6302 running. */
6303 return;
6306 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6307 &ipa_traceframe_write_count_racy))
6308 return;
6310 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
6311 ipa_traceframe_write_count_racy
6312 - ipa_traceframe_read_count_racy,
6313 ipa_traceframe_write_count_racy,
6314 ipa_traceframe_read_count_racy);
6316 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
6317 return;
6319 about_to_request_buffer_space_bkpt
6320 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
6321 NULL);
6323 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6324 &ipa_trace_buffer_ctrl_curr))
6325 return;
6327 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
6329 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
6332 unsigned int prev, counter;
6334 /* Update the token, with new counters, and the GDBserver stamp
6335 bit. Always reuse the current TBC index. */
6336 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6337 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
6339 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
6340 | (prev << 12)
6341 | counter
6342 | curr_tbctrl_idx);
6345 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
6346 ipa_trace_buffer_ctrl_curr))
6347 return;
6349 trace_debug ("Lib: Committed %08x -> %08x",
6350 ipa_trace_buffer_ctrl_curr_old,
6351 ipa_trace_buffer_ctrl_curr);
6353 /* Re-read these, now that we've installed the
6354 `about_to_request_buffer_space' breakpoint/lock. A thread could
6355 have finished a traceframe between the last read of these
6356 counters and setting the breakpoint above. If we start
6357 uploading, we never want to leave this function with
6358 traceframe_read_count != 0, otherwise, GDBserver could end up
6359 incrementing the counter tokens more than once (due to event loop
6360 nesting), which would break the IP agent's "effective" detection
6361 (see trace_alloc_trace_buffer). */
6362 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
6363 &ipa_traceframe_read_count))
6364 return;
6365 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
6366 &ipa_traceframe_write_count))
6367 return;
6369 if (debug_threads)
6371 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
6372 ipa_traceframe_write_count - ipa_traceframe_read_count,
6373 ipa_traceframe_write_count, ipa_traceframe_read_count);
6375 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
6376 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
6377 trace_debug ("note that ipa_traceframe_count's parts changed");
6380 /* Get the address of the current TBC object (the IP agent has an
6381 array of 3 such objects). The index is stored in the TBC
6382 token. */
6383 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
6384 ipa_trace_buffer_ctrl_addr
6385 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
6387 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
6388 (unsigned char *) &ipa_trace_buffer_ctrl,
6389 sizeof (struct ipa_trace_buffer_control)))
6390 return;
6392 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
6393 &ipa_trace_buffer_lo))
6394 return;
6395 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
6396 &ipa_trace_buffer_hi))
6397 return;
6399 /* Offsets are easier to grok for debugging than raw addresses,
6400 especially for the small trace buffer sizes that are useful for
6401 testing. */
6402 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
6403 "endfree=%d wrap=%d hi=%d",
6404 curr_tbctrl_idx,
6405 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6406 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6407 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
6408 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6409 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6411 /* Note that the IPA's buffer is always circular. */
6413 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
6415 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6416 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6418 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6419 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6420 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6421 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6422 : 0))
6424 tf = IPA_FIRST_TRACEFRAME ();
6426 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6428 struct tracepoint *tpoint;
6429 struct traceframe *tframe;
6430 unsigned char *block;
6431 struct traceframe ipa_tframe;
6433 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6434 offsetof (struct traceframe, data)))
6435 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6437 if (ipa_tframe.tpnum == 0)
6439 internal_error ("Uploading: No (more) fast traceframes, but"
6440 " ipa_traceframe_count == %u??\n",
6441 ipa_traceframe_write_count
6442 - ipa_traceframe_read_count);
6445 /* Note that this will be incorrect for multi-location
6446 tracepoints... */
6447 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6449 tframe = add_traceframe (tpoint);
6450 if (tframe == NULL)
6452 trace_buffer_is_full = 1;
6453 trace_debug ("Uploading: trace buffer is full");
6455 else
6457 /* Copy the whole set of blocks in one go for now. FIXME:
6458 split this in smaller blocks. */
6459 block = add_traceframe_block (tframe, tpoint,
6460 ipa_tframe.data_size);
6461 if (block != NULL)
6463 if (read_inferior_memory (tf
6464 + offsetof (struct traceframe, data),
6465 block, ipa_tframe.data_size))
6466 error ("Uploading: Couldn't read traceframe data at %s\n",
6467 paddress (tf + offsetof (struct traceframe, data)));
6470 trace_debug ("Uploading: traceframe didn't fit");
6471 finish_traceframe (tframe);
6474 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6476 /* If we freed the traceframe that wrapped around, go back
6477 to the non-wrap case. */
6478 if (tf < ipa_trace_buffer_ctrl.start)
6480 trace_debug ("Lib: Discarding past the wraparound");
6481 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6483 ipa_trace_buffer_ctrl.start = tf;
6484 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6485 ++ipa_traceframe_read_count;
6487 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6488 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6490 trace_debug ("Lib: buffer is fully empty. "
6491 "Trace buffer [%d] start=%d free=%d endfree=%d",
6492 curr_tbctrl_idx,
6493 (int) (ipa_trace_buffer_ctrl.start
6494 - ipa_trace_buffer_lo),
6495 (int) (ipa_trace_buffer_ctrl.free
6496 - ipa_trace_buffer_lo),
6497 (int) (ipa_trace_buffer_ctrl.end_free
6498 - ipa_trace_buffer_lo));
6500 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6501 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6502 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6503 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6506 trace_debug ("Uploaded a traceframe\n"
6507 "Lib: Trace buffer [%d] start=%d free=%d "
6508 "endfree=%d wrap=%d hi=%d",
6509 curr_tbctrl_idx,
6510 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6511 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6512 (int) (ipa_trace_buffer_ctrl.end_free
6513 - ipa_trace_buffer_lo),
6514 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6515 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6518 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6519 (unsigned char *) &ipa_trace_buffer_ctrl,
6520 sizeof (struct ipa_trace_buffer_control)))
6521 return;
6523 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6524 ipa_traceframe_read_count);
6526 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6528 target_pause_all (true);
6530 delete_breakpoint (about_to_request_buffer_space_bkpt);
6531 about_to_request_buffer_space_bkpt = NULL;
6533 target_unpause_all (true);
6535 if (trace_buffer_is_full)
6536 stop_tracing ();
6538 #endif
6540 #ifdef IN_PROCESS_AGENT
6542 IP_AGENT_EXPORT_VAR int ust_loaded;
6543 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6545 #ifdef HAVE_UST
6547 /* Static tracepoints. */
6549 /* UST puts a "struct tracepoint" in the global namespace, which
6550 conflicts with our tracepoint. Arguably, being a library, it
6551 shouldn't take ownership of such a generic name. We work around it
6552 here. */
6553 #define tracepoint ust_tracepoint
6554 #include <ust/ust.h>
6555 #undef tracepoint
6557 extern int serialize_to_text (char *outbuf, int bufsize,
6558 const char *fmt, va_list ap);
6560 #define GDB_PROBE_NAME "gdb"
6562 /* We dynamically search for the UST symbols instead of linking them
6563 in. This lets the user decide if the application uses static
6564 tracepoints, instead of always pulling libust.so in. This vector
6565 holds pointers to all functions we care about. */
6567 static struct
6569 int (*serialize_to_text) (char *outbuf, int bufsize,
6570 const char *fmt, va_list ap);
6572 int (*ltt_probe_register) (struct ltt_available_probe *pdata);
6573 int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
6575 int (*ltt_marker_connect) (const char *channel, const char *mname,
6576 const char *pname);
6577 int (*ltt_marker_disconnect) (const char *channel, const char *mname,
6578 const char *pname);
6580 void (*marker_iter_start) (struct marker_iter *iter);
6581 void (*marker_iter_next) (struct marker_iter *iter);
6582 void (*marker_iter_stop) (struct marker_iter *iter);
6583 void (*marker_iter_reset) (struct marker_iter *iter);
6584 } ust_ops;
6586 #include <dlfcn.h>
6588 /* Cast through typeof to catch incompatible API changes. Since UST
6589 only builds with gcc, we can freely use gcc extensions here
6590 too. */
6591 #define GET_UST_SYM(SYM) \
6592 do \
6594 if (ust_ops.SYM == NULL) \
6595 ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM); \
6596 if (ust_ops.SYM == NULL) \
6597 return 0; \
6598 } while (0)
6600 #define USTF(SYM) ust_ops.SYM
6602 /* Get pointers to all libust.so functions we care about. */
6604 static int
6605 dlsym_ust (void)
6607 GET_UST_SYM (serialize_to_text);
6609 GET_UST_SYM (ltt_probe_register);
6610 GET_UST_SYM (ltt_probe_unregister);
6611 GET_UST_SYM (ltt_marker_connect);
6612 GET_UST_SYM (ltt_marker_disconnect);
6614 GET_UST_SYM (marker_iter_start);
6615 GET_UST_SYM (marker_iter_next);
6616 GET_UST_SYM (marker_iter_stop);
6617 GET_UST_SYM (marker_iter_reset);
6619 ust_loaded = 1;
6620 return 1;
6623 /* Given an UST marker, return the matching gdb static tracepoint.
6624 The match is done by address. */
6626 static struct tracepoint *
6627 ust_marker_to_static_tracepoint (const struct marker *mdata)
6629 struct tracepoint *tpoint;
6631 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
6633 if (tpoint->type != static_tracepoint)
6634 continue;
6636 if (tpoint->address == (uintptr_t) mdata->location)
6637 return tpoint;
6640 return NULL;
6643 /* The probe function we install on lttng/ust markers. Whenever a
6644 probed ust marker is hit, this function is called. This is similar
6645 to gdb_collect, only for static tracepoints, instead of fast
6646 tracepoints. */
6648 static void
6649 gdb_probe (const struct marker *mdata, void *probe_private,
6650 struct registers *regs, void *call_private,
6651 const char *fmt, va_list *args)
6653 struct tracepoint *tpoint;
6654 struct static_tracepoint_ctx ctx;
6655 const struct target_desc *ipa_tdesc;
6657 /* Don't do anything until the trace run is completely set up. */
6658 if (!tracing)
6660 trace_debug ("gdb_probe: not tracing\n");
6661 return;
6664 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
6665 ctx.base.type = static_tracepoint;
6666 ctx.regcache_initted = 0;
6667 ctx.regs = regs;
6668 ctx.fmt = fmt;
6669 ctx.args = args;
6671 /* Wrap the regblock in a register cache (in the stack, we don't
6672 want to malloc here). */
6673 ctx.regspace = alloca (ipa_tdesc->registers_size);
6674 if (ctx.regspace == NULL)
6676 trace_debug ("Trace buffer block allocation failed, skipping");
6677 return;
6680 tpoint = ust_marker_to_static_tracepoint (mdata);
6681 if (tpoint == NULL)
6683 trace_debug ("gdb_probe: marker not known: "
6684 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6685 mdata->location, mdata->channel,
6686 mdata->name, mdata->format);
6687 return;
6690 if (!tpoint->enabled)
6692 trace_debug ("gdb_probe: tracepoint disabled");
6693 return;
6696 ctx.tpoint = tpoint;
6698 trace_debug ("gdb_probe: collecting marker: "
6699 "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
6700 mdata->location, mdata->channel,
6701 mdata->name, mdata->format);
6703 /* Test the condition if present, and collect if true. */
6704 if (tpoint->cond == NULL
6705 || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6706 tpoint))
6708 collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
6709 tpoint->address, tpoint);
6711 if (stopping_tracepoint
6712 || trace_buffer_is_full
6713 || expr_eval_result != expr_eval_no_error)
6714 stop_tracing ();
6716 else
6718 /* If there was a condition and it evaluated to false, the only
6719 way we would stop tracing is if there was an error during
6720 condition expression evaluation. */
6721 if (expr_eval_result != expr_eval_no_error)
6722 stop_tracing ();
6726 /* Called if the gdb static tracepoint requested collecting "$_sdata",
6727 static tracepoint string data. This is a string passed to the
6728 tracing library by the user, at the time of the tracepoint marker
6729 call. E.g., in the UST marker call:
6731 trace_mark (ust, bar33, "str %s", "FOOBAZ");
6733 the collected data is "str FOOBAZ".
6736 static void
6737 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
6738 struct traceframe *tframe)
6740 struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
6741 unsigned char *bufspace;
6742 int size;
6743 va_list copy;
6744 unsigned short blocklen;
6746 if (umd == NULL)
6748 trace_debug ("Wanted to collect static trace data, "
6749 "but there's no static trace data");
6750 return;
6753 va_copy (copy, *umd->args);
6754 size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
6755 va_end (copy);
6757 trace_debug ("Want to collect ust data");
6759 /* 'S' + size + string */
6760 bufspace = add_traceframe_block (tframe, umd->tpoint,
6761 1 + sizeof (blocklen) + size + 1);
6762 if (bufspace == NULL)
6764 trace_debug ("Trace buffer block allocation failed, skipping");
6765 return;
6768 /* Identify a static trace data block. */
6769 *bufspace = 'S';
6771 blocklen = size + 1;
6772 memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
6774 va_copy (copy, *umd->args);
6775 USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
6776 size + 1, umd->fmt, copy);
6777 va_end (copy);
6779 trace_debug ("Storing static tracepoint data in regblock: %s",
6780 bufspace + 1 + sizeof (blocklen));
6783 /* The probe to register with lttng/ust. */
6784 static struct ltt_available_probe gdb_ust_probe =
6786 GDB_PROBE_NAME,
6787 NULL,
6788 gdb_probe,
6791 #endif /* HAVE_UST */
6792 #endif /* IN_PROCESS_AGENT */
6794 #ifndef IN_PROCESS_AGENT
6796 /* Ask the in-process agent to run a command. Since we don't want to
6797 have to handle the IPA hitting breakpoints while running the
6798 command, we pause all threads, remove all breakpoints, and then set
6799 the helper thread re-running. We communicate with the helper
6800 thread by means of direct memory xfering, and a socket for
6801 synchronization. */
6803 static int
6804 run_inferior_command (char *cmd, int len)
6806 int err = -1;
6807 int pid = current_thread->id.pid ();
6809 trace_debug ("run_inferior_command: running: %s", cmd);
6811 target_pause_all (false);
6812 uninsert_all_breakpoints ();
6814 err = agent_run_command (pid, cmd, len);
6816 reinsert_all_breakpoints ();
6817 target_unpause_all (false);
6819 return err;
6822 #else /* !IN_PROCESS_AGENT */
6824 #include <sys/socket.h>
6825 #include <sys/un.h>
6827 #ifndef UNIX_PATH_MAX
6828 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6829 #endif
6831 /* Where we put the socked used for synchronization. */
6832 #define SOCK_DIR P_tmpdir
6834 /* Thread ID of the helper thread. GDBserver reads this to know which
6835 is the help thread. This is an LWP id on Linux. */
6836 extern "C" {
6837 IP_AGENT_EXPORT_VAR int helper_thread_id;
6840 static int
6841 init_named_socket (const char *name)
6843 int result, fd;
6844 struct sockaddr_un addr;
6846 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6847 if (result == -1)
6849 warning ("socket creation failed: %s", safe_strerror (errno));
6850 return -1;
6853 addr.sun_family = AF_UNIX;
6855 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6857 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6858 return -1;
6861 strcpy (addr.sun_path, name);
6863 result = access (name, F_OK);
6864 if (result == 0)
6866 /* File exists. */
6867 result = unlink (name);
6868 if (result == -1)
6870 warning ("unlink failed: %s", safe_strerror (errno));
6871 close (fd);
6872 return -1;
6874 warning ("socket %s already exists; overwriting", name);
6877 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6878 if (result == -1)
6880 warning ("bind failed: %s", safe_strerror (errno));
6881 close (fd);
6882 return -1;
6885 result = listen (fd, 1);
6886 if (result == -1)
6888 warning ("listen: %s", safe_strerror (errno));
6889 close (fd);
6890 return -1;
6893 return fd;
6896 static char agent_socket_name[UNIX_PATH_MAX];
6898 static int
6899 gdb_agent_socket_init (void)
6901 int result, fd;
6903 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6904 SOCK_DIR, getpid ());
6905 if (result >= UNIX_PATH_MAX)
6907 trace_debug ("string overflow allocating socket name");
6908 return -1;
6911 fd = init_named_socket (agent_socket_name);
6912 if (fd < 0)
6913 warning ("Error initializing named socket (%s) for communication with the "
6914 "ust helper thread. Check that directory exists and that it "
6915 "is writable.", agent_socket_name);
6917 return fd;
6920 #ifdef HAVE_UST
6922 /* The next marker to be returned on a qTsSTM command. */
6923 static const struct marker *next_st;
6925 /* Returns the first known marker. */
6927 struct marker *
6928 first_marker (void)
6930 struct marker_iter iter;
6932 USTF(marker_iter_reset) (&iter);
6933 USTF(marker_iter_start) (&iter);
6935 return iter.marker;
6938 /* Returns the marker following M. */
6940 const struct marker *
6941 next_marker (const struct marker *m)
6943 struct marker_iter iter;
6945 USTF(marker_iter_reset) (&iter);
6946 USTF(marker_iter_start) (&iter);
6948 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
6950 if (iter.marker == m)
6952 USTF(marker_iter_next) (&iter);
6953 return iter.marker;
6957 return NULL;
6960 /* Return an hexstr version of the STR C string, fit for sending to
6961 GDB. */
6963 static char *
6964 cstr_to_hexstr (const char *str)
6966 int len = strlen (str);
6967 char *hexstr = xmalloc (len * 2 + 1);
6968 bin2hex ((gdb_byte *) str, hexstr, len);
6969 return hexstr;
6972 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
6973 packets. */
6975 static void
6976 response_ust_marker (char *packet, const struct marker *st)
6978 char *strid, *format, *tmp;
6980 next_st = next_marker (st);
6982 tmp = xmalloc (strlen (st->channel) + 1 +
6983 strlen (st->name) + 1);
6984 sprintf (tmp, "%s/%s", st->channel, st->name);
6986 strid = cstr_to_hexstr (tmp);
6987 free (tmp);
6989 format = cstr_to_hexstr (st->format);
6991 sprintf (packet, "m%s:%s:%s",
6992 paddress ((uintptr_t) st->location),
6993 strid,
6994 format);
6996 free (strid);
6997 free (format);
7000 /* Return the first static tracepoint, and initialize the state
7001 machine that will iterate through all the static tracepoints. */
7003 static void
7004 cmd_qtfstm (char *packet)
7006 trace_debug ("Returning first trace state variable definition");
7008 if (first_marker ())
7009 response_ust_marker (packet, first_marker ());
7010 else
7011 strcpy (packet, "l");
7014 /* Return additional trace state variable definitions. */
7016 static void
7017 cmd_qtsstm (char *packet)
7019 trace_debug ("Returning static tracepoint");
7021 if (next_st)
7022 response_ust_marker (packet, next_st);
7023 else
7024 strcpy (packet, "l");
7027 /* Disconnect the GDB probe from a marker at a given address. */
7029 static void
7030 unprobe_marker_at (char *packet)
7032 char *p = packet;
7033 ULONGEST address;
7034 struct marker_iter iter;
7036 p += sizeof ("unprobe_marker_at:") - 1;
7038 p = unpack_varlen_hex (p, &address);
7040 USTF(marker_iter_reset) (&iter);
7041 USTF(marker_iter_start) (&iter);
7042 for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
7043 if ((uintptr_t ) iter.marker->location == address)
7045 int result;
7047 result = USTF(ltt_marker_disconnect) (iter.marker->channel,
7048 iter.marker->name,
7049 GDB_PROBE_NAME);
7050 if (result < 0)
7051 warning ("could not disable marker %s/%s",
7052 iter.marker->channel, iter.marker->name);
7053 break;
7057 /* Connect the GDB probe to a marker at a given address. */
7059 static int
7060 probe_marker_at (char *packet)
7062 char *p = packet;
7063 ULONGEST address;
7064 struct marker_iter iter;
7065 struct marker *m;
7067 p += sizeof ("probe_marker_at:") - 1;
7069 p = unpack_varlen_hex (p, &address);
7071 USTF(marker_iter_reset) (&iter);
7073 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7074 m != NULL;
7075 USTF(marker_iter_next) (&iter), m = iter.marker)
7076 if ((uintptr_t ) m->location == address)
7078 int result;
7080 trace_debug ("found marker for address. "
7081 "ltt_marker_connect (marker = %s/%s)",
7082 m->channel, m->name);
7084 result = USTF(ltt_marker_connect) (m->channel, m->name,
7085 GDB_PROBE_NAME);
7086 if (result && result != -EEXIST)
7087 trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
7088 m->channel, m->name, -result);
7090 if (result < 0)
7092 sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
7093 m->channel, m->name);
7094 return -1;
7097 strcpy (packet, "OK");
7098 return 0;
7101 sprintf (packet, "E.no marker found at 0x%s", paddress (address));
7102 return -1;
7105 static int
7106 cmd_qtstmat (char *packet)
7108 char *p = packet;
7109 ULONGEST address;
7110 struct marker_iter iter;
7111 struct marker *m;
7113 p += sizeof ("qTSTMat:") - 1;
7115 p = unpack_varlen_hex (p, &address);
7117 USTF(marker_iter_reset) (&iter);
7119 for (USTF(marker_iter_start) (&iter), m = iter.marker;
7120 m != NULL;
7121 USTF(marker_iter_next) (&iter), m = iter.marker)
7122 if ((uintptr_t ) m->location == address)
7124 response_ust_marker (packet, m);
7125 return 0;
7128 strcpy (packet, "l");
7129 return -1;
7132 static void
7133 gdb_ust_init (void)
7135 if (!dlsym_ust ())
7136 return;
7138 USTF(ltt_probe_register) (&gdb_ust_probe);
7141 #endif /* HAVE_UST */
7143 #include <sys/syscall.h>
7145 static void
7146 gdb_agent_remove_socket (void)
7148 unlink (agent_socket_name);
7151 /* Helper thread of agent. */
7153 static void *
7154 gdb_agent_helper_thread (void *arg)
7156 int listen_fd;
7158 atexit (gdb_agent_remove_socket);
7160 while (1)
7162 listen_fd = gdb_agent_socket_init ();
7164 if (helper_thread_id == 0)
7165 helper_thread_id = syscall (SYS_gettid);
7167 if (listen_fd == -1)
7169 warning ("could not create sync socket");
7170 break;
7173 while (1)
7175 socklen_t tmp;
7176 struct sockaddr_un sockaddr;
7177 int fd;
7178 char buf[1];
7179 int ret;
7180 int stop_loop = 0;
7182 tmp = sizeof (sockaddr);
7186 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
7188 /* It seems an ERESTARTSYS can escape out of accept. */
7189 while (fd == -512 || (fd == -1 && errno == EINTR));
7191 if (fd < 0)
7193 warning ("Accept returned %d, error: %s",
7194 fd, safe_strerror (errno));
7195 break;
7200 ret = read (fd, buf, 1);
7201 } while (ret == -1 && errno == EINTR);
7203 if (ret == -1)
7205 warning ("reading socket (fd=%d) failed with %s",
7206 fd, safe_strerror (errno));
7207 close (fd);
7208 break;
7211 if (cmd_buf[0])
7213 if (startswith (cmd_buf, "close"))
7215 stop_loop = 1;
7217 #ifdef HAVE_UST
7218 else if (strcmp ("qTfSTM", cmd_buf) == 0)
7220 cmd_qtfstm (cmd_buf);
7222 else if (strcmp ("qTsSTM", cmd_buf) == 0)
7224 cmd_qtsstm (cmd_buf);
7226 else if (startswith (cmd_buf, "unprobe_marker_at:"))
7228 unprobe_marker_at (cmd_buf);
7230 else if (startswith (cmd_buf, "probe_marker_at:"))
7232 probe_marker_at (cmd_buf);
7234 else if (startswith (cmd_buf, "qTSTMat:"))
7236 cmd_qtstmat (cmd_buf);
7238 #endif /* HAVE_UST */
7241 /* Fix compiler's warning: ignoring return value of 'write'. */
7242 ret = write (fd, buf, 1);
7243 close (fd);
7245 if (stop_loop)
7247 close (listen_fd);
7248 unlink (agent_socket_name);
7250 /* Sleep endlessly to wait the whole inferior stops. This
7251 thread can not exit because GDB or GDBserver may still need
7252 'current_thread' (representing this thread) to access
7253 inferior memory. Otherwise, this thread exits earlier than
7254 other threads, and 'current_thread' is set to NULL. */
7255 while (1)
7256 sleep (10);
7261 return NULL;
7264 #include <signal.h>
7265 #include <pthread.h>
7267 extern "C" {
7268 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
7271 static void
7272 gdb_agent_init (void)
7274 int res;
7275 pthread_t thread;
7276 sigset_t new_mask;
7277 sigset_t orig_mask;
7279 /* We want the helper thread to be as transparent as possible, so
7280 have it inherit an all-signals-blocked mask. */
7282 sigfillset (&new_mask);
7283 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
7284 if (res)
7285 perror_with_name ("pthread_sigmask (1)");
7287 res = pthread_create (&thread,
7288 NULL,
7289 gdb_agent_helper_thread,
7290 NULL);
7292 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
7293 if (res)
7294 perror_with_name ("pthread_sigmask (2)");
7296 while (helper_thread_id == 0)
7297 usleep (1);
7299 #ifdef HAVE_UST
7300 gdb_ust_init ();
7301 #endif
7304 #include <sys/mman.h>
7306 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
7307 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
7308 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
7309 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
7310 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
7311 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
7313 /* Record the result of getting buffer space for fast tracepoint
7314 trampolines. Any error message is copied, since caller may not be
7315 using persistent storage. */
7317 void
7318 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
7320 gdb_trampoline_buffer = (char *) (uintptr_t) begin;
7321 gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
7322 if (errmsg)
7323 strncpy (gdb_trampoline_buffer_error, errmsg, 99);
7324 else
7325 strcpy (gdb_trampoline_buffer_error, "no buffer passed");
7328 static void __attribute__ ((constructor))
7329 initialize_tracepoint_ftlib (void)
7331 initialize_tracepoint ();
7333 gdb_agent_init ();
7336 #ifndef HAVE_GETAUXVAL
7337 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
7338 found, 0 is returned. This function is provided if glibc is too old. */
7340 unsigned long
7341 getauxval (unsigned long type)
7343 unsigned long data[2];
7344 FILE *f = fopen ("/proc/self/auxv", "r");
7345 unsigned long value = 0;
7347 if (f == NULL)
7348 return 0;
7350 while (fread (data, sizeof (data), 1, f) > 0)
7352 if (data[0] == type)
7354 value = data[1];
7355 break;
7359 fclose (f);
7360 return value;
7362 #endif
7364 #endif /* IN_PROCESS_AGENT */
7366 /* Return a timestamp, expressed as microseconds of the usual Unix
7367 time. (As the result is a 64-bit number, it will not overflow any
7368 time soon.) */
7370 static LONGEST
7371 get_timestamp (void)
7373 using namespace std::chrono;
7375 steady_clock::time_point now = steady_clock::now ();
7376 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
7379 void
7380 initialize_tracepoint (void)
7382 /* Start with the default size. */
7383 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
7385 /* Wire trace state variable 1 to be the timestamp. This will be
7386 uploaded to GDB upon connection and become one of its trace state
7387 variables. (In case you're wondering, if GDB already has a trace
7388 variable numbered 1, it will be renumbered.) */
7389 create_trace_state_variable (1, 0);
7390 set_trace_state_variable_name (1, "trace_timestamp");
7391 set_trace_state_variable_getter (1, get_timestamp);
7393 #ifdef IN_PROCESS_AGENT
7395 int pagesize;
7396 size_t jump_pad_size;
7398 pagesize = sysconf (_SC_PAGE_SIZE);
7399 if (pagesize == -1)
7400 perror_with_name ("sysconf");
7402 #define SCRATCH_BUFFER_NPAGES 20
7404 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
7406 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
7407 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
7408 if (gdb_jump_pad_buffer == NULL)
7409 perror_with_name ("mmap");
7410 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
7413 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
7415 /* It's not a fatal error for something to go wrong with trampoline
7416 buffer setup, but it can be mysterious, so create a channel to
7417 report back on what went wrong, using a fixed size since we may
7418 not be able to allocate space later when the problem occurs. */
7419 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
7421 strcpy (gdb_trampoline_buffer_error, "No errors reported");
7423 initialize_low_tracepoint ();
7424 #endif