Debian Codegraph @

gdbserver/tracepoint.cc

raw
1 /* Tracepoint code for remote server for GDB.
2 Copyright (C) 2009-2025 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
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.
10
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.
15
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/>. */
18
19 #include "tracepoint.h"
20 #include "gdbthread.h"
21 #include "gdbsupport/rsp-low.h"
22
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"
30
31 #define IPA_SYM_STRUCT_NAME ipa_sym_addresses
32 #include "gdbsupport/agent.h"
33
34 #define DEFAULT_TRACE_BUFFER_SIZE 5242880 /* 5*1024*1024 */
35
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).
45
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.
53
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.
60
61 */
62
63 #ifdef IN_PROCESS_AGENT
64
65 static void trace_vdebug (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
66
67 static void
68 trace_vdebug (const char *fmt, ...)
69 {
70 char buf[1024];
71 va_list ap;
72
73 va_start (ap, fmt);
74 vsprintf (buf, fmt, ap);
75 fprintf (stderr, PROG "/tracepoint: %s\n", buf);
76 va_end (ap);
77 }
78
79 #define trace_debug(fmt, args...) \
80 do { \
81 if (debug_threads) \
82 trace_vdebug ((fmt), ##args); \
83 } while (0)
84
85 #else
86
87 #define trace_debug(fmt, args...) \
88 do { \
89 threads_debug_printf ((fmt), ##args); \
90 } while (0)
91
92 #endif
93
94 /* Prefix exported symbols, for good citizenship. All the symbols
95 that need exporting are defined in this module. Note that all
96 these symbols must be tagged with IP_AGENT_EXPORT_*. */
97 #ifdef IN_PROCESS_AGENT
98 # define gdb_tp_heap_buffer IPA_SYM_EXPORTED_NAME (gdb_tp_heap_buffer)
99 # define gdb_jump_pad_buffer IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer)
100 # define gdb_jump_pad_buffer_end IPA_SYM_EXPORTED_NAME (gdb_jump_pad_buffer_end)
101 # define gdb_trampoline_buffer IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer)
102 # define gdb_trampoline_buffer_end IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_end)
103 # define gdb_trampoline_buffer_error IPA_SYM_EXPORTED_NAME (gdb_trampoline_buffer_error)
104 # define collecting IPA_SYM_EXPORTED_NAME (collecting)
105 # define gdb_collect_ptr IPA_SYM_EXPORTED_NAME (gdb_collect_ptr)
106 # define stop_tracing IPA_SYM_EXPORTED_NAME (stop_tracing)
107 # define flush_trace_buffer IPA_SYM_EXPORTED_NAME (flush_trace_buffer)
108 # define about_to_request_buffer_space IPA_SYM_EXPORTED_NAME (about_to_request_buffer_space)
109 # define trace_buffer_is_full IPA_SYM_EXPORTED_NAME (trace_buffer_is_full)
110 # define stopping_tracepoint IPA_SYM_EXPORTED_NAME (stopping_tracepoint)
111 # define expr_eval_result IPA_SYM_EXPORTED_NAME (expr_eval_result)
112 # define error_tracepoint IPA_SYM_EXPORTED_NAME (error_tracepoint)
113 # define tracepoints IPA_SYM_EXPORTED_NAME (tracepoints)
114 # define tracing IPA_SYM_EXPORTED_NAME (tracing)
115 # define trace_buffer_ctrl IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl)
116 # define trace_buffer_ctrl_curr IPA_SYM_EXPORTED_NAME (trace_buffer_ctrl_curr)
117 # define trace_buffer_lo IPA_SYM_EXPORTED_NAME (trace_buffer_lo)
118 # define trace_buffer_hi IPA_SYM_EXPORTED_NAME (trace_buffer_hi)
119 # define traceframe_read_count IPA_SYM_EXPORTED_NAME (traceframe_read_count)
120 # define traceframe_write_count IPA_SYM_EXPORTED_NAME (traceframe_write_count)
121 # define traceframes_created IPA_SYM_EXPORTED_NAME (traceframes_created)
122 # define trace_state_variables IPA_SYM_EXPORTED_NAME (trace_state_variables)
123 # define get_raw_reg_ptr IPA_SYM_EXPORTED_NAME (get_raw_reg_ptr)
124 # define get_trace_state_variable_value_ptr \
125 IPA_SYM_EXPORTED_NAME (get_trace_state_variable_value_ptr)
126 # define set_trace_state_variable_value_ptr \
127 IPA_SYM_EXPORTED_NAME (set_trace_state_variable_value_ptr)
128 # define helper_thread_id IPA_SYM_EXPORTED_NAME (helper_thread_id)
129 # define cmd_buf IPA_SYM_EXPORTED_NAME (cmd_buf)
130 # define ipa_tdesc_idx IPA_SYM_EXPORTED_NAME (ipa_tdesc_idx)
131 #endif
132
133 #ifndef IN_PROCESS_AGENT
134
135 /* Addresses of in-process agent's symbols GDBserver cares about. */
136
137 struct ipa_sym_addresses
138 {
139 CORE_ADDR addr_gdb_tp_heap_buffer;
140 CORE_ADDR addr_gdb_jump_pad_buffer;
141 CORE_ADDR addr_gdb_jump_pad_buffer_end;
142 CORE_ADDR addr_gdb_trampoline_buffer;
143 CORE_ADDR addr_gdb_trampoline_buffer_end;
144 CORE_ADDR addr_gdb_trampoline_buffer_error;
145 CORE_ADDR addr_collecting;
146 CORE_ADDR addr_gdb_collect_ptr;
147 CORE_ADDR addr_stop_tracing;
148 CORE_ADDR addr_flush_trace_buffer;
149 CORE_ADDR addr_about_to_request_buffer_space;
150 CORE_ADDR addr_trace_buffer_is_full;
151 CORE_ADDR addr_stopping_tracepoint;
152 CORE_ADDR addr_expr_eval_result;
153 CORE_ADDR addr_error_tracepoint;
154 CORE_ADDR addr_tracepoints;
155 CORE_ADDR addr_tracing;
156 CORE_ADDR addr_trace_buffer_ctrl;
157 CORE_ADDR addr_trace_buffer_ctrl_curr;
158 CORE_ADDR addr_trace_buffer_lo;
159 CORE_ADDR addr_trace_buffer_hi;
160 CORE_ADDR addr_traceframe_read_count;
161 CORE_ADDR addr_traceframe_write_count;
162 CORE_ADDR addr_traceframes_created;
163 CORE_ADDR addr_trace_state_variables;
164 CORE_ADDR addr_get_raw_reg_ptr;
165 CORE_ADDR addr_get_trace_state_variable_value_ptr;
166 CORE_ADDR addr_set_trace_state_variable_value_ptr;
167 CORE_ADDR addr_ipa_tdesc_idx;
168 };
169
170 static struct
171 {
172 const char *name;
173 int offset;
174 } symbol_list[] = {
175 IPA_SYM(gdb_tp_heap_buffer),
176 IPA_SYM(gdb_jump_pad_buffer),
177 IPA_SYM(gdb_jump_pad_buffer_end),
178 IPA_SYM(gdb_trampoline_buffer),
179 IPA_SYM(gdb_trampoline_buffer_end),
180 IPA_SYM(gdb_trampoline_buffer_error),
181 IPA_SYM(collecting),
182 IPA_SYM(gdb_collect_ptr),
183 IPA_SYM(stop_tracing),
184 IPA_SYM(flush_trace_buffer),
185 IPA_SYM(about_to_request_buffer_space),
186 IPA_SYM(trace_buffer_is_full),
187 IPA_SYM(stopping_tracepoint),
188 IPA_SYM(expr_eval_result),
189 IPA_SYM(error_tracepoint),
190 IPA_SYM(tracepoints),
191 IPA_SYM(tracing),
192 IPA_SYM(trace_buffer_ctrl),
193 IPA_SYM(trace_buffer_ctrl_curr),
194 IPA_SYM(trace_buffer_lo),
195 IPA_SYM(trace_buffer_hi),
196 IPA_SYM(traceframe_read_count),
197 IPA_SYM(traceframe_write_count),
198 IPA_SYM(traceframes_created),
199 IPA_SYM(trace_state_variables),
200 IPA_SYM(get_raw_reg_ptr),
201 IPA_SYM(get_trace_state_variable_value_ptr),
202 IPA_SYM(set_trace_state_variable_value_ptr),
203 IPA_SYM(ipa_tdesc_idx),
204 };
205
206 static struct ipa_sym_addresses ipa_sym_addrs;
207
208 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
209
210 static void
211 write_e_ipa_not_loaded (char *buffer)
212 {
213 sprintf (buffer,
214 "E.In-process agent library not loaded in process. "
215 "Fast tracepoints unavailable.");
216 }
217
218 /* If the in-process agent library isn't loaded in the inferior, write
219 an error to BUFFER, and return 1. Otherwise, return 0. */
220
221 static int
222 maybe_write_ipa_not_loaded (char *buffer)
223 {
224 if (!agent_loaded_p ())
225 {
226 write_e_ipa_not_loaded (buffer);
227 return 1;
228 }
229 return 0;
230 }
231
232 /* Cache all future symbols that the tracepoints module might request.
233 We can not request symbols at arbitrary states in the remote
234 protocol, only when the client tells us that new symbols are
235 available. So when we load the in-process library, make sure to
236 check the entire list. */
237
238 void
239 tracepoint_look_up_symbols (void)
240 {
241 int i;
242
243 if (agent_loaded_p ())
244 return;
245
246 for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
247 {
248 CORE_ADDR *addrp =
249 (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
250
251 if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
252 {
253 threads_debug_printf ("symbol `%s' not found", symbol_list[i].name);
254 return;
255 }
256 }
257
258 agent_look_up_symbols (NULL);
259 }
260
261 #endif
262
263 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
264 of the "stop_tracing" function. When this breakpoint is hit,
265 tracing stopped in the IPA for some reason. E.g., due to
266 tracepoint reaching the pass count, hitting conditional expression
267 evaluation error, etc.
268
269 The IPA's trace buffer is never in circular tracing mode: instead,
270 GDBserver's is, and whenever the in-process buffer fills, it calls
271 "flush_trace_buffer", which triggers an internal breakpoint.
272 GDBserver reacts to this breakpoint by pulling the meanwhile
273 collected data. Old frames discarding is always handled on the
274 GDBserver side. */
275
276 #ifdef IN_PROCESS_AGENT
277 /* See target.h. */
278
279 int
280 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
281 {
282 memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
283 return 0;
284 }
285
286 /* Call this in the functions where GDBserver places a breakpoint, so
287 that the compiler doesn't try to be clever and skip calling the
288 function at all. This is necessary, even if we tell the compiler
289 to not inline said functions. */
290
291 #if defined(__GNUC__)
292 # define UNKNOWN_SIDE_EFFECTS() asm ("")
293 #else
294 # define UNKNOWN_SIDE_EFFECTS() do {} while (0)
295 #endif
296
297 /* This is needed for -Wmissing-declarations. */
298 IP_AGENT_EXPORT_FUNC void stop_tracing (void);
299
300 IP_AGENT_EXPORT_FUNC void
301 stop_tracing (void)
302 {
303 /* GDBserver places breakpoint here. */
304 UNKNOWN_SIDE_EFFECTS();
305 }
306
307 /* This is needed for -Wmissing-declarations. */
308 IP_AGENT_EXPORT_FUNC void flush_trace_buffer (void);
309
310 IP_AGENT_EXPORT_FUNC void
311 flush_trace_buffer (void)
312 {
313 /* GDBserver places breakpoint here. */
314 UNKNOWN_SIDE_EFFECTS();
315 }
316
317 #endif
318
319 #ifndef IN_PROCESS_AGENT
320 static int
321 tracepoint_handler (CORE_ADDR address)
322 {
323 trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
324 paddress (address));
325 return 0;
326 }
327
328 /* Breakpoint at "stop_tracing" in the inferior lib. */
329 static struct breakpoint *stop_tracing_bkpt;
330 static int stop_tracing_handler (CORE_ADDR);
331
332 /* Breakpoint at "flush_trace_buffer" in the inferior lib. */
333 static struct breakpoint *flush_trace_buffer_bkpt;
334 static int flush_trace_buffer_handler (CORE_ADDR);
335
336 static void download_trace_state_variables (void);
337 static void upload_fast_traceframes (void);
338
339 static int run_inferior_command (char *cmd, int len);
340
341 static int
342 read_inferior_integer (CORE_ADDR symaddr, int *val)
343 {
344 return read_inferior_memory (symaddr, (unsigned char *) val,
345 sizeof (*val));
346 }
347
348 struct tracepoint;
349 static int tracepoint_send_agent (struct tracepoint *tpoint);
350
351 static int
352 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
353 {
354 return read_inferior_memory (symaddr, (unsigned char *) val,
355 sizeof (*val));
356 }
357
358 static int
359 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
360 {
361 void *pval = (void *) (uintptr_t) val;
362 int ret;
363
364 ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
365 *val = (uintptr_t) pval;
366 return ret;
367 }
368
369 static int
370 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
371 {
372 void *pval = (void *) (uintptr_t) val;
373 return target_write_memory (symaddr,
374 (unsigned char *) &pval, sizeof (pval));
375 }
376
377 static int
378 write_inferior_integer (CORE_ADDR symaddr, int val)
379 {
380 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
381 }
382
383 static int
384 write_inferior_int8 (CORE_ADDR symaddr, int8_t val)
385 {
386 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
387 }
388
389 static int
390 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
391 {
392 return target_write_memory (symaddr, (unsigned char *) &val, sizeof (val));
393 }
394
395 static CORE_ADDR target_malloc (ULONGEST size);
396
397 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD) \
398 do { \
399 memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
400 BUF += sizeof ((OBJ)->FIELD); \
401 } while (0)
402
403 #endif
404
405 /* Base action. Concrete actions inherit this. */
406
407 struct tracepoint_action
408 {
409 char type;
410 };
411
412 /* An 'M' (collect memory) action. */
413 struct collect_memory_action
414 {
415 struct tracepoint_action base;
416
417 ULONGEST addr;
418 ULONGEST len;
419 int32_t basereg;
420 };
421
422 /* An 'R' (collect registers) action. */
423
424 struct collect_registers_action
425 {
426 struct tracepoint_action base;
427 };
428
429 /* An 'X' (evaluate expression) action. */
430
431 struct eval_expr_action
432 {
433 struct tracepoint_action base;
434
435 struct agent_expr *expr;
436 };
437
438 #ifndef IN_PROCESS_AGENT
439 static CORE_ADDR
440 m_tracepoint_action_download (const struct tracepoint_action *action)
441 {
442 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_memory_action));
443
444 target_write_memory (ipa_action, (unsigned char *) action,
445 sizeof (struct collect_memory_action));
446
447 return ipa_action;
448 }
449 static char *
450 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
451 {
452 struct collect_memory_action *maction
453 = (struct collect_memory_action *) action;
454
455 COPY_FIELD_TO_BUF (buffer, maction, addr);
456 COPY_FIELD_TO_BUF (buffer, maction, len);
457 COPY_FIELD_TO_BUF (buffer, maction, basereg);
458
459 return buffer;
460 }
461
462 static CORE_ADDR
463 r_tracepoint_action_download (const struct tracepoint_action *action)
464 {
465 CORE_ADDR ipa_action = target_malloc (sizeof (struct collect_registers_action));
466
467 target_write_memory (ipa_action, (unsigned char *) action,
468 sizeof (struct collect_registers_action));
469
470 return ipa_action;
471 }
472
473 static char *
474 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
475 {
476 return buffer;
477 }
478
479 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
480
481 static CORE_ADDR
482 x_tracepoint_action_download (const struct tracepoint_action *action)
483 {
484 CORE_ADDR ipa_action = target_malloc (sizeof (struct eval_expr_action));
485 CORE_ADDR expr;
486
487 target_write_memory (ipa_action, (unsigned char *) action,
488 sizeof (struct eval_expr_action));
489 expr = download_agent_expr (((struct eval_expr_action *) action)->expr);
490 write_inferior_data_pointer (ipa_action
491 + offsetof (struct eval_expr_action, expr),
492 expr);
493
494 return ipa_action;
495 }
496
497 /* Copy agent expression AEXPR to buffer pointed by P. If AEXPR is NULL,
498 copy 0 to P. Return updated header of buffer. */
499
500 static char *
501 agent_expr_send (char *p, const struct agent_expr *aexpr)
502 {
503 /* Copy the length of condition first, and then copy its
504 content. */
505 if (aexpr == NULL)
506 {
507 memset (p, 0, 4);
508 p += 4;
509 }
510 else
511 {
512 memcpy (p, &aexpr->length, 4);
513 p +=4;
514
515 memcpy (p, aexpr->bytes, aexpr->length);
516 p += aexpr->length;
517 }
518 return p;
519 }
520
521 static char *
522 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
523 {
524 struct eval_expr_action *eaction = (struct eval_expr_action *) action;
525
526 return agent_expr_send (buffer, eaction->expr);
527 }
528
529 static char *
530 tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
531 {
532 switch (action->type)
533 {
534 case 'M':
535 return m_tracepoint_action_send (buffer, action);
536 case 'R':
537 return r_tracepoint_action_send (buffer, action);
538 case 'X':
539 return x_tracepoint_action_send (buffer, action);
540 }
541 error ("Unknown trace action '%c'.", action->type);
542 }
543
544 static CORE_ADDR
545 tracepoint_action_download (const struct tracepoint_action *action)
546 {
547 switch (action->type)
548 {
549 case 'M':
550 return m_tracepoint_action_download (action);
551 case 'R':
552 return r_tracepoint_action_download (action);
553 case 'X':
554 return x_tracepoint_action_download (action);
555 }
556 error ("Unknown trace action '%c'.", action->type);
557 }
558 #endif
559
560 /* This structure describes a piece of the source-level definition of
561 the tracepoint. The contents are not interpreted by the target,
562 but preserved verbatim for uploading upon reconnection. */
563
564 struct source_string
565 {
566 /* The type of string, such as "cond" for a conditional. */
567 char *type;
568
569 /* The source-level string itself. For the sake of target
570 debugging, we store it in plaintext, even though it is always
571 transmitted in hex. */
572 char *str;
573
574 /* Link to the next one in the list. We link them in the order
575 received, in case some make up an ordered list of commands or
576 some such. */
577 struct source_string *next;
578 };
579
580 enum tracepoint_type
581 {
582 /* Trap based tracepoint. */
583 trap_tracepoint,
584
585 /* A fast tracepoint implemented with a jump instead of a trap. */
586 fast_tracepoint,
587 };
588
589 typedef enum eval_result_type (*condfn) (unsigned char *,
590 ULONGEST *);
591
592 /* The definition of a tracepoint. */
593
594 /* Tracepoints may have multiple locations, each at a different
595 address. This can occur with optimizations, template
596 instantiation, etc. Since the locations may be in different
597 scopes, the conditions and actions may be different for each
598 location. Our target version of tracepoints is more like GDB's
599 notion of "breakpoint locations", but we have almost nothing that
600 is not per-location, so we bother having two kinds of objects. The
601 key consequence is that numbers are not unique, and that it takes
602 both number and address to identify a tracepoint uniquely. */
603
604 struct tracepoint
605 {
606 /* The number of the tracepoint, as specified by GDB. Several
607 tracepoint objects here may share a number. */
608 uint32_t number;
609
610 /* Address at which the tracepoint is supposed to trigger. Several
611 tracepoints may share an address. */
612 CORE_ADDR address;
613
614 /* Tracepoint type. */
615 enum tracepoint_type type;
616
617 /* True if the tracepoint is currently enabled. */
618 int8_t enabled;
619
620 /* The number of single steps that will be performed after each
621 tracepoint hit. */
622 uint64_t step_count;
623
624 /* The number of times the tracepoint may be hit before it will
625 terminate the entire tracing run. */
626 uint64_t pass_count;
627
628 /* Pointer to the agent expression that is the tracepoint's
629 conditional, or NULL if the tracepoint is unconditional. */
630 struct agent_expr *cond;
631
632 /* The list of actions to take when the tracepoint triggers. */
633 uint32_t numactions;
634 struct tracepoint_action **actions;
635
636 /* Count of the times we've hit this tracepoint during the run.
637 Note that while-stepping steps are not counted as "hits". */
638 uint64_t hit_count;
639
640 /* Cached sum of the sizes of traceframes created by this point. */
641 uint64_t traceframe_usage;
642
643 CORE_ADDR compiled_cond;
644
645 /* Link to the next tracepoint in the list. */
646 struct tracepoint *next;
647
648 #ifndef IN_PROCESS_AGENT
649 /* The list of actions to take when the tracepoint triggers, in
650 string/packet form. */
651 char **actions_str;
652
653 /* The collection of strings that describe the tracepoint as it was
654 entered into GDB. These are not used by the target, but are
655 reported back to GDB upon reconnection. */
656 struct source_string *source_strings;
657
658 /* The number of bytes displaced by fast tracepoints. It may subsume
659 multiple instructions, for multi-byte fast tracepoints. This
660 field is only valid for fast tracepoints. */
661 uint32_t orig_size;
662
663 /* Only for fast tracepoints. */
664 CORE_ADDR obj_addr_on_target;
665
666 /* Address range where the original instruction under a fast
667 tracepoint was relocated to. (_end is actually one byte past
668 the end). */
669 CORE_ADDR adjusted_insn_addr;
670 CORE_ADDR adjusted_insn_addr_end;
671
672 /* The address range of the piece of the jump pad buffer that was
673 assigned to this fast tracepoint. (_end is actually one byte
674 past the end).*/
675 CORE_ADDR jump_pad;
676 CORE_ADDR jump_pad_end;
677
678 /* The address range of the piece of the trampoline buffer that was
679 assigned to this fast tracepoint. (_end is actually one byte
680 past the end). */
681 CORE_ADDR trampoline;
682 CORE_ADDR trampoline_end;
683
684 /* The list of actions to take while in a stepping loop. These
685 fields are only valid for patch-based tracepoints. */
686 int num_step_actions;
687 struct tracepoint_action **step_actions;
688 /* Same, but in string/packet form. */
689 char **step_actions_str;
690
691 /* Handle returned by the breakpoint or tracepoint module when we
692 inserted the trap or jump.
693 NULL if we haven't inserted it yet. */
694 void *handle;
695 #endif
696
697 };
698
699 #ifndef IN_PROCESS_AGENT
700
701 /* Given `while-stepping', a thread may be collecting data for more
702 than one tracepoint simultaneously. On the other hand, the same
703 tracepoint with a while-stepping action may be hit by more than one
704 thread simultaneously (but not quite, each thread could be handling
705 a different step). Each thread holds a list of these objects,
706 representing the current step of each while-stepping action being
707 collected. */
708
709 struct wstep_state
710 {
711 struct wstep_state *next;
712
713 /* The tracepoint number. */
714 int tp_number;
715 /* The tracepoint's address. */
716 CORE_ADDR tp_address;
717
718 /* The number of the current step in this 'while-stepping'
719 action. */
720 long current_step;
721 };
722
723 #endif
724
725 extern "C" {
726
727 /* The linked list of all tracepoints. Marked explicitly as used as
728 the in-process library doesn't use it for the fast tracepoints
729 support. */
730 IP_AGENT_EXPORT_VAR struct tracepoint *tracepoints;
731
732 /* The first tracepoint to exceed its pass count. */
733
734 IP_AGENT_EXPORT_VAR struct tracepoint *stopping_tracepoint;
735
736 /* True if the trace buffer is full or otherwise no longer usable. */
737
738 IP_AGENT_EXPORT_VAR int trace_buffer_is_full;
739
740 /* The first error that occurred during expression evaluation. */
741
742 /* Stored as an int to avoid the IPA ABI being dependent on whatever
743 the compiler decides to use for the enum's underlying type. Holds
744 enum eval_result_type values. */
745 IP_AGENT_EXPORT_VAR int expr_eval_result = expr_eval_no_error;
746
747 }
748
749 #ifndef IN_PROCESS_AGENT
750
751 /* Pointer to the last tracepoint in the list, new tracepoints are
752 linked in at the end. */
753
754 static struct tracepoint *last_tracepoint;
755
756 static const char * const eval_result_names[] =
757 {
758 #define AX_RESULT_TYPE(ENUM,STR) STR,
759 #include "ax-result-types.def"
760 #undef AX_RESULT_TYPE
761 };
762
763 #endif
764
765 /* The tracepoint in which the error occurred. */
766
767 extern "C" {
768 IP_AGENT_EXPORT_VAR struct tracepoint *error_tracepoint;
769 }
770
771 struct trace_state_variable
772 {
773 /* This is the name of the variable as used in GDB. The target
774 doesn't use the name, but needs to have it for saving and
775 reconnection purposes. */
776 char *name;
777
778 /* This number identifies the variable uniquely. Numbers may be
779 assigned either by the target (in the case of builtin variables),
780 or by GDB, and are presumed unique during the course of a trace
781 experiment. */
782 int number;
783
784 /* The variable's initial value, a 64-bit signed integer always. */
785 LONGEST initial_value;
786
787 /* The variable's value, a 64-bit signed integer always. */
788 LONGEST value;
789
790 /* Pointer to a getter function, used to supply computed values. */
791 LONGEST (*getter) (void);
792
793 /* Link to the next variable. */
794 struct trace_state_variable *next;
795 };
796
797 /* Linked list of all trace state variables. */
798
799 #ifdef IN_PROCESS_AGENT
800 static struct trace_state_variable *alloced_trace_state_variables;
801 #endif
802
803 IP_AGENT_EXPORT_VAR struct trace_state_variable *trace_state_variables;
804
805 /* The results of tracing go into a fixed-size space known as the
806 "trace buffer". Because usage follows a limited number of
807 patterns, we manage it ourselves rather than with malloc. Basic
808 rules are that we create only one trace frame at a time, each is
809 variable in size, they are never moved once created, and we only
810 discard if we are doing a circular buffer, and then only the oldest
811 ones. Each trace frame includes its own size, so we don't need to
812 link them together, and the trace frame number is relative to the
813 first one, so we don't need to record numbers. A trace frame also
814 records the number of the tracepoint that created it. The data
815 itself is a series of blocks, each introduced by a single character
816 and with a defined format. Each type of block has enough
817 type/length info to allow scanners to jump quickly from one block
818 to the next without reading each byte in the block. */
819
820 /* Trace buffer management would be simple - advance a free pointer
821 from beginning to end, then stop - were it not for the circular
822 buffer option, which is a useful way to prevent a trace run from
823 stopping prematurely because the buffer filled up. In the circular
824 case, the location of the first trace frame (trace_buffer_start)
825 moves as old trace frames are discarded. Also, since we grow trace
826 frames incrementally as actions are performed, we wrap around to
827 the beginning of the trace buffer. This is per-block, so each
828 block within a trace frame remains contiguous. Things get messy
829 when the wrapped-around trace frame is the one being discarded; the
830 free space ends up in two parts at opposite ends of the buffer. */
831
832 #ifndef ATTR_PACKED
833 # if defined(__GNUC__)
834 # define ATTR_PACKED __attribute__ ((packed))
835 # else
836 # define ATTR_PACKED /* nothing */
837 # endif
838 #endif
839
840 /* The data collected at a tracepoint hit. This object should be as
841 small as possible, since there may be a great many of them. We do
842 not need to keep a frame number, because they are all sequential
843 and there are no deletions; so the Nth frame in the buffer is
844 always frame number N. */
845
846 struct traceframe
847 {
848 /* Number of the tracepoint that collected this traceframe. A value
849 of 0 indicates the current end of the trace buffer. We make this
850 a 16-bit field because it's never going to happen that GDB's
851 numbering of tracepoints reaches 32,000. */
852 int tpnum : 16;
853
854 /* The size of the data in this trace frame. We limit this to 32
855 bits, even on a 64-bit target, because it's just implausible that
856 one is validly going to collect 4 gigabytes of data at a single
857 tracepoint hit. */
858 unsigned int data_size : 32;
859
860 /* The base of the trace data, which is contiguous from this point. */
861 unsigned char data[0];
862
863 } ATTR_PACKED;
864
865 /* The size of the EOB marker, in bytes. A traceframe with zeroed
866 fields (and no data) marks the end of trace data. */
867 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
868
869 /* This flag is true if the trace buffer is circular, meaning that
870 when it fills, the oldest trace frames are discarded in order to
871 make room. */
872
873 #ifndef IN_PROCESS_AGENT
874 static int circular_trace_buffer;
875 #endif
876
877 /* Size of the trace buffer. */
878
879 static LONGEST trace_buffer_size;
880
881 extern "C" {
882
883 /* Pointer to the block of memory that traceframes all go into. */
884
885 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_lo;
886
887 /* Pointer to the end of the trace buffer, more precisely to the byte
888 after the end of the buffer. */
889
890 IP_AGENT_EXPORT_VAR unsigned char *trace_buffer_hi;
891
892 }
893
894 /* Control structure holding the read/write/etc. pointers into the
895 trace buffer. We need more than one of these to implement a
896 transaction-like mechanism to guarantees that both GDBserver and the
897 in-process agent can try to change the trace buffer
898 simultaneously. */
899
900 struct trace_buffer_control
901 {
902 /* Pointer to the first trace frame in the buffer. In the
903 non-circular case, this is equal to trace_buffer_lo, otherwise it
904 moves around in the buffer. */
905 unsigned char *start;
906
907 /* Pointer to the free part of the trace buffer. Note that we clear
908 several bytes at and after this pointer, so that traceframe
909 scans/searches terminate properly. */
910 unsigned char *free;
911
912 /* Pointer to the byte after the end of the free part. Note that
913 this may be smaller than trace_buffer_free in the circular case,
914 and means that the free part is in two pieces. Initially it is
915 equal to trace_buffer_hi, then is generally equivalent to
916 trace_buffer_start. */
917 unsigned char *end_free;
918
919 /* Pointer to the wraparound. If not equal to trace_buffer_hi, then
920 this is the point at which the trace data breaks, and resumes at
921 trace_buffer_lo. */
922 unsigned char *wrap;
923 };
924
925 /* Same as above, to be used by GDBserver when updating the in-process
926 agent. */
927 struct ipa_trace_buffer_control
928 {
929 uintptr_t start;
930 uintptr_t free;
931 uintptr_t end_free;
932 uintptr_t wrap;
933 };
934
935
936 /* We have possibly both GDBserver and an inferior thread accessing
937 the same IPA trace buffer memory. The IPA is the producer (tries
938 to put new frames in the buffer), while GDBserver occasionally
939 consumes them, that is, flushes the IPA's buffer into its own
940 buffer. Both sides need to update the trace buffer control
941 pointers (current head, tail, etc.). We can't use a global lock to
942 synchronize the accesses, as otherwise we could deadlock GDBserver
943 (if the thread holding the lock stops for a signal, say). So
944 instead of that, we use a transaction scheme where GDBserver writes
945 always prevail over the IPAs writes, and, we have the IPA detect
946 the commit failure/overwrite, and retry the whole attempt. This is
947 mainly implemented by having a global token object that represents
948 who wrote last to the buffer control structure. We need to freeze
949 any inferior writing to the buffer while GDBserver touches memory,
950 so that the inferior can correctly detect that GDBserver had been
951 there, otherwise, it could mistakenly think its commit was
952 successful; that's implemented by simply having GDBserver set a
953 breakpoint the inferior hits if it is the critical region.
954
955 There are three cycling trace buffer control structure copies
956 (buffer head, tail, etc.), with the token object including an index
957 indicating which is current live copy. The IPA tentatively builds
958 an updated copy in a non-current control structure, while GDBserver
959 always clobbers the current version directly. The IPA then tries
960 to atomically "commit" its version; if GDBserver clobbered the
961 structure meanwhile, that will fail, and the IPA restarts the
962 allocation process.
963
964 Listing the step in further detail, we have:
965
966 In-process agent (producer):
967
968 - passes by `about_to_request_buffer_space' breakpoint/lock
969
970 - reads current token, extracts current trace buffer control index,
971 and starts tentatively updating the rightmost one (0->1, 1->2,
972 2->0). Note that only one inferior thread is executing this code
973 at any given time, due to an outer lock in the jump pads.
974
975 - updates counters, and tries to commit the token.
976
977 - passes by second `about_to_request_buffer_space' breakpoint/lock,
978 leaving the sync region.
979
980 - checks if the update was effective.
981
982 - if trace buffer was found full, hits flush_trace_buffer
983 breakpoint, and restarts later afterwards.
984
985 GDBserver (consumer):
986
987 - sets `about_to_request_buffer_space' breakpoint/lock.
988
989 - updates the token unconditionally, using the current buffer
990 control index, since it knows that the IP agent always writes to
991 the rightmost, and due to the breakpoint, at most one IP thread
992 can try to update the trace buffer concurrently to GDBserver, so
993 there will be no danger of trace buffer control index wrap making
994 the IPA write to the same index as GDBserver.
995
996 - flushes the IP agent's trace buffer completely, and updates the
997 current trace buffer control structure. GDBserver *always* wins.
998
999 - removes the `about_to_request_buffer_space' breakpoint.
1000
1001 The token is stored in the `trace_buffer_ctrl_curr' variable.
1002 Internally, it's bits are defined as:
1003
1004 |-------------+-----+-------------+--------+-------------+--------------|
1005 | Bit offsets | 31 | 30 - 20 | 19 | 18-8 | 7-0 |
1006 |-------------+-----+-------------+--------+-------------+--------------|
1007 | What | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
1008 |-------------+-----+-------------+--------+-------------+--------------|
1009
1010 GSB - GDBserver Stamp Bit
1011 PC - Previous Counter
1012 CC - Current Counter
1013 TBCI - Trace Buffer Control Index
1014
1015
1016 An IPA update of `trace_buffer_ctrl_curr' does:
1017
1018 - read CC from the current token, save as PC.
1019 - updates pointers
1020 - atomically tries to write PC+1,CC
1021
1022 A GDBserver update of `trace_buffer_ctrl_curr' does:
1023
1024 - reads PC and CC from the current token.
1025 - updates pointers
1026 - writes GSB,PC,CC
1027 */
1028
1029 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
1030 for the counters described below. The cleared bits are used to
1031 hold the index of the items of the `trace_buffer_ctrl' array that
1032 is "current". */
1033 #define GDBSERVER_FLUSH_COUNT_MASK 0xfffffff0
1034
1035 /* `trace_buffer_ctrl_curr' contains two counters. The `previous'
1036 counter, and the `current' counter. */
1037
1038 #define GDBSERVER_FLUSH_COUNT_MASK_PREV 0x7ff00000
1039 #define GDBSERVER_FLUSH_COUNT_MASK_CURR 0x0007ff00
1040
1041 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
1042 always stamps this bit as set. */
1043 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
1044
1045 #ifdef IN_PROCESS_AGENT
1046 IP_AGENT_EXPORT_VAR struct trace_buffer_control trace_buffer_ctrl[3];
1047 IP_AGENT_EXPORT_VAR unsigned int trace_buffer_ctrl_curr;
1048
1049 # define TRACE_BUFFER_CTRL_CURR \
1050 (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
1051
1052 #else
1053
1054 /* The GDBserver side agent only needs one instance of this object, as
1055 it doesn't need to sync with itself. Define it as array anyway so
1056 that the rest of the code base doesn't need to care for the
1057 difference. */
1058 static trace_buffer_control trace_buffer_ctrl[1];
1059 # define TRACE_BUFFER_CTRL_CURR 0
1060 #endif
1061
1062 /* These are convenience macros used to access the current trace
1063 buffer control in effect. */
1064 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
1065 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
1066 #define trace_buffer_end_free \
1067 (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
1068 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
1069
1070
1071 /* Macro that returns a pointer to the first traceframe in the buffer. */
1072
1073 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
1074
1075 /* Macro that returns a pointer to the next traceframe in the buffer.
1076 If the computed location is beyond the wraparound point, subtract
1077 the offset of the wraparound. */
1078
1079 #define NEXT_TRACEFRAME_1(TF) \
1080 (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
1081
1082 #define NEXT_TRACEFRAME(TF) \
1083 ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF) \
1084 - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
1085 ? (trace_buffer_wrap - trace_buffer_lo) \
1086 : 0)))
1087
1088 /* The difference between these counters represents the total number
1089 of complete traceframes present in the trace buffer. The IP agent
1090 writes to the write count, GDBserver writes to read count. */
1091
1092 IP_AGENT_EXPORT_VAR unsigned int traceframe_write_count;
1093 IP_AGENT_EXPORT_VAR unsigned int traceframe_read_count;
1094
1095 /* Convenience macro. */
1096
1097 #define traceframe_count \
1098 ((unsigned int) (traceframe_write_count - traceframe_read_count))
1099
1100 /* The count of all traceframes created in the current run, including
1101 ones that were discarded to make room. */
1102
1103 IP_AGENT_EXPORT_VAR int traceframes_created;
1104
1105 #ifndef IN_PROCESS_AGENT
1106
1107 /* Read-only regions are address ranges whose contents don't change,
1108 and so can be read from target memory even while looking at a trace
1109 frame. Without these, disassembly for instance will likely fail,
1110 because the program code is not usually collected into a trace
1111 frame. This data structure does not need to be very complicated or
1112 particularly efficient, it's only going to be used occasionally,
1113 and only by some commands. */
1114
1115 struct readonly_region
1116 {
1117 /* The bounds of the region. */
1118 CORE_ADDR start, end;
1119
1120 /* Link to the next one. */
1121 struct readonly_region *next;
1122 };
1123
1124 /* Linked list of readonly regions. This list stays in effect from
1125 one tstart to the next. */
1126
1127 static struct readonly_region *readonly_regions;
1128
1129 #endif
1130
1131 /* The global that controls tracing overall. */
1132
1133 IP_AGENT_EXPORT_VAR int tracing;
1134
1135 #ifndef IN_PROCESS_AGENT
1136
1137 /* Controls whether tracing should continue after GDB disconnects. */
1138
1139 int disconnected_tracing;
1140
1141 /* The reason for the last tracing run to have stopped. We initialize
1142 to a distinct string so that GDB can distinguish between "stopped
1143 after running" and "stopped because never run" cases. */
1144
1145 static const char *tracing_stop_reason = "tnotrun";
1146
1147 static int tracing_stop_tpnum;
1148
1149 /* 64-bit timestamps for the trace run's start and finish, expressed
1150 in microseconds from the Unix epoch. */
1151
1152 static LONGEST tracing_start_time;
1153 static LONGEST tracing_stop_time;
1154
1155 /* The (optional) user-supplied name of the user that started the run.
1156 This is an arbitrary string, and may be NULL. */
1157
1158 static char *tracing_user_name;
1159
1160 /* Optional user-supplied text describing the run. This is
1161 an arbitrary string, and may be NULL. */
1162
1163 static char *tracing_notes;
1164
1165 /* Optional user-supplied text explaining a tstop command. This is an
1166 arbitrary string, and may be NULL. */
1167
1168 static char *tracing_stop_note;
1169
1170 #endif
1171
1172 /* Base class for tracepoint type specific data to be passed down to
1173 collect_data_at_tracepoint. */
1174 struct tracepoint_hit_ctx
1175 {
1176 virtual struct regcache *regcache () = 0;
1177 };
1178
1179 #ifdef IN_PROCESS_AGENT
1180 /* The target description index for IPA. Passed from gdbserver, used
1181 to select ipa_tdesc. */
1182 extern "C" {
1183 IP_AGENT_EXPORT_VAR int ipa_tdesc_idx;
1184 }
1185
1186 /* Fast/jump tracepoint specific data to be passed down to
1187 collect_data_at_tracepoint. */
1188 struct fast_tracepoint_ctx : public tracepoint_hit_ctx
1189 {
1190 explicit fast_tracepoint_ctx (unsigned char *regs)
1191 : regs (regs)
1192 {}
1193
1194 virtual struct regcache *regcache () override
1195 {
1196 const struct target_desc *ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
1197
1198 if (!this->m_regcache.has_value ())
1199 {
1200 this->m_regcache.emplace (ipa_tdesc, this->regspace);
1201 supply_fast_tracepoint_registers (&this->m_regcache.value (),
1202 this->regs);
1203 }
1204
1205 return &this->m_regcache.value ();
1206 }
1207
1208 /* The buffer space M_REGCACHE uses. We use a separate buffer
1209 instead of letting the regcache malloc for both signal safety and
1210 performance reasons; this is allocated on the stack instead. */
1211 unsigned char *regspace = nullptr;
1212
1213 /* The register buffer passed by the client. */
1214 unsigned char *regs;
1215
1216 /* The GDB tracepoint matching the probed marker that was "hit". */
1217 struct tracepoint *tpoint = nullptr;
1218
1219 private:
1220
1221 /* The regcache corresponding to the registers state at the time of
1222 the tracepoint hit. Initialized lazily, from REGS. */
1223 std::optional<struct regcache> m_regcache;
1224 };
1225
1226 #else
1227
1228 /* Static tracepoint specific data to be passed down to
1229 collect_data_at_tracepoint. */
1230 struct trap_tracepoint_ctx : public tracepoint_hit_ctx
1231 {
1232 explicit trap_tracepoint_ctx (struct regcache *regcache)
1233 : m_regcache (regcache)
1234 {}
1235
1236 virtual struct regcache *regcache () override
1237 {
1238 return this->m_regcache;
1239 }
1240
1241 private:
1242
1243 struct regcache *m_regcache;
1244 };
1245
1246 #endif
1247
1248 #ifndef IN_PROCESS_AGENT
1249 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
1250 static int traceframe_read_tsv (int num, LONGEST *val);
1251 #endif
1252
1253 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1254 struct tracepoint *tpoint);
1255
1256 #ifndef IN_PROCESS_AGENT
1257 static void clear_readonly_regions (void);
1258 static void clear_installed_tracepoints (void);
1259 #endif
1260
1261 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1262 CORE_ADDR stop_pc,
1263 struct tracepoint *tpoint);
1264 #ifndef IN_PROCESS_AGENT
1265 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
1266 CORE_ADDR stop_pc,
1267 struct tracepoint *tpoint, int current_step);
1268 static void compile_tracepoint_condition (struct tracepoint *tpoint,
1269 CORE_ADDR *jump_entry);
1270 #endif
1271 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
1272 CORE_ADDR stop_pc,
1273 struct tracepoint *tpoint,
1274 struct traceframe *tframe,
1275 struct tracepoint_action *taction);
1276
1277 #ifndef IN_PROCESS_AGENT
1278 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
1279
1280 static void install_tracepoint (struct tracepoint *, char *own_buf);
1281 static void download_tracepoint (struct tracepoint *);
1282 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
1283 static void clone_fast_tracepoint (struct tracepoint *to,
1284 const struct tracepoint *from);
1285 #endif
1286
1287 static LONGEST get_timestamp (void);
1288
1289 #if defined(__GNUC__)
1290 # define memory_barrier() asm volatile ("" : : : "memory")
1291 #else
1292 # define memory_barrier() do {} while (0)
1293 #endif
1294
1295 /* We only build the IPA if this builtin is supported, and there are
1296 no uses of this in GDBserver itself, so we're safe in defining this
1297 unconditionally. */
1298 #define cmpxchg(mem, oldval, newval) \
1299 __sync_val_compare_and_swap (mem, oldval, newval)
1300
1301 /* Record that an error occurred during expression evaluation. */
1302
1303 static void
1304 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
1305 enum eval_result_type rtype)
1306 {
1307 trace_debug ("Tracepoint %d at %s %s eval reports error %d",
1308 tpoint->number, paddress (tpoint->address), which, rtype);
1309
1310 #ifdef IN_PROCESS_AGENT
1311 /* Only record the first error we get. */
1312 if (cmpxchg (&expr_eval_result,
1313 expr_eval_no_error,
1314 rtype) != expr_eval_no_error)
1315 return;
1316 #else
1317 if (expr_eval_result != expr_eval_no_error)
1318 return;
1319 #endif
1320
1321 error_tracepoint = tpoint;
1322 }
1323
1324 /* Trace buffer management. */
1325
1326 static void
1327 clear_trace_buffer (void)
1328 {
1329 trace_buffer_start = trace_buffer_lo;
1330 trace_buffer_free = trace_buffer_lo;
1331 trace_buffer_end_free = trace_buffer_hi;
1332 trace_buffer_wrap = trace_buffer_hi;
1333 /* A traceframe with zeroed fields marks the end of trace data. */
1334 ((struct traceframe *) trace_buffer_free)->tpnum = 0;
1335 ((struct traceframe *) trace_buffer_free)->data_size = 0;
1336 traceframe_read_count = traceframe_write_count = 0;
1337 traceframes_created = 0;
1338 }
1339
1340 #ifndef IN_PROCESS_AGENT
1341
1342 static void
1343 clear_inferior_trace_buffer (void)
1344 {
1345 CORE_ADDR ipa_trace_buffer_lo;
1346 CORE_ADDR ipa_trace_buffer_hi;
1347 struct traceframe ipa_traceframe = { 0 };
1348 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
1349
1350 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
1351 &ipa_trace_buffer_lo);
1352 read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
1353 &ipa_trace_buffer_hi);
1354
1355 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
1356 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
1357 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
1358 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
1359
1360 /* A traceframe with zeroed fields marks the end of trace data. */
1361 target_write_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
1362 (unsigned char *) &ipa_trace_buffer_ctrl,
1363 sizeof (ipa_trace_buffer_ctrl));
1364
1365 write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
1366
1367 /* A traceframe with zeroed fields marks the end of trace data. */
1368 target_write_memory (ipa_trace_buffer_lo,
1369 (unsigned char *) &ipa_traceframe,
1370 sizeof (ipa_traceframe));
1371
1372 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
1373 write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
1374 write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
1375 }
1376
1377 #endif
1378
1379 static void
1380 init_trace_buffer (LONGEST bufsize)
1381 {
1382 size_t alloc_size;
1383
1384 trace_buffer_size = bufsize;
1385
1386 /* Make sure to internally allocate at least space for the EOB
1387 marker. */
1388 alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
1389 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
1390 trace_buffer_lo = (unsigned char *) xrealloc (trace_buffer_lo, alloc_size);
1391
1392 trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
1393
1394 clear_trace_buffer ();
1395 }
1396
1397 #ifdef IN_PROCESS_AGENT
1398
1399 /* This is needed for -Wmissing-declarations. */
1400 IP_AGENT_EXPORT_FUNC void about_to_request_buffer_space (void);
1401
1402 IP_AGENT_EXPORT_FUNC void
1403 about_to_request_buffer_space (void)
1404 {
1405 /* GDBserver places breakpoint here while it goes about to flush
1406 data at random times. */
1407 UNKNOWN_SIDE_EFFECTS();
1408 }
1409
1410 #endif
1411
1412 /* Carve out a piece of the trace buffer, returning NULL in case of
1413 failure. */
1414
1415 static void *
1416 trace_buffer_alloc (size_t amt)
1417 {
1418 unsigned char *rslt;
1419 struct trace_buffer_control *tbctrl;
1420 unsigned int curr;
1421 #ifdef IN_PROCESS_AGENT
1422 unsigned int prev, prev_filtered;
1423 unsigned int commit_count;
1424 unsigned int commit;
1425 unsigned int readout;
1426 #else
1427 struct traceframe *oldest;
1428 unsigned char *new_start;
1429 #endif
1430
1431 trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
1432 (long) amt, (long) sizeof (struct traceframe));
1433
1434 /* Account for the EOB marker. */
1435 amt += TRACEFRAME_EOB_MARKER_SIZE;
1436
1437 #ifdef IN_PROCESS_AGENT
1438 again:
1439 memory_barrier ();
1440
1441 /* Read the current token and extract the index to try to write to,
1442 storing it in CURR. */
1443 prev = trace_buffer_ctrl_curr;
1444 prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
1445 curr = prev_filtered + 1;
1446 if (curr > 2)
1447 curr = 0;
1448
1449 about_to_request_buffer_space ();
1450
1451 /* Start out with a copy of the current state. GDBserver may be
1452 midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
1453 be able to commit anyway if that happens. */
1454 trace_buffer_ctrl[curr]
1455 = trace_buffer_ctrl[prev_filtered];
1456 trace_debug ("trying curr=%u", curr);
1457 #else
1458 /* The GDBserver's agent doesn't need all that syncing, and always
1459 updates TCB 0 (there's only one, mind you). */
1460 curr = 0;
1461 #endif
1462 tbctrl = &trace_buffer_ctrl[curr];
1463
1464 /* Offsets are easier to grok for debugging than raw addresses,
1465 especially for the small trace buffer sizes that are useful for
1466 testing. */
1467 trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
1468 curr,
1469 (int) (tbctrl->start - trace_buffer_lo),
1470 (int) (tbctrl->free - trace_buffer_lo),
1471 (int) (tbctrl->end_free - trace_buffer_lo),
1472 (int) (tbctrl->wrap - trace_buffer_lo),
1473 (int) (trace_buffer_hi - trace_buffer_lo));
1474
1475 /* The algorithm here is to keep trying to get a contiguous block of
1476 the requested size, possibly discarding older traceframes to free
1477 up space. Since free space might come in one or two pieces,
1478 depending on whether discarded traceframes wrapped around at the
1479 high end of the buffer, we test both pieces after each
1480 discard. */
1481 while (1)
1482 {
1483 /* First, if we have two free parts, try the upper one first. */
1484 if (tbctrl->end_free < tbctrl->free)
1485 {
1486 if (tbctrl->free + amt <= trace_buffer_hi)
1487 /* We have enough in the upper part. */
1488 break;
1489 else
1490 {
1491 /* Our high part of free space wasn't enough. Give up
1492 on it for now, set wraparound. We will recover the
1493 space later, if/when the wrapped-around traceframe is
1494 discarded. */
1495 trace_debug ("Upper part too small, setting wraparound");
1496 tbctrl->wrap = tbctrl->free;
1497 tbctrl->free = trace_buffer_lo;
1498 }
1499 }
1500
1501 /* The normal case. */
1502 if (tbctrl->free + amt <= tbctrl->end_free)
1503 break;
1504
1505 #ifdef IN_PROCESS_AGENT
1506 /* The IP Agent's buffer is always circular. It isn't used
1507 currently, but `circular_trace_buffer' could represent
1508 GDBserver's mode. If we didn't find space, ask GDBserver to
1509 flush. */
1510
1511 flush_trace_buffer ();
1512 memory_barrier ();
1513 if (tracing)
1514 {
1515 trace_debug ("gdbserver flushed buffer, retrying");
1516 goto again;
1517 }
1518
1519 /* GDBserver cancelled the tracing. Bail out as well. */
1520 return NULL;
1521 #else
1522 /* If we're here, then neither part is big enough, and
1523 non-circular trace buffers are now full. */
1524 if (!circular_trace_buffer)
1525 {
1526 trace_debug ("Not enough space in the trace buffer");
1527 return NULL;
1528 }
1529
1530 trace_debug ("Need more space in the trace buffer");
1531
1532 /* If we have a circular buffer, we can try discarding the
1533 oldest traceframe and see if that helps. */
1534 oldest = FIRST_TRACEFRAME ();
1535 if (oldest->tpnum == 0)
1536 {
1537 /* Not good; we have no traceframes to free. Perhaps we're
1538 asking for a block that is larger than the buffer? In
1539 any case, give up. */
1540 trace_debug ("No traceframes to discard");
1541 return NULL;
1542 }
1543
1544 /* We don't run this code in the in-process agent currently.
1545 E.g., we could leave the in-process agent in autonomous
1546 circular mode if we only have fast tracepoints. If we do
1547 that, then this bit becomes racy with GDBserver, which also
1548 writes to this counter. */
1549 --traceframe_write_count;
1550
1551 new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
1552 /* If we freed the traceframe that wrapped around, go back
1553 to the non-wrap case. */
1554 if (new_start < tbctrl->start)
1555 {
1556 trace_debug ("Discarding past the wraparound");
1557 tbctrl->wrap = trace_buffer_hi;
1558 }
1559 tbctrl->start = new_start;
1560 tbctrl->end_free = tbctrl->start;
1561
1562 trace_debug ("Discarded a traceframe\n"
1563 "Trace buffer [%d], start=%d free=%d "
1564 "endfree=%d wrap=%d hi=%d",
1565 curr,
1566 (int) (tbctrl->start - trace_buffer_lo),
1567 (int) (tbctrl->free - trace_buffer_lo),
1568 (int) (tbctrl->end_free - trace_buffer_lo),
1569 (int) (tbctrl->wrap - trace_buffer_lo),
1570 (int) (trace_buffer_hi - trace_buffer_lo));
1571
1572 /* Now go back around the loop. The discard might have resulted
1573 in either one or two pieces of free space, so we want to try
1574 both before freeing any more traceframes. */
1575 #endif
1576 }
1577
1578 /* If we get here, we know we can provide the asked-for space. */
1579
1580 rslt = tbctrl->free;
1581
1582 /* Adjust the request back down, now that we know we have space for
1583 the marker, but don't commit to AMT yet, we may still need to
1584 restart the operation if GDBserver touches the trace buffer
1585 (obviously only important in the in-process agent's version). */
1586 tbctrl->free += (amt - sizeof (struct traceframe));
1587
1588 /* Or not. If GDBserver changed the trace buffer behind our back,
1589 we get to restart a new allocation attempt. */
1590
1591 #ifdef IN_PROCESS_AGENT
1592 /* Build the tentative token. */
1593 commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
1594 & GDBSERVER_FLUSH_COUNT_MASK_CURR);
1595 commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
1596 | commit_count
1597 | curr);
1598
1599 /* Try to commit it. */
1600 readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
1601 if (readout != prev)
1602 {
1603 trace_debug ("GDBserver has touched the trace buffer, restarting."
1604 " (prev=%08x, commit=%08x, readout=%08x)",
1605 prev, commit, readout);
1606 goto again;
1607 }
1608
1609 /* Hold your horses here. Even if that change was committed,
1610 GDBserver could come in, and clobber it. We need to hold to be
1611 able to tell if GDBserver clobbers before or after we committed
1612 the change. Whenever GDBserver goes about touching the IPA
1613 buffer, it sets a breakpoint in this routine, so we have a sync
1614 point here. */
1615 about_to_request_buffer_space ();
1616
1617 /* Check if the change has been effective, even if GDBserver stopped
1618 us at the breakpoint. */
1619
1620 {
1621 unsigned int refetch;
1622
1623 memory_barrier ();
1624
1625 refetch = trace_buffer_ctrl_curr;
1626
1627 if (refetch == commit
1628 || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
1629 {
1630 /* effective */
1631 trace_debug ("change is effective: (prev=%08x, commit=%08x, "
1632 "readout=%08x, refetch=%08x)",
1633 prev, commit, readout, refetch);
1634 }
1635 else
1636 {
1637 trace_debug ("GDBserver has touched the trace buffer, not effective."
1638 " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
1639 prev, commit, readout, refetch);
1640 goto again;
1641 }
1642 }
1643 #endif
1644
1645 /* We have a new piece of the trace buffer. Hurray! */
1646
1647 /* Add an EOB marker just past this allocation. */
1648 ((struct traceframe *) tbctrl->free)->tpnum = 0;
1649 ((struct traceframe *) tbctrl->free)->data_size = 0;
1650
1651 /* Adjust the request back down, now that we know we have space for
1652 the marker. */
1653 amt -= sizeof (struct traceframe);
1654
1655 if (debug_threads)
1656 {
1657 trace_debug ("Allocated %d bytes", (int) amt);
1658 trace_debug ("Trace buffer [%d] start=%d free=%d "
1659 "endfree=%d wrap=%d hi=%d",
1660 curr,
1661 (int) (tbctrl->start - trace_buffer_lo),
1662 (int) (tbctrl->free - trace_buffer_lo),
1663 (int) (tbctrl->end_free - trace_buffer_lo),
1664 (int) (tbctrl->wrap - trace_buffer_lo),
1665 (int) (trace_buffer_hi - trace_buffer_lo));
1666 }
1667
1668 return rslt;
1669 }
1670
1671 #ifndef IN_PROCESS_AGENT
1672
1673 /* Return the total free space. This is not necessarily the largest
1674 block we can allocate, because of the two-part case. */
1675
1676 static int
1677 free_space (void)
1678 {
1679 if (trace_buffer_free <= trace_buffer_end_free)
1680 return trace_buffer_end_free - trace_buffer_free;
1681 else
1682 return ((trace_buffer_end_free - trace_buffer_lo)
1683 + (trace_buffer_hi - trace_buffer_free));
1684 }
1685
1686 /* An 'S' in continuation packets indicates remainder are for
1687 while-stepping. */
1688
1689 static int seen_step_action_flag;
1690
1691 /* Create a tracepoint (location) with given number and address. Add this
1692 new tracepoint to list and sort this list. */
1693
1694 static struct tracepoint *
1695 add_tracepoint (int num, CORE_ADDR addr)
1696 {
1697 struct tracepoint *tpoint, **tp_next;
1698
1699 tpoint = XNEW (struct tracepoint);
1700 tpoint->number = num;
1701 tpoint->address = addr;
1702 tpoint->numactions = 0;
1703 tpoint->actions = NULL;
1704 tpoint->actions_str = NULL;
1705 tpoint->cond = NULL;
1706 tpoint->num_step_actions = 0;
1707 tpoint->step_actions = NULL;
1708 tpoint->step_actions_str = NULL;
1709 /* Start all off as regular (slow) tracepoints. */
1710 tpoint->type = trap_tracepoint;
1711 tpoint->orig_size = -1;
1712 tpoint->source_strings = NULL;
1713 tpoint->compiled_cond = 0;
1714 tpoint->handle = NULL;
1715 tpoint->next = NULL;
1716
1717 /* Find a place to insert this tracepoint into list in order to keep
1718 the tracepoint list still in the ascending order. There may be
1719 multiple tracepoints at the same address as TPOINT's, and this
1720 guarantees TPOINT is inserted after all the tracepoints which are
1721 set at the same address. For example, fast tracepoints A, B, C are
1722 set at the same address, and D is to be insert at the same place as
1723 well,
1724
1725 -->| A |--> | B |-->| C |->...
1726
1727 One jump pad was created for tracepoint A, B, and C, and the target
1728 address of A is referenced/used in jump pad. So jump pad will let
1729 inferior jump to A. If D is inserted in front of A, like this,
1730
1731 -->| D |-->| A |--> | B |-->| C |->...
1732
1733 without updating jump pad, D is not reachable during collect, which
1734 is wrong. As we can see, the order of B, C and D doesn't matter, but
1735 A should always be the `first' one. */
1736 for (tp_next = &tracepoints;
1737 (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
1738 tp_next = &(*tp_next)->next)
1739 ;
1740 tpoint->next = *tp_next;
1741 *tp_next = tpoint;
1742 last_tracepoint = tpoint;
1743
1744 seen_step_action_flag = 0;
1745
1746 return tpoint;
1747 }
1748
1749 #ifndef IN_PROCESS_AGENT
1750
1751 /* Return the tracepoint with the given number and address, or NULL. */
1752
1753 static struct tracepoint *
1754 find_tracepoint (int id, CORE_ADDR addr)
1755 {
1756 struct tracepoint *tpoint;
1757
1758 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
1759 if (tpoint->number == id && tpoint->address == addr)
1760 return tpoint;
1761
1762 return NULL;
1763 }
1764
1765 /* Remove TPOINT from global list. */
1766
1767 static void
1768 remove_tracepoint (struct tracepoint *tpoint)
1769 {
1770 struct tracepoint *tp, *tp_prev;
1771
1772 for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
1773 tp_prev = tp, tp = tp->next)
1774 ;
1775
1776 if (tp)
1777 {
1778 if (tp_prev)
1779 tp_prev->next = tp->next;
1780 else
1781 tracepoints = tp->next;
1782
1783 xfree (tp);
1784 }
1785 }
1786
1787 /* There may be several tracepoints with the same number (because they
1788 are "locations", in GDB parlance); return the next one after the
1789 given tracepoint, or search from the beginning of the list if the
1790 first argument is NULL. */
1791
1792 static struct tracepoint *
1793 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
1794 {
1795 struct tracepoint *tpoint;
1796
1797 if (prev_tp)
1798 tpoint = prev_tp->next;
1799 else
1800 tpoint = tracepoints;
1801 for (; tpoint; tpoint = tpoint->next)
1802 if (tpoint->number == num)
1803 return tpoint;
1804
1805 return NULL;
1806 }
1807
1808 #endif
1809
1810 /* Append another action to perform when the tracepoint triggers. */
1811
1812 static void
1813 add_tracepoint_action (struct tracepoint *tpoint, const char *packet)
1814 {
1815 const char *act;
1816
1817 if (*packet == 'S')
1818 {
1819 seen_step_action_flag = 1;
1820 ++packet;
1821 }
1822
1823 act = packet;
1824
1825 while (*act)
1826 {
1827 const char *act_start = act;
1828 struct tracepoint_action *action = NULL;
1829
1830 switch (*act)
1831 {
1832 case 'M':
1833 {
1834 struct collect_memory_action *maction =
1835 XNEW (struct collect_memory_action);
1836 ULONGEST basereg;
1837 int is_neg;
1838
1839 maction->base.type = *act;
1840 action = &maction->base;
1841
1842 ++act;
1843 is_neg = (*act == '-');
1844 if (*act == '-')
1845 ++act;
1846 act = unpack_varlen_hex (act, &basereg);
1847 ++act;
1848 act = unpack_varlen_hex (act, &maction->addr);
1849 ++act;
1850 act = unpack_varlen_hex (act, &maction->len);
1851 maction->basereg = (is_neg
1852 ? - (int) basereg
1853 : (int) basereg);
1854 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
1855 pulongest (maction->len),
1856 paddress (maction->addr), maction->basereg);
1857 break;
1858 }
1859 case 'R':
1860 {
1861 struct collect_registers_action *raction =
1862 XNEW (struct collect_registers_action);
1863
1864 raction->base.type = *act;
1865 action = &raction->base;
1866
1867 trace_debug ("Want to collect registers");
1868 ++act;
1869 /* skip past hex digits of mask for now */
1870 while (isxdigit(*act))
1871 ++act;
1872 break;
1873 }
1874 case 'S':
1875 trace_debug ("Unexpected step action, ignoring");
1876 ++act;
1877 break;
1878 case 'X':
1879 {
1880 struct eval_expr_action *xaction = XNEW (struct eval_expr_action);
1881
1882 xaction->base.type = *act;
1883 action = &xaction->base;
1884
1885 trace_debug ("Want to evaluate expression");
1886 xaction->expr = gdb_parse_agent_expr (&act);
1887 break;
1888 }
1889 default:
1890 trace_debug ("unknown trace action '%c', ignoring...", *act);
1891 break;
1892 case '-':
1893 break;
1894 }
1895
1896 if (action == NULL)
1897 break;
1898
1899 if (seen_step_action_flag)
1900 {
1901 tpoint->num_step_actions++;
1902
1903 tpoint->step_actions
1904 = XRESIZEVEC (struct tracepoint_action *, tpoint->step_actions,
1905 tpoint->num_step_actions);
1906 tpoint->step_actions_str
1907 = XRESIZEVEC (char *, tpoint->step_actions_str,
1908 tpoint->num_step_actions);
1909 tpoint->step_actions[tpoint->num_step_actions - 1] = action;
1910 tpoint->step_actions_str[tpoint->num_step_actions - 1]
1911 = savestring (act_start, act - act_start);
1912 }
1913 else
1914 {
1915 tpoint->numactions++;
1916 tpoint->actions
1917 = XRESIZEVEC (struct tracepoint_action *, tpoint->actions,
1918 tpoint->numactions);
1919 tpoint->actions_str
1920 = XRESIZEVEC (char *, tpoint->actions_str, tpoint->numactions);
1921 tpoint->actions[tpoint->numactions - 1] = action;
1922 tpoint->actions_str[tpoint->numactions - 1]
1923 = savestring (act_start, act - act_start);
1924 }
1925 }
1926 }
1927
1928 #endif
1929
1930 /* Find or create a trace state variable with the given number. */
1931
1932 static struct trace_state_variable *
1933 get_trace_state_variable (int num)
1934 {
1935 struct trace_state_variable *tsv;
1936
1937 #ifdef IN_PROCESS_AGENT
1938 /* Search for an existing variable. */
1939 for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
1940 if (tsv->number == num)
1941 return tsv;
1942 #endif
1943
1944 /* Search for an existing variable. */
1945 for (tsv = trace_state_variables; tsv; tsv = tsv->next)
1946 if (tsv->number == num)
1947 return tsv;
1948
1949 return NULL;
1950 }
1951
1952 /* Find or create a trace state variable with the given number. */
1953
1954 static struct trace_state_variable *
1955 create_trace_state_variable (int num, int gdb)
1956 {
1957 struct trace_state_variable *tsv;
1958
1959 tsv = get_trace_state_variable (num);
1960 if (tsv != NULL)
1961 return tsv;
1962
1963 /* Create a new variable. */
1964 tsv = XNEW (struct trace_state_variable);
1965 tsv->number = num;
1966 tsv->initial_value = 0;
1967 tsv->value = 0;
1968 tsv->getter = NULL;
1969 tsv->name = NULL;
1970 #ifdef IN_PROCESS_AGENT
1971 if (!gdb)
1972 {
1973 tsv->next = alloced_trace_state_variables;
1974 alloced_trace_state_variables = tsv;
1975 }
1976 else
1977 #endif
1978 {
1979 tsv->next = trace_state_variables;
1980 trace_state_variables = tsv;
1981 }
1982 return tsv;
1983 }
1984
1985 /* This is needed for -Wmissing-declarations. */
1986 IP_AGENT_EXPORT_FUNC LONGEST get_trace_state_variable_value (int num);
1987
1988 IP_AGENT_EXPORT_FUNC LONGEST
1989 get_trace_state_variable_value (int num)
1990 {
1991 struct trace_state_variable *tsv;
1992
1993 tsv = get_trace_state_variable (num);
1994
1995 if (!tsv)
1996 {
1997 trace_debug ("No trace state variable %d, skipping value get", num);
1998 return 0;
1999 }
2000
2001 /* Call a getter function if we have one. While it's tempting to
2002 set up something to only call the getter once per tracepoint hit,
2003 it could run afoul of thread races. Better to let the getter
2004 handle it directly, if necessary to worry about it. */
2005 if (tsv->getter)
2006 tsv->value = (tsv->getter) ();
2007
2008 trace_debug ("get_trace_state_variable_value(%d) ==> %s",
2009 num, plongest (tsv->value));
2010
2011 return tsv->value;
2012 }
2013
2014 /* This is needed for -Wmissing-declarations. */
2015 IP_AGENT_EXPORT_FUNC void set_trace_state_variable_value (int num,
2016 LONGEST val);
2017
2018 IP_AGENT_EXPORT_FUNC void
2019 set_trace_state_variable_value (int num, LONGEST val)
2020 {
2021 struct trace_state_variable *tsv;
2022
2023 tsv = get_trace_state_variable (num);
2024
2025 if (!tsv)
2026 {
2027 trace_debug ("No trace state variable %d, skipping value set", num);
2028 return;
2029 }
2030
2031 tsv->value = val;
2032 }
2033
2034 LONGEST
2035 agent_get_trace_state_variable_value (int num)
2036 {
2037 return get_trace_state_variable_value (num);
2038 }
2039
2040 void
2041 agent_set_trace_state_variable_value (int num, LONGEST val)
2042 {
2043 set_trace_state_variable_value (num, val);
2044 }
2045
2046 static void
2047 set_trace_state_variable_name (int num, const char *name)
2048 {
2049 struct trace_state_variable *tsv;
2050
2051 tsv = get_trace_state_variable (num);
2052
2053 if (!tsv)
2054 {
2055 trace_debug ("No trace state variable %d, skipping name set", num);
2056 return;
2057 }
2058
2059 tsv->name = (char *) name;
2060 }
2061
2062 static void
2063 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
2064 {
2065 struct trace_state_variable *tsv;
2066
2067 tsv = get_trace_state_variable (num);
2068
2069 if (!tsv)
2070 {
2071 trace_debug ("No trace state variable %d, skipping getter set", num);
2072 return;
2073 }
2074
2075 tsv->getter = getter;
2076 }
2077
2078 /* Add a raw traceframe for the given tracepoint. */
2079
2080 static struct traceframe *
2081 add_traceframe (struct tracepoint *tpoint)
2082 {
2083 struct traceframe *tframe;
2084
2085 tframe
2086 = (struct traceframe *) trace_buffer_alloc (sizeof (struct traceframe));
2087
2088 if (tframe == NULL)
2089 return NULL;
2090
2091 tframe->tpnum = tpoint->number;
2092 tframe->data_size = 0;
2093
2094 return tframe;
2095 }
2096
2097 /* Add a block to the traceframe currently being worked on. */
2098
2099 static unsigned char *
2100 add_traceframe_block (struct traceframe *tframe,
2101 struct tracepoint *tpoint, int amt)
2102 {
2103 unsigned char *block;
2104
2105 if (!tframe)
2106 return NULL;
2107
2108 block = (unsigned char *) trace_buffer_alloc (amt);
2109
2110 if (!block)
2111 return NULL;
2112
2113 gdb_assert (tframe->tpnum == tpoint->number);
2114
2115 tframe->data_size += amt;
2116 tpoint->traceframe_usage += amt;
2117
2118 return block;
2119 }
2120
2121 /* Flag that the current traceframe is finished. */
2122
2123 static void
2124 finish_traceframe (struct traceframe *tframe)
2125 {
2126 ++traceframe_write_count;
2127 ++traceframes_created;
2128 }
2129
2130 #ifndef IN_PROCESS_AGENT
2131
2132 /* Given a traceframe number NUM, find the NUMth traceframe in the
2133 buffer. */
2134
2135 static struct traceframe *
2136 find_traceframe (int num)
2137 {
2138 struct traceframe *tframe;
2139 int tfnum = 0;
2140
2141 for (tframe = FIRST_TRACEFRAME ();
2142 tframe->tpnum != 0;
2143 tframe = NEXT_TRACEFRAME (tframe))
2144 {
2145 if (tfnum == num)
2146 return tframe;
2147 ++tfnum;
2148 }
2149
2150 return NULL;
2151 }
2152
2153 static CORE_ADDR
2154 get_traceframe_address (struct traceframe *tframe)
2155 {
2156 CORE_ADDR addr;
2157 struct tracepoint *tpoint;
2158
2159 addr = traceframe_get_pc (tframe);
2160
2161 if (addr)
2162 return addr;
2163
2164 /* Fallback strategy, will be incorrect for while-stepping frames
2165 and multi-location tracepoints. */
2166 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
2167 return tpoint->address;
2168 }
2169
2170 /* Search for the next traceframe whose address is inside or outside
2171 the given range. */
2172
2173 static struct traceframe *
2174 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
2175 int *tfnump)
2176 {
2177 client_state &cs = get_client_state ();
2178 struct traceframe *tframe;
2179 CORE_ADDR tfaddr;
2180
2181 *tfnump = cs.current_traceframe + 1;
2182 tframe = find_traceframe (*tfnump);
2183 /* The search is not supposed to wrap around. */
2184 if (!tframe)
2185 {
2186 *tfnump = -1;
2187 return NULL;
2188 }
2189
2190 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2191 {
2192 tfaddr = get_traceframe_address (tframe);
2193 if (inside_p
2194 ? (lo <= tfaddr && tfaddr <= hi)
2195 : (lo > tfaddr || tfaddr > hi))
2196 return tframe;
2197 ++*tfnump;
2198 }
2199
2200 *tfnump = -1;
2201 return NULL;
2202 }
2203
2204 /* Search for the next traceframe recorded by the given tracepoint.
2205 Note that for multi-location tracepoints, this will find whatever
2206 location appears first. */
2207
2208 static struct traceframe *
2209 find_next_traceframe_by_tracepoint (int num, int *tfnump)
2210 {
2211 client_state &cs = get_client_state ();
2212 struct traceframe *tframe;
2213
2214 *tfnump = cs.current_traceframe + 1;
2215 tframe = find_traceframe (*tfnump);
2216 /* The search is not supposed to wrap around. */
2217 if (!tframe)
2218 {
2219 *tfnump = -1;
2220 return NULL;
2221 }
2222
2223 for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
2224 {
2225 if (tframe->tpnum == num)
2226 return tframe;
2227 ++*tfnump;
2228 }
2229
2230 *tfnump = -1;
2231 return NULL;
2232 }
2233
2234 #endif
2235
2236 #ifndef IN_PROCESS_AGENT
2237
2238 /* Clear all past trace state. */
2239
2240 static void
2241 cmd_qtinit (char *packet)
2242 {
2243 client_state &cs = get_client_state ();
2244 struct trace_state_variable *tsv, *prev, *next;
2245
2246 /* Can't do this command without a pid attached. */
2247 if (current_thread == NULL)
2248 {
2249 write_enn (packet);
2250 return;
2251 }
2252
2253 /* Make sure we don't try to read from a trace frame. */
2254 cs.current_traceframe = -1;
2255
2256 stop_tracing ();
2257
2258 trace_debug ("Initializing the trace");
2259
2260 clear_installed_tracepoints ();
2261 clear_readonly_regions ();
2262
2263 tracepoints = NULL;
2264 last_tracepoint = NULL;
2265
2266 /* Clear out any leftover trace state variables. Ones with target
2267 defined getters should be kept however. */
2268 prev = NULL;
2269 tsv = trace_state_variables;
2270 while (tsv)
2271 {
2272 trace_debug ("Looking at var %d", tsv->number);
2273 if (tsv->getter == NULL)
2274 {
2275 next = tsv->next;
2276 if (prev)
2277 prev->next = next;
2278 else
2279 trace_state_variables = next;
2280 trace_debug ("Deleting var %d", tsv->number);
2281 free (tsv);
2282 tsv = next;
2283 }
2284 else
2285 {
2286 prev = tsv;
2287 tsv = tsv->next;
2288 }
2289 }
2290
2291 clear_trace_buffer ();
2292 clear_inferior_trace_buffer ();
2293
2294 write_ok (packet);
2295 }
2296
2297 /* Restore the program to its pre-tracing state. This routine may be called
2298 in error situations, so it needs to be careful about only restoring
2299 from known-valid bits. */
2300
2301 static void
2302 clear_installed_tracepoints (void)
2303 {
2304 struct tracepoint *tpoint;
2305
2306 target_pause_all (true);
2307
2308 /* Restore any bytes overwritten by tracepoints. */
2309 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
2310 {
2311 /* Catch the case where we might try to remove a tracepoint that
2312 was never actually installed. */
2313 if (tpoint->handle == NULL)
2314 {
2315 trace_debug ("Tracepoint %d at 0x%s was "
2316 "never installed, nothing to clear",
2317 tpoint->number, paddress (tpoint->address));
2318 continue;
2319 }
2320
2321 switch (tpoint->type)
2322 {
2323 case trap_tracepoint:
2324 {
2325 struct breakpoint *bp
2326 = (struct breakpoint *) tpoint->handle;
2327
2328 delete_breakpoint (bp);
2329 }
2330 break;
2331 case fast_tracepoint:
2332 {
2333 struct fast_tracepoint_jump *jump
2334 = (struct fast_tracepoint_jump *) tpoint->handle;
2335
2336 delete_fast_tracepoint_jump (jump);
2337 }
2338 break;
2339 }
2340
2341 tpoint->handle = NULL;
2342 }
2343
2344 target_unpause_all (true);
2345 }
2346
2347 /* Parse a packet that defines a tracepoint. */
2348
2349 static void
2350 cmd_qtdp (char *own_buf)
2351 {
2352 int tppacket;
2353 /* Whether there is a trailing hyphen at the end of the QTDP packet. */
2354 int trail_hyphen = 0;
2355 ULONGEST num;
2356 ULONGEST addr;
2357 ULONGEST count;
2358 struct tracepoint *tpoint;
2359 const char *packet = own_buf;
2360
2361 packet += strlen ("QTDP:");
2362
2363 /* A hyphen at the beginning marks a packet specifying actions for a
2364 tracepoint already supplied. */
2365 tppacket = 1;
2366 if (*packet == '-')
2367 {
2368 tppacket = 0;
2369 ++packet;
2370 }
2371 packet = unpack_varlen_hex (packet, &num);
2372 ++packet; /* skip a colon */
2373 packet = unpack_varlen_hex (packet, &addr);
2374 ++packet; /* skip a colon */
2375
2376 /* See if we already have this tracepoint. */
2377 tpoint = find_tracepoint (num, addr);
2378
2379 if (tppacket)
2380 {
2381 /* Duplicate tracepoints are never allowed. */
2382 if (tpoint)
2383 {
2384 trace_debug ("Tracepoint error: tracepoint %d"
2385 " at 0x%s already exists",
2386 (int) num, paddress (addr));
2387 write_enn (own_buf);
2388 return;
2389 }
2390
2391 tpoint = add_tracepoint (num, addr);
2392
2393 tpoint->enabled = (*packet == 'E');
2394 ++packet; /* skip 'E' */
2395 ++packet; /* skip a colon */
2396 packet = unpack_varlen_hex (packet, &count);
2397 tpoint->step_count = count;
2398 ++packet; /* skip a colon */
2399 packet = unpack_varlen_hex (packet, &count);
2400 tpoint->pass_count = count;
2401 /* See if we have any of the additional optional fields. */
2402 while (*packet == ':')
2403 {
2404 ++packet;
2405 if (*packet == 'F')
2406 {
2407 tpoint->type = fast_tracepoint;
2408 ++packet;
2409 packet = unpack_varlen_hex (packet, &count);
2410 tpoint->orig_size = count;
2411 }
2412 else if (*packet == 'X')
2413 {
2414 tpoint->cond = gdb_parse_agent_expr (&packet);
2415 }
2416 else if (*packet == '-')
2417 break;
2418 else if (*packet == '\0')
2419 break;
2420 else
2421 trace_debug ("Unknown optional tracepoint field");
2422 }
2423 if (*packet == '-')
2424 {
2425 trail_hyphen = 1;
2426 trace_debug ("Also has actions\n");
2427 }
2428
2429 trace_debug ("Defined %stracepoint %d at 0x%s, "
2430 "enabled %d step %" PRIu64 " pass %" PRIu64,
2431 tpoint->type == fast_tracepoint ? "fast " : "",
2432 tpoint->number, paddress (tpoint->address), tpoint->enabled,
2433 tpoint->step_count, tpoint->pass_count);
2434 }
2435 else if (tpoint)
2436 add_tracepoint_action (tpoint, packet);
2437 else
2438 {
2439 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2440 (int) num, paddress (addr));
2441 write_enn (own_buf);
2442 return;
2443 }
2444
2445 /* Install tracepoint during tracing only once for each tracepoint location.
2446 For each tracepoint loc, GDB may send multiple QTDP packets, and we can
2447 determine the last QTDP packet for one tracepoint location by checking
2448 trailing hyphen in QTDP packet. */
2449 if (tracing && !trail_hyphen)
2450 {
2451 struct tracepoint *tp = NULL;
2452
2453 /* Pause all threads temporarily while we patch tracepoints. */
2454 target_pause_all (false);
2455
2456 /* download_tracepoint will update global `tracepoints'
2457 list, so it is unsafe to leave threads in jump pad. */
2458 target_stabilize_threads ();
2459
2460 /* Freeze threads. */
2461 target_pause_all (true);
2462
2463
2464 if (tpoint->type != trap_tracepoint)
2465 {
2466 /* Find another fast tracepoint at the same address. */
2467 for (tp = tracepoints; tp; tp = tp->next)
2468 {
2469 if (tp->address == tpoint->address && tp->type == tpoint->type
2470 && tp->number != tpoint->number)
2471 break;
2472 }
2473
2474 /* TPOINT is installed at the same address as TP. */
2475 if (tp)
2476 {
2477 if (tpoint->type == fast_tracepoint)
2478 clone_fast_tracepoint (tpoint, tp);
2479 }
2480 }
2481
2482 if (use_agent && tpoint->type == fast_tracepoint
2483 && agent_capability_check (AGENT_CAPA_FAST_TRACE))
2484 {
2485 /* Download and install fast tracepoint by agent. */
2486 if (tracepoint_send_agent (tpoint) == 0)
2487 write_ok (own_buf);
2488 else
2489 {
2490 write_enn (own_buf);
2491 remove_tracepoint (tpoint);
2492 }
2493 }
2494 else
2495 {
2496 download_tracepoint (tpoint);
2497
2498 if (tpoint->type == trap_tracepoint || tp == NULL)
2499 {
2500 install_tracepoint (tpoint, own_buf);
2501 if (strcmp (own_buf, "OK") != 0)
2502 remove_tracepoint (tpoint);
2503 }
2504 else
2505 write_ok (own_buf);
2506 }
2507
2508 target_unpause_all (true);
2509 return;
2510 }
2511
2512 write_ok (own_buf);
2513 }
2514
2515 static void
2516 cmd_qtdpsrc (char *own_buf)
2517 {
2518 ULONGEST num, addr, start, slen;
2519 struct tracepoint *tpoint;
2520 const char *packet = own_buf;
2521 const char *saved;
2522 char *srctype, *src;
2523 size_t nbytes;
2524 struct source_string *last, *newlast;
2525
2526 packet += strlen ("QTDPsrc:");
2527
2528 packet = unpack_varlen_hex (packet, &num);
2529 ++packet; /* skip a colon */
2530 packet = unpack_varlen_hex (packet, &addr);
2531 ++packet; /* skip a colon */
2532
2533 /* See if we already have this tracepoint. */
2534 tpoint = find_tracepoint (num, addr);
2535
2536 if (!tpoint)
2537 {
2538 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
2539 (int) num, paddress (addr));
2540 write_enn (own_buf);
2541 return;
2542 }
2543
2544 saved = packet;
2545 packet = strchr (packet, ':');
2546 srctype = (char *) xmalloc (packet - saved + 1);
2547 memcpy (srctype, saved, packet - saved);
2548 srctype[packet - saved] = '\0';
2549 ++packet;
2550 packet = unpack_varlen_hex (packet, &start);
2551 ++packet; /* skip a colon */
2552 packet = unpack_varlen_hex (packet, &slen);
2553 ++packet; /* skip a colon */
2554 src = (char *) xmalloc (slen + 1);
2555 nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
2556 src[nbytes] = '\0';
2557
2558 newlast = XNEW (struct source_string);
2559 newlast->type = srctype;
2560 newlast->str = src;
2561 newlast->next = NULL;
2562 /* Always add a source string to the end of the list;
2563 this keeps sequences of actions/commands in the right
2564 order. */
2565 if (tpoint->source_strings)
2566 {
2567 for (last = tpoint->source_strings; last->next; last = last->next)
2568 ;
2569 last->next = newlast;
2570 }
2571 else
2572 tpoint->source_strings = newlast;
2573
2574 write_ok (own_buf);
2575 }
2576
2577 static void
2578 cmd_qtdv (char *own_buf)
2579 {
2580 ULONGEST num, val, builtin;
2581 char *varname;
2582 size_t nbytes;
2583 struct trace_state_variable *tsv;
2584 const char *packet = own_buf;
2585
2586 packet += strlen ("QTDV:");
2587
2588 packet = unpack_varlen_hex (packet, &num);
2589 ++packet; /* skip a colon */
2590 packet = unpack_varlen_hex (packet, &val);
2591 ++packet; /* skip a colon */
2592 packet = unpack_varlen_hex (packet, &builtin);
2593 ++packet; /* skip a colon */
2594
2595 nbytes = strlen (packet) / 2;
2596 varname = (char *) xmalloc (nbytes + 1);
2597 nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
2598 varname[nbytes] = '\0';
2599
2600 tsv = create_trace_state_variable (num, 1);
2601 tsv->initial_value = (LONGEST) val;
2602 tsv->name = varname;
2603
2604 set_trace_state_variable_value (num, (LONGEST) val);
2605
2606 write_ok (own_buf);
2607 }
2608
2609 static void
2610 cmd_qtenable_disable (char *own_buf, int enable)
2611 {
2612 const char *packet = own_buf;
2613 ULONGEST num, addr;
2614 struct tracepoint *tp;
2615
2616 packet += strlen (enable ? "QTEnable:" : "QTDisable:");
2617 packet = unpack_varlen_hex (packet, &num);
2618 ++packet; /* skip a colon */
2619 packet = unpack_varlen_hex (packet, &addr);
2620
2621 tp = find_tracepoint (num, addr);
2622
2623 if (tp)
2624 {
2625 if ((enable && tp->enabled) || (!enable && !tp->enabled))
2626 {
2627 trace_debug ("Tracepoint %d at 0x%s is already %s",
2628 (int) num, paddress (addr),
2629 enable ? "enabled" : "disabled");
2630 write_ok (own_buf);
2631 return;
2632 }
2633
2634 trace_debug ("%s tracepoint %d at 0x%s",
2635 enable ? "Enabling" : "Disabling",
2636 (int) num, paddress (addr));
2637
2638 tp->enabled = enable;
2639
2640 if (tp->type == fast_tracepoint)
2641 {
2642 int offset = offsetof (struct tracepoint, enabled);
2643 CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
2644
2645 int ret = write_inferior_int8 (obj_addr, enable);
2646 if (ret)
2647 {
2648 trace_debug ("Cannot write enabled flag into "
2649 "inferior process memory");
2650 write_enn (own_buf);
2651 return;
2652 }
2653 }
2654
2655 write_ok (own_buf);
2656 }
2657 else
2658 {
2659 trace_debug ("Tracepoint %d at 0x%s not found",
2660 (int) num, paddress (addr));
2661 write_enn (own_buf);
2662 }
2663 }
2664
2665 static void
2666 cmd_qtv (char *own_buf)
2667 {
2668 client_state &cs = get_client_state ();
2669 ULONGEST num;
2670 LONGEST val = 0;
2671 int err;
2672 char *packet = own_buf;
2673
2674 packet += strlen ("qTV:");
2675 unpack_varlen_hex (packet, &num);
2676
2677 if (cs.current_traceframe >= 0)
2678 {
2679 err = traceframe_read_tsv ((int) num, &val);
2680 if (err)
2681 {
2682 strcpy (own_buf, "U");
2683 return;
2684 }
2685 }
2686 /* Only make tsv's be undefined before the first trace run. After a
2687 trace run is over, the user might want to see the last value of
2688 the tsv, and it might not be available in a traceframe. */
2689 else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
2690 {
2691 strcpy (own_buf, "U");
2692 return;
2693 }
2694 else
2695 val = get_trace_state_variable_value (num);
2696
2697 sprintf (own_buf, "V%s", phex_nz (val, 0));
2698 }
2699
2700 /* Clear out the list of readonly regions. */
2701
2702 static void
2703 clear_readonly_regions (void)
2704 {
2705 struct readonly_region *roreg;
2706
2707 while (readonly_regions)
2708 {
2709 roreg = readonly_regions;
2710 readonly_regions = readonly_regions->next;
2711 free (roreg);
2712 }
2713 }
2714
2715 /* Parse the collection of address ranges whose contents GDB believes
2716 to be unchanging and so can be read directly from target memory
2717 even while looking at a traceframe. */
2718
2719 static void
2720 cmd_qtro (char *own_buf)
2721 {
2722 ULONGEST start, end;
2723 struct readonly_region *roreg;
2724 const char *packet = own_buf;
2725
2726 trace_debug ("Want to mark readonly regions");
2727
2728 clear_readonly_regions ();
2729
2730 packet += strlen ("QTro");
2731
2732 while (*packet == ':')
2733 {
2734 ++packet; /* skip a colon */
2735 packet = unpack_varlen_hex (packet, &start);
2736 ++packet; /* skip a comma */
2737 packet = unpack_varlen_hex (packet, &end);
2738
2739 roreg = XNEW (struct readonly_region);
2740 roreg->start = start;
2741 roreg->end = end;
2742 roreg->next = readonly_regions;
2743 readonly_regions = roreg;
2744 trace_debug ("Added readonly region from 0x%s to 0x%s",
2745 paddress (roreg->start), paddress (roreg->end));
2746 }
2747
2748 write_ok (own_buf);
2749 }
2750
2751 /* Test to see if the given range is in our list of readonly ranges.
2752 We only test for being entirely within a range, GDB is not going to
2753 send a single memory packet that spans multiple regions. */
2754
2755 int
2756 in_readonly_region (CORE_ADDR addr, ULONGEST length)
2757 {
2758 struct readonly_region *roreg;
2759
2760 for (roreg = readonly_regions; roreg; roreg = roreg->next)
2761 if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
2762 return 1;
2763
2764 return 0;
2765 }
2766
2767 static CORE_ADDR gdb_jump_pad_head;
2768
2769 /* Return the address of the next free jump space. */
2770
2771 static CORE_ADDR
2772 get_jump_space_head (void)
2773 {
2774 if (gdb_jump_pad_head == 0)
2775 {
2776 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
2777 &gdb_jump_pad_head))
2778 {
2779 internal_error ("error extracting jump_pad_buffer");
2780 }
2781 }
2782
2783 return gdb_jump_pad_head;
2784 }
2785
2786 /* Reserve USED bytes from the jump space. */
2787
2788 static void
2789 claim_jump_space (ULONGEST used)
2790 {
2791 trace_debug ("claim_jump_space reserves %s bytes at %s",
2792 pulongest (used), paddress (gdb_jump_pad_head));
2793 gdb_jump_pad_head += used;
2794 }
2795
2796 static CORE_ADDR trampoline_buffer_head = 0;
2797 static CORE_ADDR trampoline_buffer_tail;
2798
2799 /* Reserve USED bytes from the trampoline buffer and return the
2800 address of the start of the reserved space in TRAMPOLINE. Returns
2801 non-zero if the space is successfully claimed. */
2802
2803 int
2804 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
2805 {
2806 if (!trampoline_buffer_head)
2807 {
2808 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
2809 &trampoline_buffer_tail))
2810 {
2811 internal_error ("error extracting trampoline_buffer");
2812 }
2813
2814 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2815 &trampoline_buffer_head))
2816 {
2817 internal_error ("error extracting trampoline_buffer_end");
2818 }
2819 }
2820
2821 /* Start claiming space from the top of the trampoline space. If
2822 the space is located at the bottom of the virtual address space,
2823 this reduces the possibility that corruption will occur if a null
2824 pointer is used to write to memory. */
2825 if (trampoline_buffer_head - trampoline_buffer_tail < used)
2826 {
2827 trace_debug ("claim_trampoline_space failed to reserve %s bytes",
2828 pulongest (used));
2829 return 0;
2830 }
2831
2832 trampoline_buffer_head -= used;
2833
2834 trace_debug ("claim_trampoline_space reserves %s bytes at %s",
2835 pulongest (used), paddress (trampoline_buffer_head));
2836
2837 *trampoline = trampoline_buffer_head;
2838 return 1;
2839 }
2840
2841 /* Returns non-zero if there is space allocated for use in trampolines
2842 for fast tracepoints. */
2843
2844 int
2845 have_fast_tracepoint_trampoline_buffer (char *buf)
2846 {
2847 CORE_ADDR trampoline_end, errbuf;
2848
2849 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
2850 &trampoline_end))
2851 {
2852 internal_error ("error extracting trampoline_buffer_end");
2853 }
2854
2855 if (buf)
2856 {
2857 buf[0] = '\0';
2858 strcpy (buf, "was claiming");
2859 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
2860 &errbuf))
2861 {
2862 internal_error ("error extracting errbuf");
2863 }
2864
2865 read_inferior_memory (errbuf, (unsigned char *) buf, 100);
2866 }
2867
2868 return trampoline_end != 0;
2869 }
2870
2871 static void
2872 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
2873 {
2874 to->jump_pad = from->jump_pad;
2875 to->jump_pad_end = from->jump_pad_end;
2876 to->trampoline = from->trampoline;
2877 to->trampoline_end = from->trampoline_end;
2878 to->adjusted_insn_addr = from->adjusted_insn_addr;
2879 to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
2880 to->handle = from->handle;
2881
2882 gdb_assert (from->handle);
2883 inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
2884 }
2885
2886 #define MAX_JUMP_SIZE 20
2887
2888 /* Install fast tracepoint. Return 0 if successful, otherwise return
2889 non-zero. */
2890
2891 static int
2892 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
2893 {
2894 CORE_ADDR jentry, jump_entry;
2895 CORE_ADDR trampoline;
2896 CORE_ADDR collect;
2897 ULONGEST trampoline_size;
2898 int err = 0;
2899 /* The jump to the jump pad of the last fast tracepoint
2900 installed. */
2901 unsigned char fjump[MAX_JUMP_SIZE];
2902 ULONGEST fjump_size;
2903
2904 if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
2905 {
2906 trace_debug ("Requested a fast tracepoint on an instruction "
2907 "that is of less than the minimum length.");
2908 return 0;
2909 }
2910
2911 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_collect_ptr,
2912 &collect))
2913 {
2914 error ("error extracting gdb_collect_ptr");
2915 return 1;
2916 }
2917
2918 jentry = jump_entry = get_jump_space_head ();
2919
2920 trampoline = 0;
2921 trampoline_size = 0;
2922
2923 /* Install the jump pad. */
2924 err = target_install_fast_tracepoint_jump_pad
2925 (tpoint->obj_addr_on_target, tpoint->address, collect,
2926 ipa_sym_addrs.addr_collecting, tpoint->orig_size, &jentry,
2927 &trampoline, &trampoline_size, fjump, &fjump_size,
2928 &tpoint->adjusted_insn_addr, &tpoint->adjusted_insn_addr_end, errbuf);
2929
2930 if (err)
2931 return 1;
2932
2933 /* Wire it in. */
2934 tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
2935 fjump_size);
2936
2937 if (tpoint->handle != NULL)
2938 {
2939 tpoint->jump_pad = jump_entry;
2940 tpoint->jump_pad_end = jentry;
2941 tpoint->trampoline = trampoline;
2942 tpoint->trampoline_end = trampoline + trampoline_size;
2943
2944 /* Pad to 8-byte alignment. */
2945 jentry = ((jentry + 7) & ~0x7);
2946 claim_jump_space (jentry - jump_entry);
2947 }
2948
2949 return 0;
2950 }
2951
2952
2953 /* Install tracepoint TPOINT, and write reply message in OWN_BUF. */
2954
2955 static void
2956 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
2957 {
2958 tpoint->handle = NULL;
2959 *own_buf = '\0';
2960
2961 if (tpoint->type == trap_tracepoint)
2962 {
2963 /* Tracepoints are installed as memory breakpoints. Just go
2964 ahead and install the trap. The breakpoints module
2965 handles duplicated breakpoints, and the memory read
2966 routine handles un-patching traps from memory reads. */
2967 tpoint->handle = set_breakpoint_at (tpoint->address,
2968 tracepoint_handler);
2969 }
2970 else if (tpoint->type == fast_tracepoint)
2971 {
2972 if (!agent_loaded_p ())
2973 {
2974 trace_debug ("Requested a fast tracepoint, but fast "
2975 "tracepoints aren't supported.");
2976 write_e_ipa_not_loaded (own_buf);
2977 return;
2978 }
2979
2980 install_fast_tracepoint (tpoint, own_buf);
2981 }
2982 else
2983 internal_error ("Unknown tracepoint type");
2984
2985 if (tpoint->handle == NULL)
2986 {
2987 if (*own_buf == '\0')
2988 write_enn (own_buf);
2989 }
2990 else
2991 write_ok (own_buf);
2992 }
2993
2994 static void download_tracepoint_1 (struct tracepoint *tpoint);
2995
2996 static void
2997 cmd_qtstart (char *packet)
2998 {
2999 struct tracepoint *tpoint, *prev_ftpoint;
3000 CORE_ADDR tpptr = 0, prev_tpptr = 0;
3001
3002 trace_debug ("Starting the trace");
3003
3004 /* Pause all threads temporarily while we patch tracepoints. */
3005 target_pause_all (false);
3006
3007 /* Get threads out of jump pads. Safe to do here, since this is a
3008 top level command. And, required to do here, since we're
3009 deleting/rewriting jump pads. */
3010
3011 target_stabilize_threads ();
3012
3013 /* Freeze threads. */
3014 target_pause_all (true);
3015
3016 /* Sync the fast tracepoints list in the inferior ftlib. */
3017 if (agent_loaded_p ())
3018 download_trace_state_variables ();
3019
3020 /* No previous fast tpoint yet. */
3021 prev_ftpoint = NULL;
3022
3023 *packet = '\0';
3024
3025 if (agent_loaded_p ())
3026 {
3027 /* Tell IPA about the correct tdesc. */
3028 if (write_inferior_integer (ipa_sym_addrs.addr_ipa_tdesc_idx,
3029 target_get_ipa_tdesc_idx ()))
3030 error ("Error setting ipa_tdesc_idx variable in lib");
3031 }
3032
3033 /* Start out empty. */
3034 if (agent_loaded_p ())
3035 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, 0);
3036
3037 /* Download and install tracepoints. */
3038 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
3039 {
3040 /* Ensure all the hit counts start at zero. */
3041 tpoint->hit_count = 0;
3042 tpoint->traceframe_usage = 0;
3043
3044 if (tpoint->type == trap_tracepoint)
3045 {
3046 /* Tracepoints are installed as memory breakpoints. Just go
3047 ahead and install the trap. The breakpoints module
3048 handles duplicated breakpoints, and the memory read
3049 routine handles un-patching traps from memory reads. */
3050 tpoint->handle = set_breakpoint_at (tpoint->address,
3051 tracepoint_handler);
3052 }
3053 else if (tpoint->type == fast_tracepoint)
3054 {
3055 if (maybe_write_ipa_not_loaded (packet))
3056 {
3057 trace_debug ("Requested a fast tracepoint, but fast "
3058 "tracepoints aren't supported.");
3059 break;
3060 }
3061
3062 int use_agent_p
3063 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
3064
3065 if (prev_ftpoint != NULL
3066 && prev_ftpoint->address == tpoint->address)
3067 {
3068 if (use_agent_p)
3069 tracepoint_send_agent (tpoint);
3070 else
3071 download_tracepoint_1 (tpoint);
3072
3073 clone_fast_tracepoint (tpoint, prev_ftpoint);
3074 }
3075 else
3076 {
3077 /* Tracepoint is installed successfully? */
3078 int installed = 0;
3079
3080 /* Download and install fast tracepoint by agent. */
3081 if (use_agent_p)
3082 installed = !tracepoint_send_agent (tpoint);
3083 else
3084 {
3085 download_tracepoint_1 (tpoint);
3086 installed = !install_fast_tracepoint (tpoint, packet);
3087 }
3088
3089 if (installed)
3090 prev_ftpoint = tpoint;
3091 }
3092
3093 prev_tpptr = tpptr;
3094 tpptr = tpoint->obj_addr_on_target;
3095
3096 if (tpoint == tracepoints)
3097 /* First object in list, set the head pointer in the
3098 inferior. */
3099 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints, tpptr);
3100 else
3101 write_inferior_data_pointer (prev_tpptr
3102 + offsetof (struct tracepoint, next),
3103 tpptr);
3104 }
3105
3106 /* Any failure in the inner loop is sufficient cause to give
3107 up. */
3108 if (tpoint->handle == NULL)
3109 break;
3110 }
3111
3112 /* Any error in tracepoint insertion is unacceptable; better to
3113 address the problem now, than end up with a useless or misleading
3114 trace run. */
3115 if (tpoint != NULL)
3116 {
3117 clear_installed_tracepoints ();
3118 if (*packet == '\0')
3119 write_enn (packet);
3120 target_unpause_all (true);
3121 return;
3122 }
3123
3124 stopping_tracepoint = NULL;
3125 trace_buffer_is_full = 0;
3126 expr_eval_result = expr_eval_no_error;
3127 error_tracepoint = NULL;
3128 tracing_start_time = get_timestamp ();
3129
3130 /* Tracing is now active, hits will now start being logged. */
3131 tracing = 1;
3132
3133 if (agent_loaded_p ())
3134 {
3135 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
3136 {
3137 internal_error ("Error setting tracing variable in lib");
3138 }
3139
3140 if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
3141 0))
3142 {
3143 internal_error ("Error clearing stopping_tracepoint variable"
3144 " in lib");
3145 }
3146
3147 if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
3148 {
3149 internal_error ("Error clearing trace_buffer_is_full variable"
3150 " in lib");
3151 }
3152
3153 stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
3154 stop_tracing_handler);
3155 if (stop_tracing_bkpt == NULL)
3156 error ("Error setting stop_tracing breakpoint");
3157
3158 flush_trace_buffer_bkpt
3159 = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
3160 flush_trace_buffer_handler);
3161 if (flush_trace_buffer_bkpt == NULL)
3162 error ("Error setting flush_trace_buffer breakpoint");
3163 }
3164
3165 target_unpause_all (true);
3166
3167 write_ok (packet);
3168 }
3169
3170 /* End a tracing run, filling in a stop reason to report back to GDB,
3171 and removing the tracepoints from the code. */
3172
3173 void
3174 stop_tracing (void)
3175 {
3176 if (!tracing)
3177 {
3178 trace_debug ("Tracing is already off, ignoring");
3179 return;
3180 }
3181
3182 trace_debug ("Stopping the trace");
3183
3184 /* Pause all threads before removing fast jumps from memory,
3185 breakpoints, and touching IPA state variables (inferior memory).
3186 Some thread may hit the internal tracing breakpoints, or be
3187 collecting this moment, but that's ok, we don't release the
3188 tpoint object's memory or the jump pads here (we only do that
3189 when we're sure we can move all threads out of the jump pads).
3190 We can't now, since we may be getting here due to the inferior
3191 agent calling us. */
3192 target_pause_all (true);
3193
3194 /* Stop logging. Tracepoints can still be hit, but they will not be
3195 recorded. */
3196 tracing = 0;
3197 if (agent_loaded_p ())
3198 {
3199 if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
3200 {
3201 internal_error ("Error clearing tracing variable in lib");
3202 }
3203 }
3204
3205 tracing_stop_time = get_timestamp ();
3206 tracing_stop_reason = "t???";
3207 tracing_stop_tpnum = 0;
3208 if (stopping_tracepoint)
3209 {
3210 trace_debug ("Stopping the trace because "
3211 "tracepoint %d was hit %" PRIu64 " times",
3212 stopping_tracepoint->number,
3213 stopping_tracepoint->pass_count);
3214 tracing_stop_reason = "tpasscount";
3215 tracing_stop_tpnum = stopping_tracepoint->number;
3216 }
3217 else if (trace_buffer_is_full)
3218 {
3219 trace_debug ("Stopping the trace because the trace buffer is full");
3220 tracing_stop_reason = "tfull";
3221 }
3222 else if (expr_eval_result != expr_eval_no_error)
3223 {
3224 trace_debug ("Stopping the trace because of an expression eval error");
3225 tracing_stop_reason = eval_result_names[expr_eval_result];
3226 tracing_stop_tpnum = error_tracepoint->number;
3227 }
3228 #ifndef IN_PROCESS_AGENT
3229 else if (!gdb_connected ())
3230 {
3231 trace_debug ("Stopping the trace because GDB disconnected");
3232 tracing_stop_reason = "tdisconnected";
3233 }
3234 #endif
3235 else
3236 {
3237 trace_debug ("Stopping the trace because of a tstop command");
3238 tracing_stop_reason = "tstop";
3239 }
3240
3241 stopping_tracepoint = NULL;
3242 error_tracepoint = NULL;
3243
3244 /* Clear out the tracepoints. */
3245 clear_installed_tracepoints ();
3246
3247 if (agent_loaded_p ())
3248 {
3249 /* Pull in fast tracepoint trace frames from the inferior lib
3250 buffer into our buffer, even if our buffer is already full,
3251 because we want to present the full number of created frames
3252 in addition to what fit in the trace buffer. */
3253 upload_fast_traceframes ();
3254 }
3255
3256 if (stop_tracing_bkpt != NULL)
3257 {
3258 delete_breakpoint (stop_tracing_bkpt);
3259 stop_tracing_bkpt = NULL;
3260 }
3261
3262 if (flush_trace_buffer_bkpt != NULL)
3263 {
3264 delete_breakpoint (flush_trace_buffer_bkpt);
3265 flush_trace_buffer_bkpt = NULL;
3266 }
3267
3268 target_unpause_all (true);
3269 }
3270
3271 static int
3272 stop_tracing_handler (CORE_ADDR addr)
3273 {
3274 trace_debug ("lib hit stop_tracing");
3275
3276 /* Don't actually handle it here. When we stop tracing we remove
3277 breakpoints from the inferior, and that is not allowed in a
3278 breakpoint handler (as the caller is walking the breakpoint
3279 list). */
3280 return 0;
3281 }
3282
3283 static int
3284 flush_trace_buffer_handler (CORE_ADDR addr)
3285 {
3286 trace_debug ("lib hit flush_trace_buffer");
3287 return 0;
3288 }
3289
3290 static void
3291 cmd_qtstop (char *packet)
3292 {
3293 stop_tracing ();
3294 write_ok (packet);
3295 }
3296
3297 static void
3298 cmd_qtdisconnected (char *own_buf)
3299 {
3300 ULONGEST setting;
3301 char *packet = own_buf;
3302
3303 packet += strlen ("QTDisconnected:");
3304
3305 unpack_varlen_hex (packet, &setting);
3306
3307 write_ok (own_buf);
3308
3309 disconnected_tracing = setting;
3310 }
3311
3312 static void
3313 cmd_qtframe (char *own_buf)
3314 {
3315 client_state &cs = get_client_state ();
3316 ULONGEST frame, pc, lo, hi, num;
3317 int tfnum, tpnum;
3318 struct traceframe *tframe;
3319 const char *packet = own_buf;
3320
3321 packet += strlen ("QTFrame:");
3322
3323 if (startswith (packet, "pc:"))
3324 {
3325 packet += strlen ("pc:");
3326 unpack_varlen_hex (packet, &pc);
3327 trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
3328 tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
3329 }
3330 else if (startswith (packet, "range:"))
3331 {
3332 packet += strlen ("range:");
3333 packet = unpack_varlen_hex (packet, &lo);
3334 ++packet;
3335 unpack_varlen_hex (packet, &hi);
3336 trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
3337 paddress (lo), paddress (hi));
3338 tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
3339 }
3340 else if (startswith (packet, "outside:"))
3341 {
3342 packet += strlen ("outside:");
3343 packet = unpack_varlen_hex (packet, &lo);
3344 ++packet;
3345 unpack_varlen_hex (packet, &hi);
3346 trace_debug ("Want to find next traceframe "
3347 "outside the range 0x%s to 0x%s",
3348 paddress (lo), paddress (hi));
3349 tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
3350 }
3351 else if (startswith (packet, "tdp:"))
3352 {
3353 packet += strlen ("tdp:");
3354 unpack_varlen_hex (packet, &num);
3355 tpnum = (int) num;
3356 trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
3357 tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
3358 }
3359 else
3360 {
3361 unpack_varlen_hex (packet, &frame);
3362 tfnum = (int) frame;
3363 if (tfnum == -1)
3364 {
3365 trace_debug ("Want to stop looking at traceframes");
3366 cs.current_traceframe = -1;
3367 write_ok (own_buf);
3368 return;
3369 }
3370 trace_debug ("Want to look at traceframe %d", tfnum);
3371 tframe = find_traceframe (tfnum);
3372 }
3373
3374 if (tframe)
3375 {
3376 cs.current_traceframe = tfnum;
3377 sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
3378 }
3379 else
3380 sprintf (own_buf, "F-1");
3381 }
3382
3383 static void
3384 cmd_qtstatus (char *packet)
3385 {
3386 char *stop_reason_rsp = NULL;
3387 char *buf1, *buf2, *buf3;
3388 const char *str;
3389 int slen;
3390
3391 /* Translate the plain text of the notes back into hex for
3392 transmission. */
3393
3394 str = (tracing_user_name ? tracing_user_name : "");
3395 slen = strlen (str);
3396 buf1 = (char *) alloca (slen * 2 + 1);
3397 bin2hex ((gdb_byte *) str, buf1, slen);
3398
3399 str = (tracing_notes ? tracing_notes : "");
3400 slen = strlen (str);
3401 buf2 = (char *) alloca (slen * 2 + 1);
3402 bin2hex ((gdb_byte *) str, buf2, slen);
3403
3404 str = (tracing_stop_note ? tracing_stop_note : "");
3405 slen = strlen (str);
3406 buf3 = (char *) alloca (slen * 2 + 1);
3407 bin2hex ((gdb_byte *) str, buf3, slen);
3408
3409 trace_debug ("Returning trace status as %d, stop reason %s",
3410 tracing, tracing_stop_reason);
3411
3412 if (agent_loaded_p ())
3413 {
3414 target_pause_all (true);
3415
3416 upload_fast_traceframes ();
3417
3418 target_unpause_all (true);
3419 }
3420
3421 stop_reason_rsp = (char *) tracing_stop_reason;
3422
3423 /* The user visible error string in terror needs to be hex encoded.
3424 We leave it as plain string in `tracing_stop_reason' to ease
3425 debugging. */
3426 if (startswith (stop_reason_rsp, "terror:"))
3427 {
3428 const char *result_name;
3429 int hexstr_len;
3430 char *p;
3431
3432 result_name = stop_reason_rsp + strlen ("terror:");
3433 hexstr_len = strlen (result_name) * 2;
3434 p = stop_reason_rsp
3435 = (char *) alloca (strlen ("terror:") + hexstr_len + 1);
3436 strcpy (p, "terror:");
3437 p += strlen (p);
3438 bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
3439 }
3440
3441 /* If this was a forced stop, include any stop note that was supplied. */
3442 if (strcmp (stop_reason_rsp, "tstop") == 0)
3443 {
3444 stop_reason_rsp = (char *) alloca (strlen ("tstop:") + strlen (buf3) + 1);
3445 strcpy (stop_reason_rsp, "tstop:");
3446 strcat (stop_reason_rsp, buf3);
3447 }
3448
3449 sprintf (packet,
3450 "T%d;"
3451 "%s:%x;"
3452 "tframes:%x;tcreated:%x;"
3453 "tfree:%x;tsize:%s;"
3454 "circular:%d;"
3455 "disconn:%d;"
3456 "starttime:%s;stoptime:%s;"
3457 "username:%s;notes:%s:",
3458 tracing ? 1 : 0,
3459 stop_reason_rsp, tracing_stop_tpnum,
3460 traceframe_count, traceframes_created,
3461 free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
3462 circular_trace_buffer,
3463 disconnected_tracing,
3464 phex_nz (tracing_start_time),
3465 phex_nz (tracing_stop_time),
3466 buf1, buf2);
3467 }
3468
3469 static void
3470 cmd_qtp (char *own_buf)
3471 {
3472 ULONGEST num, addr;
3473 struct tracepoint *tpoint;
3474 const char *packet = own_buf;
3475
3476 packet += strlen ("qTP:");
3477
3478 packet = unpack_varlen_hex (packet, &num);
3479 ++packet; /* skip a colon */
3480 packet = unpack_varlen_hex (packet, &addr);
3481
3482 /* See if we already have this tracepoint. */
3483 tpoint = find_tracepoint (num, addr);
3484
3485 if (!tpoint)
3486 {
3487 trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
3488 (int) num, paddress (addr));
3489 write_enn (own_buf);
3490 return;
3491 }
3492
3493 sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
3494 tpoint->traceframe_usage);
3495 }
3496
3497 /* State variables to help return all the tracepoint bits. */
3498 static struct tracepoint *cur_tpoint;
3499 static unsigned int cur_action;
3500 static unsigned int cur_step_action;
3501 static struct source_string *cur_source_string;
3502 static struct trace_state_variable *cur_tsv;
3503
3504 /* Compose a response that is an imitation of the syntax by which the
3505 tracepoint was originally downloaded. */
3506
3507 static void
3508 response_tracepoint (char *packet, struct tracepoint *tpoint)
3509 {
3510 char *buf;
3511
3512 sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
3513 paddress (tpoint->address),
3514 (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
3515 tpoint->pass_count);
3516 if (tpoint->type == fast_tracepoint)
3517 sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
3518
3519 if (tpoint->cond)
3520 {
3521 buf = gdb_unparse_agent_expr (tpoint->cond);
3522 sprintf (packet + strlen (packet), ":X%x,%s",
3523 tpoint->cond->length, buf);
3524 free (buf);
3525 }
3526 }
3527
3528 /* Compose a response that is an imitation of the syntax by which the
3529 tracepoint action was originally downloaded (with the difference
3530 that due to the way we store the actions, this will output a packet
3531 per action, while GDB could have combined more than one action
3532 per-packet. */
3533
3534 static void
3535 response_action (char *packet, struct tracepoint *tpoint,
3536 char *taction, int step)
3537 {
3538 sprintf (packet, "%c%x:%s:%s",
3539 (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
3540 taction);
3541 }
3542
3543 /* Compose a response that is an imitation of the syntax by which the
3544 tracepoint source piece was originally downloaded. */
3545
3546 static void
3547 response_source (char *packet,
3548 struct tracepoint *tpoint, struct source_string *src)
3549 {
3550 char *buf;
3551 int len;
3552
3553 len = strlen (src->str);
3554 buf = (char *) alloca (len * 2 + 1);
3555 bin2hex ((gdb_byte *) src->str, buf, len);
3556
3557 sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
3558 tpoint->number, paddress (tpoint->address),
3559 src->type, 0, len, buf);
3560 }
3561
3562 /* Return the first piece of tracepoint definition, and initialize the
3563 state machine that will iterate through all the tracepoint
3564 bits. */
3565
3566 static void
3567 cmd_qtfp (char *packet)
3568 {
3569 trace_debug ("Returning first tracepoint definition piece");
3570
3571 cur_tpoint = tracepoints;
3572 cur_action = cur_step_action = 0;
3573 cur_source_string = NULL;
3574
3575 if (cur_tpoint)
3576 response_tracepoint (packet, cur_tpoint);
3577 else
3578 strcpy (packet, "l");
3579 }
3580
3581 /* Return additional pieces of tracepoint definition. Each action and
3582 stepping action must go into its own packet, because of packet size
3583 limits, and so we use state variables to deliver one piece at a
3584 time. */
3585
3586 static void
3587 cmd_qtsp (char *packet)
3588 {
3589 trace_debug ("Returning subsequent tracepoint definition piece");
3590
3591 if (!cur_tpoint)
3592 {
3593 /* This case would normally never occur, but be prepared for
3594 GDB misbehavior. */
3595 strcpy (packet, "l");
3596 }
3597 else if (cur_action < cur_tpoint->numactions)
3598 {
3599 response_action (packet, cur_tpoint,
3600 cur_tpoint->actions_str[cur_action], 0);
3601 ++cur_action;
3602 }
3603 else if (cur_step_action < cur_tpoint->num_step_actions)
3604 {
3605 response_action (packet, cur_tpoint,
3606 cur_tpoint->step_actions_str[cur_step_action], 1);
3607 ++cur_step_action;
3608 }
3609 else if ((cur_source_string
3610 ? cur_source_string->next
3611 : cur_tpoint->source_strings))
3612 {
3613 if (cur_source_string)
3614 cur_source_string = cur_source_string->next;
3615 else
3616 cur_source_string = cur_tpoint->source_strings;
3617 response_source (packet, cur_tpoint, cur_source_string);
3618 }
3619 else
3620 {
3621 cur_tpoint = cur_tpoint->next;
3622 cur_action = cur_step_action = 0;
3623 cur_source_string = NULL;
3624 if (cur_tpoint)
3625 response_tracepoint (packet, cur_tpoint);
3626 else
3627 strcpy (packet, "l");
3628 }
3629 }
3630
3631 /* Compose a response that is an imitation of the syntax by which the
3632 trace state variable was originally downloaded. */
3633
3634 static void
3635 response_tsv (char *packet, struct trace_state_variable *tsv)
3636 {
3637 char *buf = (char *) "";
3638 int namelen;
3639
3640 if (tsv->name)
3641 {
3642 namelen = strlen (tsv->name);
3643 buf = (char *) alloca (namelen * 2 + 1);
3644 bin2hex ((gdb_byte *) tsv->name, buf, namelen);
3645 }
3646
3647 sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
3648 tsv->getter ? 1 : 0, buf);
3649 }
3650
3651 /* Return the first trace state variable definition, and initialize
3652 the state machine that will iterate through all the tsv bits. */
3653
3654 static void
3655 cmd_qtfv (char *packet)
3656 {
3657 trace_debug ("Returning first trace state variable definition");
3658
3659 cur_tsv = trace_state_variables;
3660
3661 if (cur_tsv)
3662 response_tsv (packet, cur_tsv);
3663 else
3664 strcpy (packet, "l");
3665 }
3666
3667 /* Return additional trace state variable definitions. */
3668
3669 static void
3670 cmd_qtsv (char *packet)
3671 {
3672 trace_debug ("Returning additional trace state variable definition");
3673
3674 if (cur_tsv)
3675 {
3676 cur_tsv = cur_tsv->next;
3677 if (cur_tsv)
3678 response_tsv (packet, cur_tsv);
3679 else
3680 strcpy (packet, "l");
3681 }
3682 else
3683 strcpy (packet, "l");
3684 }
3685
3686 /* Sent the agent a command to close it. */
3687
3688 void
3689 gdb_agent_about_to_close (int pid)
3690 {
3691 char buf[IPA_CMD_BUF_SIZE];
3692
3693 if (!maybe_write_ipa_not_loaded (buf))
3694 {
3695 scoped_restore_current_thread restore_thread;
3696
3697 /* Find any thread which belongs to process PID. */
3698 switch_to_thread (find_any_thread_of_pid (pid));
3699
3700 strcpy (buf, "close");
3701
3702 run_inferior_command (buf, strlen (buf) + 1);
3703 }
3704 }
3705
3706 /* Return the minimum instruction size needed for fast tracepoints as a
3707 hexadecimal number. */
3708
3709 static void
3710 cmd_qtminftpilen (char *packet)
3711 {
3712 if (current_thread == NULL)
3713 {
3714 /* Indicate that the minimum length is currently unknown. */
3715 strcpy (packet, "0");
3716 return;
3717 }
3718
3719 sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
3720 }
3721
3722 /* Respond to qTBuffer packet with a block of raw data from the trace
3723 buffer. GDB may ask for a lot, but we are allowed to reply with
3724 only as much as will fit within packet limits or whatever. */
3725
3726 static void
3727 cmd_qtbuffer (char *own_buf)
3728 {
3729 ULONGEST offset, num, tot;
3730 unsigned char *tbp;
3731 const char *packet = own_buf;
3732
3733 packet += strlen ("qTBuffer:");
3734
3735 packet = unpack_varlen_hex (packet, &offset);
3736 ++packet; /* skip a comma */
3737 unpack_varlen_hex (packet, &num);
3738
3739 trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
3740 (int) num, phex_nz (offset, 0));
3741
3742 tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
3743
3744 /* If we're right at the end, reply specially that we're done. */
3745 if (offset == tot)
3746 {
3747 strcpy (own_buf, "l");
3748 return;
3749 }
3750
3751 /* Object to any other out-of-bounds request. */
3752 if (offset > tot)
3753 {
3754 write_enn (own_buf);
3755 return;
3756 }
3757
3758 /* Compute the pointer corresponding to the given offset, accounting
3759 for wraparound. */
3760 tbp = trace_buffer_start + offset;
3761 if (tbp >= trace_buffer_wrap)
3762 tbp -= (trace_buffer_wrap - trace_buffer_lo);
3763
3764 /* Trim to the remaining bytes if we're close to the end. */
3765 if (num > tot - offset)
3766 num = tot - offset;
3767
3768 /* Trim to available packet size. */
3769 if (num >= (PBUFSIZ - 16) / 2 )
3770 num = (PBUFSIZ - 16) / 2;
3771
3772 bin2hex (tbp, own_buf, num);
3773 }
3774
3775 static void
3776 cmd_bigqtbuffer_circular (char *own_buf)
3777 {
3778 ULONGEST val;
3779 char *packet = own_buf;
3780
3781 packet += strlen ("QTBuffer:circular:");
3782
3783 unpack_varlen_hex (packet, &val);
3784 circular_trace_buffer = val;
3785 trace_debug ("Trace buffer is now %s",
3786 circular_trace_buffer ? "circular" : "linear");
3787 write_ok (own_buf);
3788 }
3789
3790 static void
3791 cmd_bigqtbuffer_size (char *own_buf)
3792 {
3793 ULONGEST val;
3794 LONGEST sval;
3795 char *packet = own_buf;
3796
3797 /* Can't change the size during a tracing run. */
3798 if (tracing)
3799 {
3800 write_enn (own_buf);
3801 return;
3802 }
3803
3804 packet += strlen ("QTBuffer:size:");
3805
3806 /* -1 is sent as literal "-1". */
3807 if (strcmp (packet, "-1") == 0)
3808 sval = DEFAULT_TRACE_BUFFER_SIZE;
3809 else
3810 {
3811 unpack_varlen_hex (packet, &val);
3812 sval = (LONGEST) val;
3813 }
3814
3815 init_trace_buffer (sval);
3816 trace_debug ("Trace buffer is now %s bytes",
3817 plongest (trace_buffer_size));
3818 write_ok (own_buf);
3819 }
3820
3821 static void
3822 cmd_qtnotes (char *own_buf)
3823 {
3824 size_t nbytes;
3825 char *saved, *user, *notes, *stopnote;
3826 char *packet = own_buf;
3827
3828 packet += strlen ("QTNotes:");
3829
3830 while (*packet)
3831 {
3832 if (startswith (packet, "user:"))
3833 {
3834 packet += strlen ("user:");
3835 saved = packet;
3836 packet = strchr (packet, ';');
3837 nbytes = (packet - saved) / 2;
3838 user = (char *) xmalloc (nbytes + 1);
3839 nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
3840 user[nbytes] = '\0';
3841 ++packet; /* skip the semicolon */
3842 trace_debug ("User is '%s'", user);
3843 xfree (tracing_user_name);
3844 tracing_user_name = user;
3845 }
3846 else if (startswith (packet, "notes:"))
3847 {
3848 packet += strlen ("notes:");
3849 saved = packet;
3850 packet = strchr (packet, ';');
3851 nbytes = (packet - saved) / 2;
3852 notes = (char *) xmalloc (nbytes + 1);
3853 nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
3854 notes[nbytes] = '\0';
3855 ++packet; /* skip the semicolon */
3856 trace_debug ("Notes is '%s'", notes);
3857 xfree (tracing_notes);
3858 tracing_notes = notes;
3859 }
3860 else if (startswith (packet, "tstop:"))
3861 {
3862 packet += strlen ("tstop:");
3863 saved = packet;
3864 packet = strchr (packet, ';');
3865 nbytes = (packet - saved) / 2;
3866 stopnote = (char *) xmalloc (nbytes + 1);
3867 nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
3868 stopnote[nbytes] = '\0';
3869 ++packet; /* skip the semicolon */
3870 trace_debug ("tstop note is '%s'", stopnote);
3871 xfree (tracing_stop_note);
3872 tracing_stop_note = stopnote;
3873 }
3874 else
3875 break;
3876 }
3877
3878 write_ok (own_buf);
3879 }
3880
3881 int
3882 handle_tracepoint_general_set (char *packet)
3883 {
3884 if (strcmp ("QTinit", packet) == 0)
3885 {
3886 cmd_qtinit (packet);
3887 return 1;
3888 }
3889 else if (startswith (packet, "QTDP:"))
3890 {
3891 cmd_qtdp (packet);
3892 return 1;
3893 }
3894 else if (startswith (packet, "QTDPsrc:"))
3895 {
3896 cmd_qtdpsrc (packet);
3897 return 1;
3898 }
3899 else if (startswith (packet, "QTEnable:"))
3900 {
3901 cmd_qtenable_disable (packet, 1);
3902 return 1;
3903 }
3904 else if (startswith (packet, "QTDisable:"))
3905 {
3906 cmd_qtenable_disable (packet, 0);
3907 return 1;
3908 }
3909 else if (startswith (packet, "QTDV:"))
3910 {
3911 cmd_qtdv (packet);
3912 return 1;
3913 }
3914 else if (startswith (packet, "QTro:"))
3915 {
3916 cmd_qtro (packet);
3917 return 1;
3918 }
3919 else if (strcmp ("QTStart", packet) == 0)
3920 {
3921 cmd_qtstart (packet);
3922 return 1;
3923 }
3924 else if (strcmp ("QTStop", packet) == 0)
3925 {
3926 cmd_qtstop (packet);
3927 return 1;
3928 }
3929 else if (startswith (packet, "QTDisconnected:"))
3930 {
3931 cmd_qtdisconnected (packet);
3932 return 1;
3933 }
3934 else if (startswith (packet, "QTFrame:"))
3935 {
3936 cmd_qtframe (packet);
3937 return 1;
3938 }
3939 else if (startswith (packet, "QTBuffer:circular:"))
3940 {
3941 cmd_bigqtbuffer_circular (packet);
3942 return 1;
3943 }
3944 else if (startswith (packet, "QTBuffer:size:"))
3945 {
3946 cmd_bigqtbuffer_size (packet);
3947 return 1;
3948 }
3949 else if (startswith (packet, "QTNotes:"))
3950 {
3951 cmd_qtnotes (packet);
3952 return 1;
3953 }
3954
3955 return 0;
3956 }
3957
3958 int
3959 handle_tracepoint_query (char *packet)
3960 {
3961 if (strcmp ("qTStatus", packet) == 0)
3962 {
3963 cmd_qtstatus (packet);
3964 return 1;
3965 }
3966 else if (startswith (packet, "qTP:"))
3967 {
3968 cmd_qtp (packet);
3969 return 1;
3970 }
3971 else if (strcmp ("qTfP", packet) == 0)
3972 {
3973 cmd_qtfp (packet);
3974 return 1;
3975 }
3976 else if (strcmp ("qTsP", packet) == 0)
3977 {
3978 cmd_qtsp (packet);
3979 return 1;
3980 }
3981 else if (strcmp ("qTfV", packet) == 0)
3982 {
3983 cmd_qtfv (packet);
3984 return 1;
3985 }
3986 else if (strcmp ("qTsV", packet) == 0)
3987 {
3988 cmd_qtsv (packet);
3989 return 1;
3990 }
3991 else if (startswith (packet, "qTV:"))
3992 {
3993 cmd_qtv (packet);
3994 return 1;
3995 }
3996 else if (startswith (packet, "qTBuffer:"))
3997 {
3998 cmd_qtbuffer (packet);
3999 return 1;
4000 }
4001 else if (strcmp ("qTMinFTPILen", packet) == 0)
4002 {
4003 cmd_qtminftpilen (packet);
4004 return 1;
4005 }
4006
4007 return 0;
4008 }
4009
4010 #endif
4011 #ifndef IN_PROCESS_AGENT
4012
4013 /* Call this when thread TINFO has hit the tracepoint defined by
4014 TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
4015 action. This adds a while-stepping collecting state item to the
4016 threads' collecting state list, so that we can keep track of
4017 multiple simultaneous while-stepping actions being collected by the
4018 same thread. This can happen in cases like:
4019
4020 ff0001 INSN1 <-- TP1, while-stepping 10 collect $regs
4021 ff0002 INSN2
4022 ff0003 INSN3 <-- TP2, collect $regs
4023 ff0004 INSN4 <-- TP3, while-stepping 10 collect $regs
4024 ff0005 INSN5
4025
4026 Notice that when instruction INSN5 is reached, the while-stepping
4027 actions of both TP1 and TP3 are still being collected, and that TP2
4028 had been collected meanwhile. The whole range of ff0001-ff0005
4029 should be single-stepped, due to at least TP1's while-stepping
4030 action covering the whole range. */
4031
4032 static void
4033 add_while_stepping_state (thread_info *tinfo,
4034 int tp_number, CORE_ADDR tp_address)
4035 {
4036 struct wstep_state *wstep = XNEW (struct wstep_state);
4037
4038 wstep->next = tinfo->while_stepping;
4039
4040 wstep->tp_number = tp_number;
4041 wstep->tp_address = tp_address;
4042 wstep->current_step = 0;
4043
4044 tinfo->while_stepping = wstep;
4045 }
4046
4047 /* Release the while-stepping collecting state WSTEP. */
4048
4049 static void
4050 release_while_stepping_state (struct wstep_state *wstep)
4051 {
4052 free (wstep);
4053 }
4054
4055 /* Release all while-stepping collecting states currently associated
4056 with thread TINFO. */
4057
4058 void
4059 release_while_stepping_state_list (thread_info *tinfo)
4060 {
4061 struct wstep_state *head;
4062
4063 while (tinfo->while_stepping)
4064 {
4065 head = tinfo->while_stepping;
4066 tinfo->while_stepping = head->next;
4067 release_while_stepping_state (head);
4068 }
4069 }
4070
4071 /* If TINFO was handling a 'while-stepping' action, the step has
4072 finished, so collect any step data needed, and check if any more
4073 steps are required. Return true if the thread was indeed
4074 collecting tracepoint data, false otherwise. */
4075
4076 int
4077 tracepoint_finished_step (thread_info *tinfo, CORE_ADDR stop_pc)
4078 {
4079 struct tracepoint *tpoint;
4080 struct wstep_state *wstep;
4081 struct wstep_state **wstep_link;
4082
4083 /* Pull in fast tracepoint trace frames from the inferior lib buffer into
4084 our buffer. */
4085 if (agent_loaded_p ())
4086 upload_fast_traceframes ();
4087
4088 /* Check if we were indeed collecting data for one of more
4089 tracepoints with a 'while-stepping' count. */
4090 if (tinfo->while_stepping == NULL)
4091 return 0;
4092
4093 if (!tracing)
4094 {
4095 /* We're not even tracing anymore. Stop this thread from
4096 collecting. */
4097 release_while_stepping_state_list (tinfo);
4098
4099 /* The thread had stopped due to a single-step request indeed
4100 explained by a tracepoint. */
4101 return 1;
4102 }
4103
4104 wstep = tinfo->while_stepping;
4105 wstep_link = &tinfo->while_stepping;
4106
4107 trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
4108 target_pid_to_str (tinfo->id).c_str (),
4109 wstep->tp_number, paddress (wstep->tp_address));
4110
4111 trap_tracepoint_ctx ctx (get_thread_regcache (tinfo));
4112
4113 while (wstep != NULL)
4114 {
4115 tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
4116 if (tpoint == NULL)
4117 {
4118 trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
4119 wstep->tp_number, paddress (wstep->tp_address),
4120 target_pid_to_str (tinfo->id).c_str ());
4121
4122 /* Unlink. */
4123 *wstep_link = wstep->next;
4124 release_while_stepping_state (wstep);
4125 wstep = *wstep_link;
4126 continue;
4127 }
4128
4129 /* We've just finished one step. */
4130 ++wstep->current_step;
4131
4132 /* Collect data. */
4133 collect_data_at_step (&ctx, stop_pc, tpoint, wstep->current_step);
4134
4135 if (wstep->current_step >= tpoint->step_count)
4136 {
4137 /* The requested numbers of steps have occurred. */
4138 trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
4139 target_pid_to_str (tinfo->id).c_str (),
4140 wstep->tp_number, paddress (wstep->tp_address));
4141
4142 /* Unlink the wstep. */
4143 *wstep_link = wstep->next;
4144 release_while_stepping_state (wstep);
4145 wstep = *wstep_link;
4146
4147 /* Only check the hit count now, which ensure that we do all
4148 our stepping before stopping the run. */
4149 if (tpoint->pass_count > 0
4150 && tpoint->hit_count >= tpoint->pass_count
4151 && stopping_tracepoint == NULL)
4152 stopping_tracepoint = tpoint;
4153 }
4154 else
4155 {
4156 /* Keep single-stepping until the requested numbers of steps
4157 have occurred. */
4158 wstep_link = &wstep->next;
4159 wstep = *wstep_link;
4160 }
4161
4162 if (stopping_tracepoint
4163 || trace_buffer_is_full
4164 || expr_eval_result != expr_eval_no_error)
4165 {
4166 stop_tracing ();
4167 break;
4168 }
4169 }
4170
4171 return 1;
4172 }
4173
4174 /* Handle any internal tracing control breakpoint hits. That means,
4175 pull traceframes from the IPA to our buffer, and syncing both
4176 tracing agents when the IPA's tracing stops for some reason. */
4177
4178 int
4179 handle_tracepoint_bkpts (thread_info *tinfo, CORE_ADDR stop_pc)
4180 {
4181 /* Pull in fast tracepoint trace frames from the inferior in-process
4182 agent's buffer into our buffer. */
4183
4184 if (!agent_loaded_p ())
4185 return 0;
4186
4187 upload_fast_traceframes ();
4188
4189 /* Check if the in-process agent had decided we should stop
4190 tracing. */
4191 if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
4192 {
4193 int ipa_trace_buffer_is_full;
4194 CORE_ADDR ipa_stopping_tracepoint;
4195 int ipa_expr_eval_result;
4196 CORE_ADDR ipa_error_tracepoint;
4197
4198 trace_debug ("lib stopped at stop_tracing");
4199
4200 read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
4201 &ipa_trace_buffer_is_full);
4202
4203 read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
4204 &ipa_stopping_tracepoint);
4205 write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
4206
4207 read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
4208 &ipa_error_tracepoint);
4209 write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
4210
4211 read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
4212 &ipa_expr_eval_result);
4213 write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
4214
4215 trace_debug ("lib: trace_buffer_is_full: %d, "
4216 "stopping_tracepoint: %s, "
4217 "ipa_expr_eval_result: %d, "
4218 "error_tracepoint: %s, ",
4219 ipa_trace_buffer_is_full,
4220 paddress (ipa_stopping_tracepoint),
4221 ipa_expr_eval_result,
4222 paddress (ipa_error_tracepoint));
4223
4224 if (ipa_trace_buffer_is_full)
4225 trace_debug ("lib stopped due to full buffer.");
4226
4227 if (ipa_stopping_tracepoint)
4228 trace_debug ("lib stopped due to tpoint");
4229
4230 if (ipa_error_tracepoint)
4231 trace_debug ("lib stopped due to error");
4232
4233 if (ipa_stopping_tracepoint != 0)
4234 {
4235 stopping_tracepoint
4236 = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
4237 }
4238 else if (ipa_expr_eval_result != expr_eval_no_error)
4239 {
4240 expr_eval_result = ipa_expr_eval_result;
4241 error_tracepoint
4242 = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
4243 }
4244 stop_tracing ();
4245 return 1;
4246 }
4247 else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
4248 {
4249 trace_debug ("lib stopped at flush_trace_buffer");
4250 return 1;
4251 }
4252
4253 return 0;
4254 }
4255
4256 /* Return true if TINFO just hit a tracepoint. Collect data if
4257 so. */
4258
4259 int
4260 tracepoint_was_hit (thread_info *tinfo, CORE_ADDR stop_pc)
4261 {
4262 struct tracepoint *tpoint;
4263 int ret = 0;
4264
4265 /* Not tracing, don't handle. */
4266 if (!tracing)
4267 return 0;
4268
4269 trap_tracepoint_ctx ctx (get_thread_regcache (tinfo));
4270
4271 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
4272 {
4273 /* Note that we collect fast tracepoints here as well. We'll
4274 step over the fast tracepoint jump later, which avoids the
4275 double collect. */
4276 if (tpoint->enabled && stop_pc == tpoint->address)
4277 {
4278 trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
4279 target_pid_to_str (tinfo->id).c_str (),
4280 tpoint->number, paddress (tpoint->address));
4281
4282 /* Test the condition if present, and collect if true. */
4283 if (!tpoint->cond
4284 || (condition_true_at_tracepoint (&ctx, tpoint)))
4285 collect_data_at_tracepoint (&ctx, stop_pc, tpoint);
4286
4287 if (stopping_tracepoint
4288 || trace_buffer_is_full
4289 || expr_eval_result != expr_eval_no_error)
4290 {
4291 stop_tracing ();
4292 }
4293 /* If the tracepoint had a 'while-stepping' action, then set
4294 the thread to collect this tracepoint on the following
4295 single-steps. */
4296 else if (tpoint->step_count > 0)
4297 {
4298 add_while_stepping_state (tinfo,
4299 tpoint->number, tpoint->address);
4300 }
4301
4302 ret = 1;
4303 }
4304 }
4305
4306 return ret;
4307 }
4308
4309 #endif
4310
4311 /* Create a trace frame for the hit of the given tracepoint in the
4312 given thread. */
4313
4314 static void
4315 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
4316 struct tracepoint *tpoint)
4317 {
4318 struct traceframe *tframe;
4319 int acti;
4320
4321 /* Only count it as a hit when we actually collect data. */
4322 tpoint->hit_count++;
4323
4324 /* If we've exceeded a defined pass count, record the event for
4325 later, and finish the collection for this hit. This test is only
4326 for nonstepping tracepoints, stepping tracepoints test at the end
4327 of their while-stepping loop. */
4328 if (tpoint->pass_count > 0
4329 && tpoint->hit_count >= tpoint->pass_count
4330 && tpoint->step_count == 0
4331 && stopping_tracepoint == NULL)
4332 stopping_tracepoint = tpoint;
4333
4334 trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
4335 tpoint->number, paddress (tpoint->address), tpoint->hit_count);
4336
4337 tframe = add_traceframe (tpoint);
4338
4339 if (tframe)
4340 {
4341 for (acti = 0; acti < tpoint->numactions; ++acti)
4342 {
4343 #ifndef IN_PROCESS_AGENT
4344 trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
4345 tpoint->number, paddress (tpoint->address),
4346 tpoint->actions_str[acti]);
4347 #endif
4348
4349 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4350 tpoint->actions[acti]);
4351 }
4352
4353 finish_traceframe (tframe);
4354 }
4355
4356 if (tframe == NULL && tracing)
4357 trace_buffer_is_full = 1;
4358 }
4359
4360 #ifndef IN_PROCESS_AGENT
4361
4362 static void
4363 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
4364 CORE_ADDR stop_pc,
4365 struct tracepoint *tpoint, int current_step)
4366 {
4367 struct traceframe *tframe;
4368 int acti;
4369
4370 trace_debug ("Making new step traceframe for "
4371 "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
4372 tpoint->number, paddress (tpoint->address),
4373 current_step, tpoint->step_count,
4374 tpoint->hit_count);
4375
4376 tframe = add_traceframe (tpoint);
4377
4378 if (tframe)
4379 {
4380 for (acti = 0; acti < tpoint->num_step_actions; ++acti)
4381 {
4382 trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
4383 tpoint->number, paddress (tpoint->address),
4384 tpoint->step_actions_str[acti]);
4385
4386 do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
4387 tpoint->step_actions[acti]);
4388 }
4389
4390 finish_traceframe (tframe);
4391 }
4392
4393 if (tframe == NULL && tracing)
4394 trace_buffer_is_full = 1;
4395 }
4396
4397 #endif
4398
4399 static void
4400 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4401 CORE_ADDR stop_pc,
4402 struct tracepoint *tpoint,
4403 struct traceframe *tframe,
4404 struct tracepoint_action *taction)
4405 {
4406 enum eval_result_type err;
4407
4408 switch (taction->type)
4409 {
4410 case 'M':
4411 {
4412 struct collect_memory_action *maction;
4413 struct eval_agent_expr_context ax_ctx;
4414
4415 maction = (struct collect_memory_action *) taction;
4416 ax_ctx.regcache = NULL;
4417 ax_ctx.tframe = tframe;
4418 ax_ctx.tpoint = tpoint;
4419
4420 trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
4421 pulongest (maction->len),
4422 paddress (maction->addr), maction->basereg);
4423 /* (should use basereg) */
4424 agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
4425 maction->len);
4426 break;
4427 }
4428 case 'R':
4429 {
4430 unsigned char *regspace;
4431 int regcache_size;
4432
4433 trace_debug ("Want to collect registers");
4434
4435 regcache *context_regcache = ctx->regcache ();
4436 regcache_size = register_cache_size (context_regcache->tdesc);
4437
4438 /* Collect all registers for now. */
4439 regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
4440 if (regspace == NULL)
4441 {
4442 trace_debug ("Trace buffer block allocation failed, skipping");
4443 break;
4444 }
4445 /* Identify a register block. */
4446 *regspace = 'R';
4447
4448 /* Wrap the regblock in a register cache (in the stack, we
4449 don't want to malloc here). */
4450 regcache tregcache (context_regcache->tdesc, regspace + 1);
4451
4452 /* Copy the register data to the regblock. */
4453 tregcache.copy_from (context_regcache);
4454
4455 #ifndef IN_PROCESS_AGENT
4456 /* On some platforms, trap-based tracepoints will have the PC
4457 pointing to the next instruction after the trap, but we
4458 don't want the user or GDB trying to guess whether the
4459 saved PC needs adjusting; so always record the adjusted
4460 stop_pc. Note that we can't use tpoint->address instead,
4461 since it will be wrong for while-stepping actions. This
4462 adjustment is a nop for fast tracepoints collected from the
4463 in-process lib (but not if GDBserver is collecting one
4464 preemptively), since the PC had already been adjusted to
4465 contain the tracepoint's address by the jump pad. */
4466 trace_debug ("Storing stop pc (0x%s) in regblock",
4467 paddress (stop_pc));
4468
4469 /* This changes the regblock, not the thread's
4470 regcache. */
4471 regcache_write_pc (&tregcache, stop_pc);
4472 #endif
4473 }
4474 break;
4475 case 'X':
4476 {
4477 struct eval_expr_action *eaction;
4478 struct eval_agent_expr_context ax_ctx;
4479
4480 eaction = (struct eval_expr_action *) taction;
4481 ax_ctx.regcache = ctx->regcache ();
4482 ax_ctx.tframe = tframe;
4483 ax_ctx.tpoint = tpoint;
4484
4485 trace_debug ("Want to evaluate expression");
4486
4487 err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
4488
4489 if (err != expr_eval_no_error)
4490 {
4491 record_tracepoint_error (tpoint, "action expression", err);
4492 return;
4493 }
4494 }
4495 break;
4496 default:
4497 trace_debug ("unknown trace action '%c', ignoring", taction->type);
4498 break;
4499 }
4500 }
4501
4502 static int
4503 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
4504 struct tracepoint *tpoint)
4505 {
4506 ULONGEST value = 0;
4507 enum eval_result_type err;
4508
4509 /* Presently, gdbserver doesn't run compiled conditions, only the
4510 IPA does. If the program stops at a fast tracepoint's address
4511 (e.g., due to a breakpoint, trap tracepoint, or stepping),
4512 gdbserver preemptively collect the fast tracepoint. Later, on
4513 resume, gdbserver steps over the fast tracepoint like it steps
4514 over breakpoints, so that the IPA doesn't see that fast
4515 tracepoint. This avoids double collects of fast tracepoints in
4516 that stopping scenario. Having gdbserver itself handle the fast
4517 tracepoint gives the user a consistent view of when fast or trap
4518 tracepoints are collected, compared to an alternative where only
4519 trap tracepoints are collected on stop, and fast tracepoints on
4520 resume. When a fast tracepoint is being processed by gdbserver,
4521 it is always the non-compiled condition expression that is
4522 used. */
4523 #ifdef IN_PROCESS_AGENT
4524 if (tpoint->compiled_cond)
4525 {
4526 auto fctx = static_cast<fast_tracepoint_ctx *> (ctx);
4527 err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (fctx->regs, &value);
4528 }
4529 else
4530 #endif
4531 {
4532 struct eval_agent_expr_context ax_ctx;
4533
4534 ax_ctx.regcache = ctx->regcache ();
4535 ax_ctx.tframe = NULL;
4536 ax_ctx.tpoint = tpoint;
4537
4538 err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
4539 }
4540 if (err != expr_eval_no_error)
4541 {
4542 record_tracepoint_error (tpoint, "condition", err);
4543 /* The error case must return false. */
4544 return 0;
4545 }
4546
4547 trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
4548 tpoint->number, paddress (tpoint->address),
4549 pulongest (value));
4550 return (value ? 1 : 0);
4551 }
4552
4553 /* See tracepoint.h. */
4554
4555 int
4556 agent_mem_read (struct eval_agent_expr_context *ctx,
4557 unsigned char *to, CORE_ADDR from, ULONGEST len)
4558 {
4559 unsigned char *mspace;
4560 ULONGEST remaining = len;
4561 unsigned short blocklen;
4562
4563 /* If a 'to' buffer is specified, use it. */
4564 if (to != NULL)
4565 return read_inferior_memory (from, to, len);
4566
4567 /* Otherwise, create a new memory block in the trace buffer. */
4568 while (remaining > 0)
4569 {
4570 size_t sp;
4571
4572 blocklen = (remaining > 65535 ? 65535 : remaining);
4573 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4574 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4575 if (mspace == NULL)
4576 return 1;
4577 /* Identify block as a memory block. */
4578 *mspace = 'M';
4579 ++mspace;
4580 /* Record address and size. */
4581 memcpy (mspace, &from, sizeof (from));
4582 mspace += sizeof (from);
4583 memcpy (mspace, &blocklen, sizeof (blocklen));
4584 mspace += sizeof (blocklen);
4585 /* Record the memory block proper. */
4586 if (read_inferior_memory (from, mspace, blocklen) != 0)
4587 return 1;
4588 trace_debug ("%d bytes recorded", blocklen);
4589 remaining -= blocklen;
4590 from += blocklen;
4591 }
4592 return 0;
4593 }
4594
4595 int
4596 agent_mem_read_string (struct eval_agent_expr_context *ctx,
4597 unsigned char *to, CORE_ADDR from, ULONGEST len)
4598 {
4599 unsigned char *buf, *mspace;
4600 ULONGEST remaining = len;
4601 unsigned short blocklen, i;
4602
4603 /* To save a bit of space, block lengths are 16-bit, so break large
4604 requests into multiple blocks. Bordering on overkill for strings,
4605 but it could happen that someone specifies a large max length. */
4606 while (remaining > 0)
4607 {
4608 size_t sp;
4609
4610 blocklen = (remaining > 65535 ? 65535 : remaining);
4611 /* We want working space to accumulate nonzero bytes, since
4612 traceframes must have a predecided size (otherwise it gets
4613 harder to wrap correctly for the circular case, etc). */
4614 buf = (unsigned char *) xmalloc (blocklen + 1);
4615 for (i = 0; i < blocklen; ++i)
4616 {
4617 /* Read the string one byte at a time, in case the string is
4618 at the end of a valid memory area - we don't want a
4619 correctly-terminated string to engender segvio
4620 complaints. */
4621 read_inferior_memory (from + i, buf + i, 1);
4622
4623 if (buf[i] == '\0')
4624 {
4625 blocklen = i + 1;
4626 /* Make sure outer loop stops now too. */
4627 remaining = blocklen;
4628 break;
4629 }
4630 }
4631 sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
4632 mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
4633 if (mspace == NULL)
4634 {
4635 xfree (buf);
4636 return 1;
4637 }
4638 /* Identify block as a memory block. */
4639 *mspace = 'M';
4640 ++mspace;
4641 /* Record address and size. */
4642 memcpy ((void *) mspace, (void *) &from, sizeof (from));
4643 mspace += sizeof (from);
4644 memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
4645 mspace += sizeof (blocklen);
4646 /* Copy the string contents. */
4647 memcpy ((void *) mspace, (void *) buf, blocklen);
4648 remaining -= blocklen;
4649 from += blocklen;
4650 xfree (buf);
4651 }
4652 return 0;
4653 }
4654
4655 /* Record the value of a trace state variable. */
4656
4657 int
4658 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
4659 {
4660 unsigned char *vspace;
4661 LONGEST val;
4662
4663 vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
4664 1 + sizeof (n) + sizeof (LONGEST));
4665 if (vspace == NULL)
4666 return 1;
4667 /* Identify block as a variable. */
4668 *vspace = 'V';
4669 /* Record variable's number and value. */
4670 memcpy (vspace + 1, &n, sizeof (n));
4671 val = get_trace_state_variable_value (n);
4672 memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
4673 trace_debug ("Variable %d recorded", n);
4674 return 0;
4675 }
4676
4677 #ifndef IN_PROCESS_AGENT
4678
4679 /* Callback for traceframe_walk_blocks, used to find a given block
4680 type in a traceframe. */
4681
4682 static int
4683 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
4684 {
4685 char *wantedp = (char *) data;
4686
4687 if (*wantedp == blocktype)
4688 return 1;
4689
4690 return 0;
4691 }
4692
4693 /* Walk over all traceframe blocks of the traceframe buffer starting
4694 at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
4695 block found, passing in DATA unmodified. If CALLBACK returns true,
4696 this returns a pointer to where the block is found. Returns NULL
4697 if no callback call returned true, indicating that all blocks have
4698 been walked. */
4699
4700 static unsigned char *
4701 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
4702 int tfnum,
4703 int (*callback) (char blocktype,
4704 unsigned char *dataptr,
4705 void *data),
4706 void *data)
4707 {
4708 unsigned char *dataptr;
4709
4710 if (datasize == 0)
4711 {
4712 trace_debug ("traceframe %d has no data", tfnum);
4713 return NULL;
4714 }
4715
4716 /* Iterate through a traceframe's blocks, looking for a block of the
4717 requested type. */
4718 for (dataptr = database;
4719 dataptr < database + datasize;
4720 /* nothing */)
4721 {
4722 char blocktype;
4723 unsigned short mlen;
4724
4725 if (dataptr == trace_buffer_wrap)
4726 {
4727 /* Adjust to reflect wrapping part of the frame around to
4728 the beginning. */
4729 datasize = dataptr - database;
4730 dataptr = database = trace_buffer_lo;
4731 }
4732
4733 blocktype = *dataptr++;
4734
4735 if ((*callback) (blocktype, dataptr, data))
4736 return dataptr;
4737
4738 switch (blocktype)
4739 {
4740 case 'R':
4741 /* Skip over the registers block. */
4742 dataptr += current_target_desc ()->registers_size;
4743 break;
4744 case 'M':
4745 /* Skip over the memory block. */
4746 dataptr += sizeof (CORE_ADDR);
4747 memcpy (&mlen, dataptr, sizeof (mlen));
4748 dataptr += (sizeof (mlen) + mlen);
4749 break;
4750 case 'V':
4751 /* Skip over the TSV block. */
4752 dataptr += (sizeof (int) + sizeof (LONGEST));
4753 break;
4754 case 'S':
4755 /* Skip over the static trace data block. */
4756 memcpy (&mlen, dataptr, sizeof (mlen));
4757 dataptr += (sizeof (mlen) + mlen);
4758 break;
4759 default:
4760 trace_debug ("traceframe %d has unknown block type 0x%x",
4761 tfnum, blocktype);
4762 return NULL;
4763 }
4764 }
4765
4766 return NULL;
4767 }
4768
4769 /* Look for the block of type TYPE_WANTED in the traceframe starting
4770 at DATABASE of DATASIZE bytes long. TFNUM is the traceframe
4771 number. */
4772
4773 static unsigned char *
4774 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
4775 int tfnum, char type_wanted)
4776 {
4777 return traceframe_walk_blocks (database, datasize, tfnum,
4778 match_blocktype, &type_wanted);
4779 }
4780
4781 static unsigned char *
4782 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
4783 {
4784 unsigned char *regblock;
4785
4786 regblock = traceframe_find_block_type (tframe->data,
4787 tframe->data_size,
4788 tfnum, 'R');
4789
4790 if (regblock == NULL)
4791 trace_debug ("traceframe %d has no register data", tfnum);
4792
4793 return regblock;
4794 }
4795
4796 /* Get registers from a traceframe. */
4797
4798 int
4799 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
4800 {
4801 unsigned char *dataptr;
4802 struct tracepoint *tpoint;
4803 struct traceframe *tframe;
4804
4805 tframe = find_traceframe (tfnum);
4806
4807 if (tframe == NULL)
4808 {
4809 trace_debug ("traceframe %d not found", tfnum);
4810 return 1;
4811 }
4812
4813 dataptr = traceframe_find_regblock (tframe, tfnum);
4814 if (dataptr == NULL)
4815 {
4816 /* Mark registers unavailable. */
4817 regcache->reset (REG_UNAVAILABLE);
4818
4819 /* We can generally guess at a PC, although this will be
4820 misleading for while-stepping frames and multi-location
4821 tracepoints. */
4822 tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
4823 if (tpoint != NULL)
4824 regcache_write_pc (regcache, tpoint->address);
4825 }
4826 else
4827 supply_regblock (regcache, dataptr);
4828
4829 return 0;
4830 }
4831
4832 static CORE_ADDR
4833 traceframe_get_pc (struct traceframe *tframe)
4834 {
4835 unsigned char *dataptr;
4836 const struct target_desc *tdesc = current_target_desc ();
4837
4838 dataptr = traceframe_find_regblock (tframe, -1);
4839 if (dataptr == NULL)
4840 return 0;
4841
4842 regcache regcache (tdesc, dataptr);
4843 return regcache_read_pc (&regcache);
4844 }
4845
4846 /* Read a requested block of memory from a trace frame. */
4847
4848 int
4849 traceframe_read_mem (int tfnum, CORE_ADDR addr,
4850 unsigned char *buf, ULONGEST length,
4851 ULONGEST *nbytes)
4852 {
4853 struct traceframe *tframe;
4854 unsigned char *database, *dataptr;
4855 unsigned int datasize;
4856 CORE_ADDR maddr;
4857 unsigned short mlen;
4858
4859 trace_debug ("traceframe_read_mem");
4860
4861 tframe = find_traceframe (tfnum);
4862
4863 if (!tframe)
4864 {
4865 trace_debug ("traceframe %d not found", tfnum);
4866 return 1;
4867 }
4868
4869 datasize = tframe->data_size;
4870 database = dataptr = &tframe->data[0];
4871
4872 /* Iterate through a traceframe's blocks, looking for memory. */
4873 while ((dataptr = traceframe_find_block_type (dataptr,
4874 datasize
4875 - (dataptr - database),
4876 tfnum, 'M')) != NULL)
4877 {
4878 memcpy (&maddr, dataptr, sizeof (maddr));
4879 dataptr += sizeof (maddr);
4880 memcpy (&mlen, dataptr, sizeof (mlen));
4881 dataptr += sizeof (mlen);
4882 trace_debug ("traceframe %d has %d bytes at %s",
4883 tfnum, mlen, paddress (maddr));
4884
4885 /* If the block includes the first part of the desired range,
4886 return as much it has; GDB will re-request the remainder,
4887 which might be in a different block of this trace frame. */
4888 if (maddr <= addr && addr < (maddr + mlen))
4889 {
4890 ULONGEST amt = (maddr + mlen) - addr;
4891 if (amt > length)
4892 amt = length;
4893
4894 memcpy (buf, dataptr + (addr - maddr), amt);
4895 *nbytes = amt;
4896 return 0;
4897 }
4898
4899 /* Skip over this block. */
4900 dataptr += mlen;
4901 }
4902
4903 trace_debug ("traceframe %d has no memory data for the desired region",
4904 tfnum);
4905
4906 *nbytes = 0;
4907 return 0;
4908 }
4909
4910 static int
4911 traceframe_read_tsv (int tsvnum, LONGEST *val)
4912 {
4913 client_state &cs = get_client_state ();
4914 int tfnum;
4915 struct traceframe *tframe;
4916 unsigned char *database, *dataptr;
4917 unsigned int datasize;
4918 int vnum;
4919 int found = 0;
4920
4921 trace_debug ("traceframe_read_tsv");
4922
4923 tfnum = cs.current_traceframe;
4924
4925 if (tfnum < 0)
4926 {
4927 trace_debug ("no current traceframe");
4928 return 1;
4929 }
4930
4931 tframe = find_traceframe (tfnum);
4932
4933 if (tframe == NULL)
4934 {
4935 trace_debug ("traceframe %d not found", tfnum);
4936 return 1;
4937 }
4938
4939 datasize = tframe->data_size;
4940 database = dataptr = &tframe->data[0];
4941
4942 /* Iterate through a traceframe's blocks, looking for the last
4943 matched tsv. */
4944 while ((dataptr = traceframe_find_block_type (dataptr,
4945 datasize
4946 - (dataptr - database),
4947 tfnum, 'V')) != NULL)
4948 {
4949 memcpy (&vnum, dataptr, sizeof (vnum));
4950 dataptr += sizeof (vnum);
4951
4952 trace_debug ("traceframe %d has variable %d", tfnum, vnum);
4953
4954 /* Check that this is the variable we want. */
4955 if (tsvnum == vnum)
4956 {
4957 memcpy (val, dataptr, sizeof (*val));
4958 found = 1;
4959 }
4960
4961 /* Skip over this block. */
4962 dataptr += sizeof (LONGEST);
4963 }
4964
4965 if (!found)
4966 trace_debug ("traceframe %d has no data for variable %d",
4967 tfnum, tsvnum);
4968 return !found;
4969 }
4970
4971 /* Callback for traceframe_walk_blocks. Builds a traceframe-info
4972 object. DATA is pointer to a string holding the traceframe-info
4973 object being built. */
4974
4975 static int
4976 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
4977 {
4978 std::string *buffer = (std::string *) data;
4979
4980 switch (blocktype)
4981 {
4982 case 'M':
4983 {
4984 unsigned short mlen;
4985 CORE_ADDR maddr;
4986
4987 memcpy (&maddr, dataptr, sizeof (maddr));
4988 dataptr += sizeof (maddr);
4989 memcpy (&mlen, dataptr, sizeof (mlen));
4990 dataptr += sizeof (mlen);
4991 string_xml_appendf (*buffer,
4992 "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
4993 paddress (maddr), phex_nz (mlen));
4994 break;
4995 }
4996 case 'V':
4997 {
4998 int vnum;
4999
5000 memcpy (&vnum, dataptr, sizeof (vnum));
5001 string_xml_appendf (*buffer, "<tvar id=\"%d\"/>\n", vnum);
5002 break;
5003 }
5004 case 'R':
5005 case 'S':
5006 {
5007 break;
5008 }
5009 default:
5010 warning ("Unhandled trace block type (%d) '%c ' "
5011 "while building trace frame info.",
5012 blocktype, blocktype);
5013 break;
5014 }
5015
5016 return 0;
5017 }
5018
5019 /* Build a traceframe-info object for traceframe number TFNUM into
5020 BUFFER. */
5021
5022 int
5023 traceframe_read_info (int tfnum, std::string *buffer)
5024 {
5025 struct traceframe *tframe;
5026
5027 trace_debug ("traceframe_read_info");
5028
5029 tframe = find_traceframe (tfnum);
5030
5031 if (!tframe)
5032 {
5033 trace_debug ("traceframe %d not found", tfnum);
5034 return 1;
5035 }
5036
5037 *buffer += "<traceframe-info>\n";
5038 traceframe_walk_blocks (tframe->data, tframe->data_size,
5039 tfnum, build_traceframe_info_xml, buffer);
5040 *buffer += "</traceframe-info>\n";
5041 return 0;
5042 }
5043
5044 /* Return the first fast tracepoint whose jump pad contains PC. */
5045
5046 static struct tracepoint *
5047 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
5048 {
5049 struct tracepoint *tpoint;
5050
5051 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5052 if (tpoint->type == fast_tracepoint)
5053 if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
5054 return tpoint;
5055
5056 return NULL;
5057 }
5058
5059 /* Return the first fast tracepoint whose trampoline contains PC. */
5060
5061 static struct tracepoint *
5062 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
5063 {
5064 struct tracepoint *tpoint;
5065
5066 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5067 {
5068 if (tpoint->type == fast_tracepoint
5069 && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
5070 return tpoint;
5071 }
5072
5073 return NULL;
5074 }
5075
5076 /* Return GDBserver's tracepoint that matches the IP Agent's
5077 tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
5078 address space. */
5079
5080 static struct tracepoint *
5081 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
5082 {
5083 struct tracepoint *tpoint;
5084
5085 for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
5086 if (tpoint->type == fast_tracepoint)
5087 if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
5088 return tpoint;
5089
5090 return NULL;
5091 }
5092
5093 #endif
5094
5095 /* The type of the object that is used to synchronize fast tracepoint
5096 collection. */
5097
5098 typedef struct collecting_t
5099 {
5100 /* The fast tracepoint number currently collecting. */
5101 uintptr_t tpoint;
5102
5103 /* A number that GDBserver can use to identify the thread that is
5104 presently holding the collect lock. This need not (and usually
5105 is not) the thread id, as getting the current thread ID usually
5106 requires a system call, which we want to avoid like the plague.
5107 Usually this is thread's TCB, found in the TLS (pseudo-)
5108 register, which is readable with a single insn on several
5109 architectures. */
5110 uintptr_t thread_area;
5111 } collecting_t;
5112
5113 #ifndef IN_PROCESS_AGENT
5114
5115 void
5116 force_unlock_trace_buffer (void)
5117 {
5118 write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
5119 }
5120
5121 /* Check if the thread identified by THREAD_AREA which is stopped at
5122 STOP_PC, is presently locking the fast tracepoint collection, and
5123 if so, gather some status of said collection. Returns 0 if the
5124 thread isn't collecting or in the jump pad at all. 1, if in the
5125 jump pad (or within gdb_collect) and hasn't executed the adjusted
5126 original insn yet (can set a breakpoint there and run to it). 2,
5127 if presently executing the adjusted original insn --- in which
5128 case, if we want to move the thread out of the jump pad, we need to
5129 single-step it until this function returns 0. */
5130
5131 fast_tpoint_collect_result
5132 fast_tracepoint_collecting (CORE_ADDR thread_area,
5133 CORE_ADDR stop_pc,
5134 struct fast_tpoint_collect_status *status)
5135 {
5136 CORE_ADDR ipa_collecting;
5137 CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
5138 CORE_ADDR ipa_gdb_trampoline_buffer;
5139 CORE_ADDR ipa_gdb_trampoline_buffer_end;
5140 struct tracepoint *tpoint;
5141 int needs_breakpoint;
5142
5143 /* The thread THREAD_AREA is either:
5144
5145 0. not collecting at all, not within the jump pad, or within
5146 gdb_collect or one of its callees.
5147
5148 1. in the jump pad and haven't reached gdb_collect
5149
5150 2. within gdb_collect (out of the jump pad) (collect is set)
5151
5152 3. we're in the jump pad, after gdb_collect having returned,
5153 possibly executing the adjusted insns.
5154
5155 For cases 1 and 3, `collecting' may or not be set. The jump pad
5156 doesn't have any complicated jump logic, so we can tell if the
5157 thread is executing the adjust original insn or not by just
5158 matching STOP_PC with known jump pad addresses. If we it isn't
5159 yet executing the original insn, set a breakpoint there, and let
5160 the thread run to it, so to quickly step over a possible (many
5161 insns) gdb_collect call. Otherwise, or when the breakpoint is
5162 hit, only a few (small number of) insns are left to be executed
5163 in the jump pad. Single-step the thread until it leaves the
5164 jump pad. */
5165
5166 again:
5167 tpoint = NULL;
5168 needs_breakpoint = 0;
5169 trace_debug ("fast_tracepoint_collecting");
5170
5171 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
5172 &ipa_gdb_jump_pad_buffer))
5173 {
5174 internal_error ("error extracting `gdb_jump_pad_buffer'");
5175 }
5176 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
5177 &ipa_gdb_jump_pad_buffer_end))
5178 {
5179 internal_error ("error extracting `gdb_jump_pad_buffer_end'");
5180 }
5181
5182 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
5183 &ipa_gdb_trampoline_buffer))
5184 {
5185 internal_error ("error extracting `gdb_trampoline_buffer'");
5186 }
5187 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
5188 &ipa_gdb_trampoline_buffer_end))
5189 {
5190 internal_error ("error extracting `gdb_trampoline_buffer_end'");
5191 }
5192
5193 if (ipa_gdb_jump_pad_buffer <= stop_pc
5194 && stop_pc < ipa_gdb_jump_pad_buffer_end)
5195 {
5196 /* We can tell which tracepoint(s) the thread is collecting by
5197 matching the jump pad address back to the tracepoint. */
5198 tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
5199 if (tpoint == NULL)
5200 {
5201 warning ("in jump pad, but no matching tpoint?");
5202 return fast_tpoint_collect_result::not_collecting;
5203 }
5204 else
5205 {
5206 trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
5207 "adj_insn(%s, %s)",
5208 tpoint->number, paddress (tpoint->address),
5209 paddress (tpoint->jump_pad),
5210 paddress (tpoint->jump_pad_end),
5211 paddress (tpoint->adjusted_insn_addr),
5212 paddress (tpoint->adjusted_insn_addr_end));
5213 }
5214
5215 /* Definitely in the jump pad. May or may not need
5216 fast-exit-jump-pad breakpoint. */
5217 if (tpoint->jump_pad <= stop_pc
5218 && stop_pc < tpoint->adjusted_insn_addr)
5219 needs_breakpoint = 1;
5220 }
5221 else if (ipa_gdb_trampoline_buffer <= stop_pc
5222 && stop_pc < ipa_gdb_trampoline_buffer_end)
5223 {
5224 /* We can tell which tracepoint(s) the thread is collecting by
5225 matching the trampoline address back to the tracepoint. */
5226 tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
5227 if (tpoint == NULL)
5228 {
5229 warning ("in trampoline, but no matching tpoint?");
5230 return fast_tpoint_collect_result::not_collecting;
5231 }
5232 else
5233 {
5234 trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
5235 tpoint->number, paddress (tpoint->address),
5236 paddress (tpoint->trampoline),
5237 paddress (tpoint->trampoline_end));
5238 }
5239
5240 /* Have not reached jump pad yet, but treat the trampoline as a
5241 part of the jump pad that is before the adjusted original
5242 instruction. */
5243 needs_breakpoint = 1;
5244 }
5245 else
5246 {
5247 collecting_t ipa_collecting_obj;
5248
5249 /* If `collecting' is set/locked, then the THREAD_AREA thread
5250 may or not be the one holding the lock. We have to read the
5251 lock to find out. */
5252
5253 if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
5254 &ipa_collecting))
5255 {
5256 trace_debug ("fast_tracepoint_collecting:"
5257 " failed reading 'collecting' in the inferior");
5258 return fast_tpoint_collect_result::not_collecting;
5259 }
5260
5261 if (!ipa_collecting)
5262 {
5263 trace_debug ("fast_tracepoint_collecting: not collecting"
5264 " (and nobody is).");
5265 return fast_tpoint_collect_result::not_collecting;
5266 }
5267
5268 /* Some thread is collecting. Check which. */
5269 if (read_inferior_memory (ipa_collecting,
5270 (unsigned char *) &ipa_collecting_obj,
5271 sizeof (ipa_collecting_obj)) != 0)
5272 goto again;
5273
5274 if (ipa_collecting_obj.thread_area != thread_area)
5275 {
5276 trace_debug ("fast_tracepoint_collecting: not collecting "
5277 "(another thread is)");
5278 return fast_tpoint_collect_result::not_collecting;
5279 }
5280
5281 tpoint
5282 = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
5283 if (tpoint == NULL)
5284 {
5285 warning ("fast_tracepoint_collecting: collecting, "
5286 "but tpoint %s not found?",
5287 paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
5288 return fast_tpoint_collect_result::not_collecting;
5289 }
5290
5291 /* The thread is within `gdb_collect', skip over the rest of
5292 fast tracepoint collection quickly using a breakpoint. */
5293 needs_breakpoint = 1;
5294 }
5295
5296 /* The caller wants a bit of status detail. */
5297 if (status != NULL)
5298 {
5299 status->tpoint_num = tpoint->number;
5300 status->tpoint_addr = tpoint->address;
5301 status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
5302 status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
5303 }
5304
5305 if (needs_breakpoint)
5306 {
5307 /* Hasn't executed the original instruction yet. Set breakpoint
5308 there, and wait till it's hit, then single-step until exiting
5309 the jump pad. */
5310
5311 trace_debug ("\
5312 fast_tracepoint_collecting, returning continue-until-break at %s",
5313 paddress (tpoint->adjusted_insn_addr));
5314
5315 return fast_tpoint_collect_result::before_insn; /* continue */
5316 }
5317 else
5318 {
5319 /* Just single-step until exiting the jump pad. */
5320
5321 trace_debug ("fast_tracepoint_collecting, returning "
5322 "need-single-step (%s-%s)",
5323 paddress (tpoint->adjusted_insn_addr),
5324 paddress (tpoint->adjusted_insn_addr_end));
5325
5326 return fast_tpoint_collect_result::at_insn; /* single-step */
5327 }
5328 }
5329
5330 #endif
5331
5332 #ifdef IN_PROCESS_AGENT
5333
5334 /* The global fast tracepoint collect lock. Points to a collecting_t
5335 object built on the stack by the jump pad, if presently locked;
5336 NULL if it isn't locked. Note that this lock *must* be set while
5337 executing any *function other than the jump pad. See
5338 fast_tracepoint_collecting. */
5339 extern "C" {
5340 IP_AGENT_EXPORT_VAR collecting_t *collecting;
5341 }
5342
5343 /* This is needed for -Wmissing-declarations. */
5344 IP_AGENT_EXPORT_FUNC void gdb_collect (struct tracepoint *tpoint,
5345 unsigned char *regs);
5346
5347 /* This routine, called from the jump pad (in asm) is designed to be
5348 called from the jump pads of fast tracepoints, thus it is on the
5349 critical path. */
5350
5351 IP_AGENT_EXPORT_FUNC void
5352 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
5353 {
5354 const struct target_desc *ipa_tdesc;
5355
5356 /* Don't do anything until the trace run is completely set up. */
5357 if (!tracing)
5358 return;
5359
5360 ipa_tdesc = get_ipa_tdesc (ipa_tdesc_idx);
5361 fast_tracepoint_ctx ctx (regs);
5362
5363 /* Wrap the regblock in a register cache (in the stack, we don't
5364 want to malloc here). */
5365 ctx.regspace = (unsigned char *) alloca (ipa_tdesc->registers_size);
5366 if (ctx.regspace == NULL)
5367 {
5368 trace_debug ("Trace buffer block allocation failed, skipping");
5369 return;
5370 }
5371
5372 memset (ctx.regspace, 0, ipa_tdesc->registers_size);
5373
5374 for (ctx.tpoint = tpoint;
5375 ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
5376 ctx.tpoint = ctx.tpoint->next)
5377 {
5378 if (!ctx.tpoint->enabled)
5379 continue;
5380
5381 /* Multiple tracepoints of different types, such as fast tracepoint and
5382 static tracepoint, can be set at the same address. */
5383 if (ctx.tpoint->type != tpoint->type)
5384 continue;
5385
5386 /* Test the condition if present, and collect if true. */
5387 if (ctx.tpoint->cond == NULL
5388 || condition_true_at_tracepoint (&ctx, ctx.tpoint))
5389 {
5390 collect_data_at_tracepoint (&ctx, ctx.tpoint->address,
5391 ctx.tpoint);
5392
5393 /* Note that this will cause original insns to be written back
5394 to where we jumped from, but that's OK because we're jumping
5395 back to the next whole instruction. This will go badly if
5396 instruction restoration is not atomic though. */
5397 if (stopping_tracepoint
5398 || trace_buffer_is_full
5399 || expr_eval_result != expr_eval_no_error)
5400 {
5401 stop_tracing ();
5402 break;
5403 }
5404 }
5405 else
5406 {
5407 /* If there was a condition and it evaluated to false, the only
5408 way we would stop tracing is if there was an error during
5409 condition expression evaluation. */
5410 if (expr_eval_result != expr_eval_no_error)
5411 {
5412 stop_tracing ();
5413 break;
5414 }
5415 }
5416 }
5417 }
5418
5419 /* These global variables points to the corresponding functions. This is
5420 necessary on powerpc64, where asking for function symbol address from gdb
5421 results in returning the actual code pointer, instead of the descriptor
5422 pointer. */
5423
5424 typedef void (*gdb_collect_ptr_type) (struct tracepoint *, unsigned char *);
5425 typedef ULONGEST (*get_raw_reg_ptr_type) (const unsigned char *, int);
5426 typedef LONGEST (*get_trace_state_variable_value_ptr_type) (int);
5427 typedef void (*set_trace_state_variable_value_ptr_type) (int, LONGEST);
5428
5429 extern "C" {
5430 IP_AGENT_EXPORT_VAR gdb_collect_ptr_type gdb_collect_ptr = gdb_collect;
5431 IP_AGENT_EXPORT_VAR get_raw_reg_ptr_type get_raw_reg_ptr = get_raw_reg;
5432 IP_AGENT_EXPORT_VAR get_trace_state_variable_value_ptr_type
5433 get_trace_state_variable_value_ptr = get_trace_state_variable_value;
5434 IP_AGENT_EXPORT_VAR set_trace_state_variable_value_ptr_type
5435 set_trace_state_variable_value_ptr = set_trace_state_variable_value;
5436 }
5437
5438 #endif
5439
5440 #ifndef IN_PROCESS_AGENT
5441
5442 CORE_ADDR
5443 get_raw_reg_func_addr (void)
5444 {
5445 CORE_ADDR res;
5446 if (read_inferior_data_pointer (ipa_sym_addrs.addr_get_raw_reg_ptr, &res))
5447 {
5448 error ("error extracting get_raw_reg_ptr");
5449 return 0;
5450 }
5451 return res;
5452 }
5453
5454 CORE_ADDR
5455 get_get_tsv_func_addr (void)
5456 {
5457 CORE_ADDR res;
5458 if (read_inferior_data_pointer (
5459 ipa_sym_addrs.addr_get_trace_state_variable_value_ptr, &res))
5460 {
5461 error ("error extracting get_trace_state_variable_value_ptr");
5462 return 0;
5463 }
5464 return res;
5465 }
5466
5467 CORE_ADDR
5468 get_set_tsv_func_addr (void)
5469 {
5470 CORE_ADDR res;
5471 if (read_inferior_data_pointer (
5472 ipa_sym_addrs.addr_set_trace_state_variable_value_ptr, &res))
5473 {
5474 error ("error extracting set_trace_state_variable_value_ptr");
5475 return 0;
5476 }
5477 return res;
5478 }
5479
5480 static void
5481 compile_tracepoint_condition (struct tracepoint *tpoint,
5482 CORE_ADDR *jump_entry)
5483 {
5484 CORE_ADDR entry_point = *jump_entry;
5485 enum eval_result_type err;
5486
5487 trace_debug ("Starting condition compilation for tracepoint %d\n",
5488 tpoint->number);
5489
5490 /* Initialize the global pointer to the code being built. */
5491 current_insn_ptr = *jump_entry;
5492
5493 emit_prologue ();
5494
5495 err = compile_bytecodes (tpoint->cond);
5496
5497 if (err == expr_eval_no_error)
5498 {
5499 emit_epilogue ();
5500
5501 /* Record the beginning of the compiled code. */
5502 tpoint->compiled_cond = entry_point;
5503
5504 trace_debug ("Condition compilation for tracepoint %d complete\n",
5505 tpoint->number);
5506 }
5507 else
5508 {
5509 /* Leave the unfinished code in situ, but don't point to it. */
5510
5511 tpoint->compiled_cond = 0;
5512
5513 trace_debug ("Condition compilation for tracepoint %d failed, "
5514 "error code %d",
5515 tpoint->number, err);
5516 }
5517
5518 /* Update the code pointer passed in. Note that we do this even if
5519 the compile fails, so that we can look at the partial results
5520 instead of letting them be overwritten. */
5521 *jump_entry = current_insn_ptr;
5522
5523 /* Leave a gap, to aid dump decipherment. */
5524 *jump_entry += 16;
5525 }
5526
5527 /* The base pointer of the IPA's heap. This is the only memory the
5528 IPA is allowed to use. The IPA should _not_ call the inferior's
5529 `malloc' during operation. That'd be slow, and, most importantly,
5530 it may not be safe. We may be collecting a tracepoint in a signal
5531 handler, for example. */
5532 static CORE_ADDR target_tp_heap;
5533
5534 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
5535 to 8 bytes. */
5536
5537 static CORE_ADDR
5538 target_malloc (ULONGEST size)
5539 {
5540 CORE_ADDR ptr;
5541
5542 if (target_tp_heap == 0)
5543 {
5544 /* We have the pointer *address*, need what it points to. */
5545 if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
5546 &target_tp_heap))
5547 {
5548 internal_error ("couldn't get target heap head pointer");
5549 }
5550 }
5551
5552 ptr = target_tp_heap;
5553 target_tp_heap += size;
5554
5555 /* Pad to 8-byte alignment. */
5556 target_tp_heap = ((target_tp_heap + 7) & ~0x7);
5557
5558 return ptr;
5559 }
5560
5561 static CORE_ADDR
5562 download_agent_expr (struct agent_expr *expr)
5563 {
5564 CORE_ADDR expr_addr;
5565 CORE_ADDR expr_bytes;
5566
5567 expr_addr = target_malloc (sizeof (*expr));
5568 target_write_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
5569
5570 expr_bytes = target_malloc (expr->length);
5571 write_inferior_data_pointer (expr_addr + offsetof (struct agent_expr, bytes),
5572 expr_bytes);
5573 target_write_memory (expr_bytes, expr->bytes, expr->length);
5574
5575 return expr_addr;
5576 }
5577
5578 /* Align V up to N bits. */
5579 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
5580
5581 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller. */
5582
5583 static void
5584 download_tracepoint_1 (struct tracepoint *tpoint)
5585 {
5586 struct tracepoint target_tracepoint;
5587 CORE_ADDR tpptr = 0;
5588
5589 gdb_assert (tpoint->type == fast_tracepoint);
5590
5591 if (tpoint->cond != NULL && target_emit_ops () != NULL)
5592 {
5593 CORE_ADDR jentry, jump_entry;
5594
5595 jentry = jump_entry = get_jump_space_head ();
5596
5597 if (tpoint->cond != NULL)
5598 {
5599 /* Pad to 8-byte alignment. (needed?) */
5600 /* Actually this should be left for the target to
5601 decide. */
5602 jentry = UALIGN (jentry, 8);
5603
5604 compile_tracepoint_condition (tpoint, &jentry);
5605 }
5606
5607 /* Pad to 8-byte alignment. */
5608 jentry = UALIGN (jentry, 8);
5609 claim_jump_space (jentry - jump_entry);
5610 }
5611
5612 target_tracepoint = *tpoint;
5613
5614 tpptr = target_malloc (sizeof (*tpoint));
5615 tpoint->obj_addr_on_target = tpptr;
5616
5617 /* Write the whole object. We'll fix up its pointers in a bit.
5618 Assume no next for now. This is fixed up above on the next
5619 iteration, if there's any. */
5620 target_tracepoint.next = NULL;
5621 /* Need to clear this here too, since we're downloading the
5622 tracepoints before clearing our own copy. */
5623 target_tracepoint.hit_count = 0;
5624
5625 target_write_memory (tpptr, (unsigned char *) &target_tracepoint,
5626 sizeof (target_tracepoint));
5627
5628 if (tpoint->cond)
5629 write_inferior_data_pointer (tpptr
5630 + offsetof (struct tracepoint, cond),
5631 download_agent_expr (tpoint->cond));
5632
5633 if (tpoint->numactions)
5634 {
5635 int i;
5636 CORE_ADDR actions_array;
5637
5638 /* The pointers array. */
5639 actions_array
5640 = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
5641 write_inferior_data_pointer (tpptr + offsetof (struct tracepoint,
5642 actions),
5643 actions_array);
5644
5645 /* Now for each pointer, download the action. */
5646 for (i = 0; i < tpoint->numactions; i++)
5647 {
5648 struct tracepoint_action *action = tpoint->actions[i];
5649 CORE_ADDR ipa_action = tracepoint_action_download (action);
5650
5651 if (ipa_action != 0)
5652 write_inferior_data_pointer (actions_array
5653 + i * sizeof (*tpoint->actions),
5654 ipa_action);
5655 }
5656 }
5657 }
5658
5659 #define IPA_PROTO_FAST_TRACE_FLAG 0
5660 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
5661 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
5662 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
5663 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
5664
5665 /* Send a command to agent to download and install tracepoint TPOINT. */
5666
5667 static int
5668 tracepoint_send_agent (struct tracepoint *tpoint)
5669 {
5670 char buf[IPA_CMD_BUF_SIZE];
5671 char *p;
5672 int i, ret;
5673
5674 p = buf;
5675 strcpy (p, "FastTrace:");
5676 p += 10;
5677
5678 COPY_FIELD_TO_BUF (p, tpoint, number);
5679 COPY_FIELD_TO_BUF (p, tpoint, address);
5680 COPY_FIELD_TO_BUF (p, tpoint, type);
5681 COPY_FIELD_TO_BUF (p, tpoint, enabled);
5682 COPY_FIELD_TO_BUF (p, tpoint, step_count);
5683 COPY_FIELD_TO_BUF (p, tpoint, pass_count);
5684 COPY_FIELD_TO_BUF (p, tpoint, numactions);
5685 COPY_FIELD_TO_BUF (p, tpoint, hit_count);
5686 COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
5687 COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
5688 COPY_FIELD_TO_BUF (p, tpoint, orig_size);
5689
5690 /* condition */
5691 p = agent_expr_send (p, tpoint->cond);
5692
5693 /* tracepoint_action */
5694 for (i = 0; i < tpoint->numactions; i++)
5695 {
5696 struct tracepoint_action *action = tpoint->actions[i];
5697
5698 p[0] = action->type;
5699 p = tracepoint_action_send (&p[1], action);
5700 }
5701
5702 get_jump_space_head ();
5703 /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
5704 agent can use jump pad from it. */
5705 if (tpoint->type == fast_tracepoint)
5706 {
5707 memcpy (p, &gdb_jump_pad_head, 8);
5708 p += 8;
5709 }
5710
5711 ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
5712 if (ret)
5713 return ret;
5714
5715 if (!startswith (buf, "OK"))
5716 return 1;
5717
5718 /* The value of tracepoint's target address is stored in BUF. */
5719 memcpy (&tpoint->obj_addr_on_target,
5720 &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
5721
5722 if (tpoint->type == fast_tracepoint)
5723 {
5724 unsigned char *insn
5725 = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
5726 int fjump_size;
5727
5728 trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
5729 (unsigned int) tpoint->obj_addr_on_target,
5730 (unsigned int) gdb_jump_pad_head);
5731
5732 memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
5733
5734 /* This has been done in agent. We should also set up record for it. */
5735 memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
5736 /* Wire it in. */
5737 tpoint->handle
5738 = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
5739 }
5740
5741 return 0;
5742 }
5743
5744 static void
5745 download_tracepoint (struct tracepoint *tpoint)
5746 {
5747 struct tracepoint *tp, *tp_prev;
5748
5749 if (tpoint->type != fast_tracepoint)
5750 return;
5751
5752 download_tracepoint_1 (tpoint);
5753
5754 /* Find the previous entry of TPOINT, which is fast tracepoint or
5755 static tracepoint. */
5756 tp_prev = NULL;
5757 for (tp = tracepoints; tp != tpoint; tp = tp->next)
5758 {
5759 if (tp->type == fast_tracepoint)
5760 tp_prev = tp;
5761 }
5762
5763 if (tp_prev)
5764 {
5765 CORE_ADDR tp_prev_target_next_addr;
5766
5767 /* Insert TPOINT after TP_PREV in IPA. */
5768 if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
5769 + offsetof (struct tracepoint, next),
5770 &tp_prev_target_next_addr))
5771 {
5772 internal_error ("error reading `tp_prev->next'");
5773 }
5774
5775 /* tpoint->next = tp_prev->next */
5776 write_inferior_data_pointer (tpoint->obj_addr_on_target
5777 + offsetof (struct tracepoint, next),
5778 tp_prev_target_next_addr);
5779 /* tp_prev->next = tpoint */
5780 write_inferior_data_pointer (tp_prev->obj_addr_on_target
5781 + offsetof (struct tracepoint, next),
5782 tpoint->obj_addr_on_target);
5783 }
5784 else
5785 /* First object in list, set the head pointer in the
5786 inferior. */
5787 write_inferior_data_pointer (ipa_sym_addrs.addr_tracepoints,
5788 tpoint->obj_addr_on_target);
5789
5790 }
5791
5792 static void
5793 download_trace_state_variables (void)
5794 {
5795 CORE_ADDR ptr = 0, prev_ptr = 0;
5796 struct trace_state_variable *tsv;
5797
5798 /* Start out empty. */
5799 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables, 0);
5800
5801 for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
5802 {
5803 struct trace_state_variable target_tsv;
5804
5805 /* TSV's with a getter have been initialized equally in both the
5806 inferior and GDBserver. Skip them. */
5807 if (tsv->getter != NULL)
5808 continue;
5809
5810 target_tsv = *tsv;
5811
5812 prev_ptr = ptr;
5813 ptr = target_malloc (sizeof (*tsv));
5814
5815 if (tsv == trace_state_variables)
5816 {
5817 /* First object in list, set the head pointer in the
5818 inferior. */
5819
5820 write_inferior_data_pointer (ipa_sym_addrs.addr_trace_state_variables,
5821 ptr);
5822 }
5823 else
5824 {
5825 write_inferior_data_pointer (prev_ptr
5826 + offsetof (struct trace_state_variable,
5827 next),
5828 ptr);
5829 }
5830
5831 /* Write the whole object. We'll fix up its pointers in a bit.
5832 Assume no next, fixup when needed. */
5833 target_tsv.next = NULL;
5834
5835 target_write_memory (ptr, (unsigned char *) &target_tsv,
5836 sizeof (target_tsv));
5837
5838 if (tsv->name != NULL)
5839 {
5840 size_t size = strlen (tsv->name) + 1;
5841 CORE_ADDR name_addr = target_malloc (size);
5842 target_write_memory (name_addr,
5843 (unsigned char *) tsv->name, size);
5844 write_inferior_data_pointer (ptr
5845 + offsetof (struct trace_state_variable,
5846 name),
5847 name_addr);
5848 }
5849
5850 gdb_assert (tsv->getter == NULL);
5851 }
5852
5853 if (prev_ptr != 0)
5854 {
5855 /* Fixup the next pointer in the last item in the list. */
5856 write_inferior_data_pointer (prev_ptr
5857 + offsetof (struct trace_state_variable,
5858 next), 0);
5859 }
5860 }
5861
5862 /* Upload complete trace frames out of the IP Agent's trace buffer
5863 into GDBserver's trace buffer. This always uploads either all or
5864 no trace frames. This is the counter part of
5865 `trace_alloc_trace_buffer'. See its description of the atomic
5866 syncing mechanism. */
5867
5868 static void
5869 upload_fast_traceframes (void)
5870 {
5871 unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
5872 unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
5873 CORE_ADDR tf;
5874 struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
5875 unsigned int curr_tbctrl_idx;
5876 unsigned int ipa_trace_buffer_ctrl_curr;
5877 unsigned int ipa_trace_buffer_ctrl_curr_old;
5878 CORE_ADDR ipa_trace_buffer_ctrl_addr;
5879 struct breakpoint *about_to_request_buffer_space_bkpt;
5880 CORE_ADDR ipa_trace_buffer_lo;
5881 CORE_ADDR ipa_trace_buffer_hi;
5882
5883 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5884 &ipa_traceframe_read_count_racy))
5885 {
5886 /* This will happen in most targets if the current thread is
5887 running. */
5888 return;
5889 }
5890
5891 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5892 &ipa_traceframe_write_count_racy))
5893 return;
5894
5895 trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
5896 ipa_traceframe_write_count_racy
5897 - ipa_traceframe_read_count_racy,
5898 ipa_traceframe_write_count_racy,
5899 ipa_traceframe_read_count_racy);
5900
5901 if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
5902 return;
5903
5904 about_to_request_buffer_space_bkpt
5905 = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
5906 NULL);
5907
5908 if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5909 &ipa_trace_buffer_ctrl_curr))
5910 return;
5911
5912 ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
5913
5914 curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
5915
5916 {
5917 unsigned int prev, counter;
5918
5919 /* Update the token, with new counters, and the GDBserver stamp
5920 bit. Always reuse the current TBC index. */
5921 prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
5922 counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
5923
5924 ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
5925 | (prev << 12)
5926 | counter
5927 | curr_tbctrl_idx);
5928 }
5929
5930 if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
5931 ipa_trace_buffer_ctrl_curr))
5932 return;
5933
5934 trace_debug ("Lib: Committed %08x -> %08x",
5935 ipa_trace_buffer_ctrl_curr_old,
5936 ipa_trace_buffer_ctrl_curr);
5937
5938 /* Re-read these, now that we've installed the
5939 `about_to_request_buffer_space' breakpoint/lock. A thread could
5940 have finished a traceframe between the last read of these
5941 counters and setting the breakpoint above. If we start
5942 uploading, we never want to leave this function with
5943 traceframe_read_count != 0, otherwise, GDBserver could end up
5944 incrementing the counter tokens more than once (due to event loop
5945 nesting), which would break the IP agent's "effective" detection
5946 (see trace_alloc_trace_buffer). */
5947 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
5948 &ipa_traceframe_read_count))
5949 return;
5950 if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
5951 &ipa_traceframe_write_count))
5952 return;
5953
5954 if (debug_threads)
5955 {
5956 trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
5957 ipa_traceframe_write_count - ipa_traceframe_read_count,
5958 ipa_traceframe_write_count, ipa_traceframe_read_count);
5959
5960 if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
5961 || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
5962 trace_debug ("note that ipa_traceframe_count's parts changed");
5963 }
5964
5965 /* Get the address of the current TBC object (the IP agent has an
5966 array of 3 such objects). The index is stored in the TBC
5967 token. */
5968 ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
5969 ipa_trace_buffer_ctrl_addr
5970 += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
5971
5972 if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
5973 (unsigned char *) &ipa_trace_buffer_ctrl,
5974 sizeof (struct ipa_trace_buffer_control)))
5975 return;
5976
5977 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
5978 &ipa_trace_buffer_lo))
5979 return;
5980 if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
5981 &ipa_trace_buffer_hi))
5982 return;
5983
5984 /* Offsets are easier to grok for debugging than raw addresses,
5985 especially for the small trace buffer sizes that are useful for
5986 testing. */
5987 trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
5988 "endfree=%d wrap=%d hi=%d",
5989 curr_tbctrl_idx,
5990 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
5991 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
5992 (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
5993 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
5994 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
5995
5996 /* Note that the IPA's buffer is always circular. */
5997
5998 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
5999
6000 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ) \
6001 ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
6002
6003 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ) \
6004 (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) \
6005 - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
6006 ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo) \
6007 : 0))
6008
6009 tf = IPA_FIRST_TRACEFRAME ();
6010
6011 while (ipa_traceframe_write_count - ipa_traceframe_read_count)
6012 {
6013 struct tracepoint *tpoint;
6014 struct traceframe *tframe;
6015 unsigned char *block;
6016 struct traceframe ipa_tframe;
6017
6018 if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
6019 offsetof (struct traceframe, data)))
6020 error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
6021
6022 if (ipa_tframe.tpnum == 0)
6023 {
6024 internal_error ("Uploading: No (more) fast traceframes, but"
6025 " ipa_traceframe_count == %u??\n",
6026 ipa_traceframe_write_count
6027 - ipa_traceframe_read_count);
6028 }
6029
6030 /* Note that this will be incorrect for multi-location
6031 tracepoints... */
6032 tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
6033
6034 tframe = add_traceframe (tpoint);
6035 if (tframe == NULL)
6036 {
6037 trace_buffer_is_full = 1;
6038 trace_debug ("Uploading: trace buffer is full");
6039 }
6040 else
6041 {
6042 /* Copy the whole set of blocks in one go for now. FIXME:
6043 split this in smaller blocks. */
6044 block = add_traceframe_block (tframe, tpoint,
6045 ipa_tframe.data_size);
6046 if (block != NULL)
6047 {
6048 if (read_inferior_memory (tf
6049 + offsetof (struct traceframe, data),
6050 block, ipa_tframe.data_size))
6051 error ("Uploading: Couldn't read traceframe data at %s\n",
6052 paddress (tf + offsetof (struct traceframe, data)));
6053 }
6054
6055 trace_debug ("Uploading: traceframe didn't fit");
6056 finish_traceframe (tframe);
6057 }
6058
6059 tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
6060
6061 /* If we freed the traceframe that wrapped around, go back
6062 to the non-wrap case. */
6063 if (tf < ipa_trace_buffer_ctrl.start)
6064 {
6065 trace_debug ("Lib: Discarding past the wraparound");
6066 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6067 }
6068 ipa_trace_buffer_ctrl.start = tf;
6069 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
6070 ++ipa_traceframe_read_count;
6071
6072 if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
6073 && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
6074 {
6075 trace_debug ("Lib: buffer is fully empty. "
6076 "Trace buffer [%d] start=%d free=%d endfree=%d",
6077 curr_tbctrl_idx,
6078 (int) (ipa_trace_buffer_ctrl.start
6079 - ipa_trace_buffer_lo),
6080 (int) (ipa_trace_buffer_ctrl.free
6081 - ipa_trace_buffer_lo),
6082 (int) (ipa_trace_buffer_ctrl.end_free
6083 - ipa_trace_buffer_lo));
6084
6085 ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
6086 ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
6087 ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
6088 ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
6089 }
6090
6091 trace_debug ("Uploaded a traceframe\n"
6092 "Lib: Trace buffer [%d] start=%d free=%d "
6093 "endfree=%d wrap=%d hi=%d",
6094 curr_tbctrl_idx,
6095 (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
6096 (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
6097 (int) (ipa_trace_buffer_ctrl.end_free
6098 - ipa_trace_buffer_lo),
6099 (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
6100 (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
6101 }
6102
6103 if (target_write_memory (ipa_trace_buffer_ctrl_addr,
6104 (unsigned char *) &ipa_trace_buffer_ctrl,
6105 sizeof (struct ipa_trace_buffer_control)))
6106 return;
6107
6108 write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
6109 ipa_traceframe_read_count);
6110
6111 trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
6112
6113 target_pause_all (true);
6114
6115 delete_breakpoint (about_to_request_buffer_space_bkpt);
6116 about_to_request_buffer_space_bkpt = NULL;
6117
6118 target_unpause_all (true);
6119
6120 if (trace_buffer_is_full)
6121 stop_tracing ();
6122 }
6123 #endif
6124
6125 #ifdef IN_PROCESS_AGENT
6126
6127 IP_AGENT_EXPORT_VAR char cmd_buf[IPA_CMD_BUF_SIZE];
6128
6129 #endif /* IN_PROCESS_AGENT */
6130
6131 #ifndef IN_PROCESS_AGENT
6132
6133 /* Ask the in-process agent to run a command. Since we don't want to
6134 have to handle the IPA hitting breakpoints while running the
6135 command, we pause all threads, remove all breakpoints, and then set
6136 the helper thread re-running. We communicate with the helper
6137 thread by means of direct memory xfering, and a socket for
6138 synchronization. */
6139
6140 static int
6141 run_inferior_command (char *cmd, int len)
6142 {
6143 int err = -1;
6144 int pid = current_thread->id.pid ();
6145
6146 trace_debug ("run_inferior_command: running: %s", cmd);
6147
6148 target_pause_all (false);
6149 uninsert_all_breakpoints ();
6150
6151 err = agent_run_command (pid, cmd, len);
6152
6153 reinsert_all_breakpoints ();
6154 target_unpause_all (false);
6155
6156 return err;
6157 }
6158
6159 #else /* !IN_PROCESS_AGENT */
6160
6161 #include <sys/socket.h>
6162 #include <sys/un.h>
6163
6164 #ifndef UNIX_PATH_MAX
6165 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
6166 #endif
6167
6168 /* Where we put the socked used for synchronization. */
6169 #define SOCK_DIR P_tmpdir
6170
6171 /* Thread ID of the helper thread. GDBserver reads this to know which
6172 is the help thread. This is an LWP id on Linux. */
6173 extern "C" {
6174 IP_AGENT_EXPORT_VAR int helper_thread_id;
6175 }
6176
6177 static int
6178 init_named_socket (const char *name)
6179 {
6180 int result, fd;
6181 struct sockaddr_un addr;
6182
6183 result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
6184 if (result == -1)
6185 {
6186 warning ("socket creation failed: %s", safe_strerror (errno));
6187 return -1;
6188 }
6189
6190 addr.sun_family = AF_UNIX;
6191
6192 if (strlen (name) >= ARRAY_SIZE (addr.sun_path))
6193 {
6194 warning ("socket name too long for sockaddr_un::sun_path field: %s", name);
6195 return -1;
6196 }
6197
6198 strcpy (addr.sun_path, name);
6199
6200 result = access (name, F_OK);
6201 if (result == 0)
6202 {
6203 /* File exists. */
6204 result = unlink (name);
6205 if (result == -1)
6206 {
6207 warning ("unlink failed: %s", safe_strerror (errno));
6208 close (fd);
6209 return -1;
6210 }
6211 warning ("socket %s already exists; overwriting", name);
6212 }
6213
6214 result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
6215 if (result == -1)
6216 {
6217 warning ("bind failed: %s", safe_strerror (errno));
6218 close (fd);
6219 return -1;
6220 }
6221
6222 result = listen (fd, 1);
6223 if (result == -1)
6224 {
6225 warning ("listen: %s", safe_strerror (errno));
6226 close (fd);
6227 return -1;
6228 }
6229
6230 return fd;
6231 }
6232
6233 static char agent_socket_name[UNIX_PATH_MAX];
6234
6235 static int
6236 gdb_agent_socket_init (void)
6237 {
6238 int result, fd;
6239
6240 result = snprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
6241 SOCK_DIR, getpid ());
6242 if (result >= UNIX_PATH_MAX)
6243 {
6244 trace_debug ("string overflow allocating socket name");
6245 return -1;
6246 }
6247
6248 fd = init_named_socket (agent_socket_name);
6249 if (fd < 0)
6250 warning ("Error initializing named socket (%s) for communication with the "
6251 "ust helper thread. Check that directory exists and that it "
6252 "is writable.", agent_socket_name);
6253
6254 return fd;
6255 }
6256
6257 #include <sys/syscall.h>
6258
6259 static void
6260 gdb_agent_remove_socket (void)
6261 {
6262 unlink (agent_socket_name);
6263 }
6264
6265 /* Helper thread of agent. */
6266
6267 static void *
6268 gdb_agent_helper_thread (void *arg)
6269 {
6270 int listen_fd;
6271
6272 atexit (gdb_agent_remove_socket);
6273
6274 while (1)
6275 {
6276 listen_fd = gdb_agent_socket_init ();
6277
6278 if (helper_thread_id == 0)
6279 helper_thread_id = syscall (SYS_gettid);
6280
6281 if (listen_fd == -1)
6282 {
6283 warning ("could not create sync socket");
6284 break;
6285 }
6286
6287 while (1)
6288 {
6289 socklen_t tmp;
6290 struct sockaddr_un sockaddr;
6291 int fd;
6292 char buf[1];
6293 int ret;
6294 int stop_loop = 0;
6295
6296 tmp = sizeof (sockaddr);
6297
6298 do
6299 {
6300 fd = accept (listen_fd, (struct sockaddr *) &sockaddr, &tmp);
6301 }
6302 /* It seems an ERESTARTSYS can escape out of accept. */
6303 while (fd == -512 || (fd == -1 && errno == EINTR));
6304
6305 if (fd < 0)
6306 {
6307 warning ("Accept returned %d, error: %s",
6308 fd, safe_strerror (errno));
6309 break;
6310 }
6311
6312 do
6313 {
6314 ret = read (fd, buf, 1);
6315 } while (ret == -1 && errno == EINTR);
6316
6317 if (ret == -1)
6318 {
6319 warning ("reading socket (fd=%d) failed with %s",
6320 fd, safe_strerror (errno));
6321 close (fd);
6322 break;
6323 }
6324
6325 if (cmd_buf[0])
6326 {
6327 if (startswith (cmd_buf, "close"))
6328 {
6329 stop_loop = 1;
6330 }
6331 }
6332
6333 /* Fix compiler's warning: ignoring return value of 'write'. */
6334 ret = write (fd, buf, 1);
6335 close (fd);
6336
6337 if (stop_loop)
6338 {
6339 close (listen_fd);
6340 unlink (agent_socket_name);
6341
6342 /* Sleep endlessly to wait the whole inferior stops. This
6343 thread can not exit because GDB or GDBserver may still need
6344 'current_thread' (representing this thread) to access
6345 inferior memory. Otherwise, this thread exits earlier than
6346 other threads, and 'current_thread' is set to NULL. */
6347 while (1)
6348 sleep (10);
6349 }
6350 }
6351 }
6352
6353 return NULL;
6354 }
6355
6356 #include <signal.h>
6357 #include <pthread.h>
6358
6359 extern "C" {
6360 IP_AGENT_EXPORT_VAR int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
6361 }
6362
6363 static void
6364 gdb_agent_init (void)
6365 {
6366 int res;
6367 pthread_t thread;
6368 sigset_t new_mask;
6369 sigset_t orig_mask;
6370
6371 /* We want the helper thread to be as transparent as possible, so
6372 have it inherit an all-signals-blocked mask. */
6373
6374 sigfillset (&new_mask);
6375 res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
6376 if (res)
6377 perror_with_name ("pthread_sigmask (1)");
6378
6379 res = pthread_create (&thread,
6380 NULL,
6381 gdb_agent_helper_thread,
6382 NULL);
6383
6384 res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
6385 if (res)
6386 perror_with_name ("pthread_sigmask (2)");
6387
6388 while (helper_thread_id == 0)
6389 usleep (1);
6390 }
6391
6392 #include <sys/mman.h>
6393
6394 IP_AGENT_EXPORT_VAR char *gdb_tp_heap_buffer;
6395 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer;
6396 IP_AGENT_EXPORT_VAR char *gdb_jump_pad_buffer_end;
6397 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer;
6398 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_end;
6399 IP_AGENT_EXPORT_VAR char *gdb_trampoline_buffer_error;
6400
6401 /* Record the result of getting buffer space for fast tracepoint
6402 trampolines. Any error message is copied, since caller may not be
6403 using persistent storage. */
6404
6405 void
6406 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
6407 {
6408 gdb_trampoline_buffer = (char *) (uintptr_t) begin;
6409 gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
6410 if (errmsg)
6411 strncpy (gdb_trampoline_buffer_error, errmsg, 99);
6412 else
6413 strcpy (gdb_trampoline_buffer_error, "no buffer passed");
6414 }
6415
6416 static void __attribute__ ((constructor))
6417 initialize_tracepoint_ftlib (void)
6418 {
6419 initialize_tracepoint ();
6420
6421 gdb_agent_init ();
6422 }
6423
6424 #ifndef HAVE_GETAUXVAL
6425 /* Retrieve the value of TYPE from the auxiliary vector. If TYPE is not
6426 found, 0 is returned. This function is provided if glibc is too old. */
6427
6428 unsigned long
6429 getauxval (unsigned long type)
6430 {
6431 unsigned long data[2];
6432 FILE *f = fopen ("/proc/self/auxv", "r");
6433 unsigned long value = 0;
6434
6435 if (f == NULL)
6436 return 0;
6437
6438 while (fread (data, sizeof (data), 1, f) > 0)
6439 {
6440 if (data[0] == type)
6441 {
6442 value = data[1];
6443 break;
6444 }
6445 }
6446
6447 fclose (f);
6448 return value;
6449 }
6450 #endif
6451
6452 #endif /* IN_PROCESS_AGENT */
6453
6454 /* Return a timestamp, expressed as microseconds of the usual Unix
6455 time. (As the result is a 64-bit number, it will not overflow any
6456 time soon.) */
6457
6458 static LONGEST
6459 get_timestamp (void)
6460 {
6461 using namespace std::chrono;
6462
6463 steady_clock::time_point now = steady_clock::now ();
6464 return duration_cast<microseconds> (now.time_since_epoch ()).count ();
6465 }
6466
6467 void
6468 initialize_tracepoint (void)
6469 {
6470 /* Start with the default size. */
6471 init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
6472
6473 /* Wire trace state variable 1 to be the timestamp. This will be
6474 uploaded to GDB upon connection and become one of its trace state
6475 variables. (In case you're wondering, if GDB already has a trace
6476 variable numbered 1, it will be renumbered.) */
6477 create_trace_state_variable (1, 0);
6478 set_trace_state_variable_name (1, "trace_timestamp");
6479 set_trace_state_variable_getter (1, get_timestamp);
6480
6481 #ifdef IN_PROCESS_AGENT
6482 {
6483 int pagesize;
6484 size_t jump_pad_size;
6485
6486 pagesize = sysconf (_SC_PAGE_SIZE);
6487 if (pagesize == -1)
6488 perror_with_name ("sysconf");
6489
6490 #define SCRATCH_BUFFER_NPAGES 20
6491
6492 jump_pad_size = pagesize * SCRATCH_BUFFER_NPAGES;
6493
6494 gdb_tp_heap_buffer = (char *) xmalloc (5 * 1024 * 1024);
6495 gdb_jump_pad_buffer = (char *) alloc_jump_pad_buffer (jump_pad_size);
6496 if (gdb_jump_pad_buffer == NULL)
6497 perror_with_name ("mmap");
6498 gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + jump_pad_size;
6499 }
6500
6501 gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
6502
6503 /* It's not a fatal error for something to go wrong with trampoline
6504 buffer setup, but it can be mysterious, so create a channel to
6505 report back on what went wrong, using a fixed size since we may
6506 not be able to allocate space later when the problem occurs. */
6507 gdb_trampoline_buffer_error = (char *) xmalloc (IPA_BUFSIZ);
6508
6509 strcpy (gdb_trampoline_buffer_error, "No errors reported");
6510
6511 initialize_low_tracepoint ();
6512 #endif
6513 }