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