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