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