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