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