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