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