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