gdb/gdbserver/tracepoint.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Tracepoint code for remote server for GDB.
  2.    Copyright (C) 2009-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "server.h"
  15. #include "tracepoint.h"
  16. #include "gdbthread.h"
  17. #include "agent.h"
  18. #include "rsp-low.h"

  19. #include <ctype.h>
  20. #include <fcntl.h>
  21. #include <unistd.h>
  22. #include <sys/time.h>
  23. #include <inttypes.h>
  24. #include <stdint.h>

  25. #include "ax.h"
  26. #include "tdesc.h"

  27. #define DEFAULT_TRACE_BUFFER_SIZE 5242880 /* 5*1024*1024 */

  28. /* This file is built for both GDBserver, and the in-process
  29.    agent (IPA), a shared library that includes a tracing agent that is
  30.    loaded by the inferior to support fast tracepoints.  Fast
  31.    tracepoints (or more accurately, jump based tracepoints) are
  32.    implemented by patching the tracepoint location with a jump into a
  33.    small trampoline function whose job is to save the register state,
  34.    call the in-process tracing agent, and then execute the original
  35.    instruction that was under the tracepoint jump (possibly adjusted,
  36.    if PC-relative, or some such).

  37.    The current synchronization design is pull based.  That means,
  38.    GDBserver does most of the work, by peeking/poking at the inferior
  39.    agent's memory directly for downloading tracepoint and associated
  40.    objects, and for uploading trace frames.  Whenever the IPA needs
  41.    something from GDBserver (trace buffer is full, tracing stopped for
  42.    some reason, etc.) the IPA calls a corresponding hook function
  43.    where GDBserver has placed a breakpoint.

  44.    Each of the agents has its own trace buffer.  When browsing the
  45.    trace frames built from slow and fast tracepoints from GDB (tfind
  46.    mode), there's no guarantee the user is seeing the trace frames in
  47.    strict chronological creation order, although, GDBserver tries to
  48.    keep the order relatively reasonable, by syncing the trace buffers
  49.    at appropriate times.

  50. */

  51. #ifdef IN_PROCESS_AGENT

  52. static void trace_vdebug (const char *, ...) ATTRIBUTE_PRINTF (1, 2);

  53. static void
  54. trace_vdebug (const char *fmt, ...)
  55. {
  56.   char buf[1024];
  57.   va_list ap;

  58.   va_start (ap, fmt);
  59.   vsprintf (buf, fmt, ap);
  60.   fprintf (stderr, PROG "/tracepoint: %s\n", buf);
  61.   va_end (ap);
  62. }

  63. #define trace_debug_1(level, fmt, args...)        \
  64.   do {                                                \
  65.     if (level <= debug_threads)                \
  66.       trace_vdebug ((fmt), ##args);                \
  67.   } while (0)

  68. #else

  69. #define trace_debug_1(level, fmt, args...)        \
  70.   do {                                                \
  71.     if (level <= debug_threads)                        \
  72.       {                                                \
  73.         debug_printf ((fmt), ##args);                \
  74.         debug_printf ("\n");                        \
  75.       }                                                \
  76.   } while (0)

  77. #endif

  78. #define trace_debug(FMT, args...)                \
  79.   trace_debug_1 (1, FMT, ##args)

  80. #if defined(__GNUC__)
  81. #  define ATTR_USED __attribute__((used))
  82. #  define ATTR_NOINLINE __attribute__((noinline))
  83. #  define ATTR_CONSTRUCTOR __attribute__ ((constructor))
  84. #else
  85. #  define ATTR_USED
  86. #  define ATTR_NOINLINE
  87. #  define ATTR_CONSTRUCTOR
  88. #endif

  89. /* Make sure the functions the IPA needs to export (symbols GDBserver
  90.    needs to query GDB about) are exported.  */

  91. #ifdef IN_PROCESS_AGENT
  92. # if defined _WIN32 || defined __CYGWIN__
  93. #   define IP_AGENT_EXPORT __declspec(dllexport) ATTR_USED
  94. # else
  95. #   if __GNUC__ >= 4
  96. #     define IP_AGENT_EXPORT \
  97.   __attribute__ ((visibility("default"))) ATTR_USED
  98. #   else
  99. #     define IP_AGENT_EXPORT ATTR_USED
  100. #   endif
  101. # endif
  102. #else
  103. #  define IP_AGENT_EXPORT
  104. #endif

  105. /* Prefix exported symbols, for good citizenship.  All the symbols
  106.    that need exporting are defined in this module.  */
  107. #ifdef IN_PROCESS_AGENT
  108. # define gdb_tp_heap_buffer gdb_agent_gdb_tp_heap_buffer
  109. # define gdb_jump_pad_buffer gdb_agent_gdb_jump_pad_buffer
  110. # define gdb_jump_pad_buffer_end gdb_agent_gdb_jump_pad_buffer_end
  111. # define gdb_trampoline_buffer gdb_agent_gdb_trampoline_buffer
  112. # define gdb_trampoline_buffer_end gdb_agent_gdb_trampoline_buffer_end
  113. # define gdb_trampoline_buffer_error gdb_agent_gdb_trampoline_buffer_error
  114. # define collecting gdb_agent_collecting
  115. # define gdb_collect gdb_agent_gdb_collect
  116. # define stop_tracing gdb_agent_stop_tracing
  117. # define flush_trace_buffer gdb_agent_flush_trace_buffer
  118. # define about_to_request_buffer_space gdb_agent_about_to_request_buffer_space
  119. # define trace_buffer_is_full gdb_agent_trace_buffer_is_full
  120. # define stopping_tracepoint gdb_agent_stopping_tracepoint
  121. # define expr_eval_result gdb_agent_expr_eval_result
  122. # define error_tracepoint gdb_agent_error_tracepoint
  123. # define tracepoints gdb_agent_tracepoints
  124. # define tracing gdb_agent_tracing
  125. # define trace_buffer_ctrl gdb_agent_trace_buffer_ctrl
  126. # define trace_buffer_ctrl_curr gdb_agent_trace_buffer_ctrl_curr
  127. # define trace_buffer_lo gdb_agent_trace_buffer_lo
  128. # define trace_buffer_hi gdb_agent_trace_buffer_hi
  129. # define traceframe_read_count gdb_agent_traceframe_read_count
  130. # define traceframe_write_count gdb_agent_traceframe_write_count
  131. # define traceframes_created gdb_agent_traceframes_created
  132. # define trace_state_variables gdb_agent_trace_state_variables
  133. # define get_raw_reg gdb_agent_get_raw_reg
  134. # define get_trace_state_variable_value \
  135.   gdb_agent_get_trace_state_variable_value
  136. # define set_trace_state_variable_value \
  137.   gdb_agent_set_trace_state_variable_value
  138. # define ust_loaded gdb_agent_ust_loaded
  139. # define helper_thread_id gdb_agent_helper_thread_id
  140. # define cmd_buf gdb_agent_cmd_buf
  141. #endif

  142. #ifndef IN_PROCESS_AGENT

  143. /* Addresses of in-process agent's symbols GDBserver cares about.  */

  144. struct ipa_sym_addresses
  145. {
  146.   CORE_ADDR addr_gdb_tp_heap_buffer;
  147.   CORE_ADDR addr_gdb_jump_pad_buffer;
  148.   CORE_ADDR addr_gdb_jump_pad_buffer_end;
  149.   CORE_ADDR addr_gdb_trampoline_buffer;
  150.   CORE_ADDR addr_gdb_trampoline_buffer_end;
  151.   CORE_ADDR addr_gdb_trampoline_buffer_error;
  152.   CORE_ADDR addr_collecting;
  153.   CORE_ADDR addr_gdb_collect;
  154.   CORE_ADDR addr_stop_tracing;
  155.   CORE_ADDR addr_flush_trace_buffer;
  156.   CORE_ADDR addr_about_to_request_buffer_space;
  157.   CORE_ADDR addr_trace_buffer_is_full;
  158.   CORE_ADDR addr_stopping_tracepoint;
  159.   CORE_ADDR addr_expr_eval_result;
  160.   CORE_ADDR addr_error_tracepoint;
  161.   CORE_ADDR addr_tracepoints;
  162.   CORE_ADDR addr_tracing;
  163.   CORE_ADDR addr_trace_buffer_ctrl;
  164.   CORE_ADDR addr_trace_buffer_ctrl_curr;
  165.   CORE_ADDR addr_trace_buffer_lo;
  166.   CORE_ADDR addr_trace_buffer_hi;
  167.   CORE_ADDR addr_traceframe_read_count;
  168.   CORE_ADDR addr_traceframe_write_count;
  169.   CORE_ADDR addr_traceframes_created;
  170.   CORE_ADDR addr_trace_state_variables;
  171.   CORE_ADDR addr_get_raw_reg;
  172.   CORE_ADDR addr_get_trace_state_variable_value;
  173.   CORE_ADDR addr_set_trace_state_variable_value;
  174.   CORE_ADDR addr_ust_loaded;
  175. };

  176. static struct
  177. {
  178.   const char *name;
  179.   int offset;
  180.   int required;
  181. } symbol_list[] = {
  182.   IPA_SYM(gdb_tp_heap_buffer),
  183.   IPA_SYM(gdb_jump_pad_buffer),
  184.   IPA_SYM(gdb_jump_pad_buffer_end),
  185.   IPA_SYM(gdb_trampoline_buffer),
  186.   IPA_SYM(gdb_trampoline_buffer_end),
  187.   IPA_SYM(gdb_trampoline_buffer_error),
  188.   IPA_SYM(collecting),
  189.   IPA_SYM(gdb_collect),
  190.   IPA_SYM(stop_tracing),
  191.   IPA_SYM(flush_trace_buffer),
  192.   IPA_SYM(about_to_request_buffer_space),
  193.   IPA_SYM(trace_buffer_is_full),
  194.   IPA_SYM(stopping_tracepoint),
  195.   IPA_SYM(expr_eval_result),
  196.   IPA_SYM(error_tracepoint),
  197.   IPA_SYM(tracepoints),
  198.   IPA_SYM(tracing),
  199.   IPA_SYM(trace_buffer_ctrl),
  200.   IPA_SYM(trace_buffer_ctrl_curr),
  201.   IPA_SYM(trace_buffer_lo),
  202.   IPA_SYM(trace_buffer_hi),
  203.   IPA_SYM(traceframe_read_count),
  204.   IPA_SYM(traceframe_write_count),
  205.   IPA_SYM(traceframes_created),
  206.   IPA_SYM(trace_state_variables),
  207.   IPA_SYM(get_raw_reg),
  208.   IPA_SYM(get_trace_state_variable_value),
  209.   IPA_SYM(set_trace_state_variable_value),
  210.   IPA_SYM(ust_loaded),
  211. };

  212. static struct ipa_sym_addresses ipa_sym_addrs;

  213. static int read_inferior_integer (CORE_ADDR symaddr, int *val);

  214. /* Returns true if both the in-process agent library and the static
  215.    tracepoints libraries are loaded in the inferior, and agent has
  216.    capability on static tracepoints.  */

  217. static int
  218. in_process_agent_supports_ust (void)
  219. {
  220.   int loaded = 0;

  221.   if (!agent_loaded_p ())
  222.     {
  223.       warning ("In-process agent not loaded");
  224.       return 0;
  225.     }

  226.   if (agent_capability_check (AGENT_CAPA_STATIC_TRACE))
  227.     {
  228.       /* Agent understands static tracepoint, then check whether UST is in
  229.          fact loaded in the inferior.  */
  230.       if (read_inferior_integer (ipa_sym_addrs.addr_ust_loaded, &loaded))
  231.         {
  232.           warning ("Error reading ust_loaded in lib");
  233.           return 0;
  234.         }

  235.       return loaded;
  236.     }
  237.   else
  238.     return 0;
  239. }

  240. static void
  241. write_e_ipa_not_loaded (char *buffer)
  242. {
  243.   sprintf (buffer,
  244.            "E.In-process agent library not loaded in process.  "
  245.            "Fast and static tracepoints unavailable.");
  246. }

  247. /* Write an error to BUFFER indicating that UST isn't loaded in the
  248.    inferior.  */

  249. static void
  250. write_e_ust_not_loaded (char *buffer)
  251. {
  252. #ifdef HAVE_UST
  253.   sprintf (buffer,
  254.            "E.UST library not loaded in process.  "
  255.            "Static tracepoints unavailable.");
  256. #else
  257.   sprintf (buffer, "E.GDBserver was built without static tracepoints support");
  258. #endif
  259. }

  260. /* If the in-process agent library isn't loaded in the inferior, write
  261.    an error to BUFFER, and return 1.  Otherwise, return 0.  */

  262. static int
  263. maybe_write_ipa_not_loaded (char *buffer)
  264. {
  265.   if (!agent_loaded_p ())
  266.     {
  267.       write_e_ipa_not_loaded (buffer);
  268.       return 1;
  269.     }
  270.   return 0;
  271. }

  272. /* If the in-process agent library and the ust (static tracepoints)
  273.    library aren't loaded in the inferior, write an error to BUFFER,
  274.    and return 1.  Otherwise, return 0.  */

  275. static int
  276. maybe_write_ipa_ust_not_loaded (char *buffer)
  277. {
  278.   if (!agent_loaded_p ())
  279.     {
  280.       write_e_ipa_not_loaded (buffer);
  281.       return 1;
  282.     }
  283.   else if (!in_process_agent_supports_ust ())
  284.     {
  285.       write_e_ust_not_loaded (buffer);
  286.       return 1;
  287.     }
  288.   return 0;
  289. }

  290. /* Cache all future symbols that the tracepoints module might request.
  291.    We can not request symbols at arbitrary states in the remote
  292.    protocol, only when the client tells us that new symbols are
  293.    available.  So when we load the in-process library, make sure to
  294.    check the entire list.  */

  295. void
  296. tracepoint_look_up_symbols (void)
  297. {
  298.   int i;

  299.   if (agent_loaded_p ())
  300.     return;

  301.   for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
  302.     {
  303.       CORE_ADDR *addrp =
  304.         (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);

  305.       if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
  306.         {
  307.           if (debug_threads)
  308.             debug_printf ("symbol `%s' not found\n", symbol_list[i].name);
  309.           return;
  310.         }
  311.     }

  312.   agent_look_up_symbols (NULL);
  313. }

  314. #endif

  315. /* GDBserver places a breakpoint on the IPA's version (which is a nop)
  316.    of the "stop_tracing" function.  When this breakpoint is hit,
  317.    tracing stopped in the IPA for some reason.  E.g., due to
  318.    tracepoint reaching the pass count, hitting conditional expression
  319.    evaluation error, etc.

  320.    The IPA's trace buffer is never in circular tracing mode: instead,
  321.    GDBserver's is, and whenever the in-process buffer fills, it calls
  322.    "flush_trace_buffer", which triggers an internal breakpoint.
  323.    GDBserver reacts to this breakpoint by pulling the meanwhile
  324.    collected data.  Old frames discarding is always handled on the
  325.    GDBserver side.  */

  326. #ifdef IN_PROCESS_AGENT
  327. int
  328. read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
  329. {
  330.   memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
  331.   return 0;
  332. }

  333. /* Call this in the functions where GDBserver places a breakpoint, so
  334.    that the compiler doesn't try to be clever and skip calling the
  335.    function at all.  This is necessary, even if we tell the compiler
  336.    to not inline said functions.  */

  337. #if defined(__GNUC__)
  338. #  define UNKNOWN_SIDE_EFFECTS() asm ("")
  339. #else
  340. #  define UNKNOWN_SIDE_EFFECTS() do {} while (0)
  341. #endif

  342. IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
  343. stop_tracing (void)
  344. {
  345.   /* GDBserver places breakpoint here.  */
  346.   UNKNOWN_SIDE_EFFECTS();
  347. }

  348. IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
  349. flush_trace_buffer (void)
  350. {
  351.   /* GDBserver places breakpoint here.  */
  352.   UNKNOWN_SIDE_EFFECTS();
  353. }

  354. #endif

  355. #ifndef IN_PROCESS_AGENT
  356. static int
  357. tracepoint_handler (CORE_ADDR address)
  358. {
  359.   trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
  360.                paddress (address));
  361.   return 0;
  362. }

  363. /* Breakpoint at "stop_tracing" in the inferior lib.  */
  364. struct breakpoint *stop_tracing_bkpt;
  365. static int stop_tracing_handler (CORE_ADDR);

  366. /* Breakpoint at "flush_trace_buffer" in the inferior lib.  */
  367. struct breakpoint *flush_trace_buffer_bkpt;
  368. static int flush_trace_buffer_handler (CORE_ADDR);

  369. static void download_trace_state_variables (void);
  370. static void upload_fast_traceframes (void);

  371. static int run_inferior_command (char *cmd, int len);

  372. static int
  373. read_inferior_integer (CORE_ADDR symaddr, int *val)
  374. {
  375.   return read_inferior_memory (symaddr, (unsigned char *) val,
  376.                                sizeof (*val));
  377. }

  378. struct tracepoint;
  379. static int tracepoint_send_agent (struct tracepoint *tpoint);

  380. static int
  381. read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
  382. {
  383.   return read_inferior_memory (symaddr, (unsigned char *) val,
  384.                                sizeof (*val));
  385. }

  386. static int
  387. read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
  388. {
  389.   void *pval = (void *) (uintptr_t) val;
  390.   int ret;

  391.   ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
  392.   *val = (uintptr_t) pval;
  393.   return ret;
  394. }

  395. static int
  396. write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
  397. {
  398.   void *pval = (void *) (uintptr_t) val;
  399.   return write_inferior_memory (symaddr,
  400.                                 (unsigned char *) &pval, sizeof (pval));
  401. }

  402. static int
  403. write_inferior_integer (CORE_ADDR symaddr, int val)
  404. {
  405.   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
  406. }

  407. static int
  408. write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
  409. {
  410.   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
  411. }

  412. static CORE_ADDR target_malloc (ULONGEST size);
  413. static int write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr);

  414. #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD)        \
  415.   do {                                                        \
  416.     memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
  417.     BUF += sizeof ((OBJ)->FIELD);                        \
  418.   } while (0)

  419. #endif

  420. /* Operations on various types of tracepoint actions.  */

  421. struct tracepoint_action;

  422. struct tracepoint_action_ops
  423. {
  424.   /* Download tracepoint action ACTION to IPA.  Return the address of action
  425.      in IPA/inferior.  */
  426.   CORE_ADDR (*download) (const struct tracepoint_action *action);

  427.   /* Send ACTION to agent via command buffer started from BUFFER.  Return
  428.      updated head of command buffer.  */
  429.   char* (*send) (char *buffer, const struct tracepoint_action *action);
  430. };

  431. /* Base action.  Concrete actions inherit this.  */

  432. struct tracepoint_action
  433. {
  434. #ifndef IN_PROCESS_AGENT
  435.   const struct tracepoint_action_ops *ops;
  436. #endif
  437.   char type;
  438. };

  439. /* An 'M' (collect memory) action.  */
  440. struct collect_memory_action
  441. {
  442.   struct tracepoint_action base;

  443.   ULONGEST addr;
  444.   ULONGEST len;
  445.   int32_t basereg;
  446. };

  447. /* An 'R' (collect registers) action.  */

  448. struct collect_registers_action
  449. {
  450.   struct tracepoint_action base;
  451. };

  452. /* An 'X' (evaluate expression) action.  */

  453. struct eval_expr_action
  454. {
  455.   struct tracepoint_action base;

  456.   struct agent_expr *expr;
  457. };

  458. /* An 'L' (collect static trace data) action.  */
  459. struct collect_static_trace_data_action
  460. {
  461.   struct tracepoint_action base;
  462. };

  463. #ifndef IN_PROCESS_AGENT
  464. static CORE_ADDR
  465. m_tracepoint_action_download (const struct tracepoint_action *action)
  466. {
  467.   int size_in_ipa = (sizeof (struct collect_memory_action)
  468.                      - offsetof (struct tracepoint_action, type));
  469.   CORE_ADDR ipa_action = target_malloc (size_in_ipa);

  470.   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
  471.                          size_in_ipa);

  472.   return ipa_action;
  473. }
  474. static char *
  475. m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
  476. {
  477.   struct collect_memory_action *maction
  478.     = (struct collect_memory_action *) action;

  479.   COPY_FIELD_TO_BUF (buffer, maction, addr);
  480.   COPY_FIELD_TO_BUF (buffer, maction, len);
  481.   COPY_FIELD_TO_BUF (buffer, maction, basereg);

  482.   return buffer;
  483. }

  484. static const struct tracepoint_action_ops m_tracepoint_action_ops =
  485. {
  486.   m_tracepoint_action_download,
  487.   m_tracepoint_action_send,
  488. };

  489. static CORE_ADDR
  490. r_tracepoint_action_download (const struct tracepoint_action *action)
  491. {
  492.   int size_in_ipa = (sizeof (struct collect_registers_action)
  493.                      - offsetof (struct tracepoint_action, type));
  494.   CORE_ADDR ipa_action  = target_malloc (size_in_ipa);

  495.   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
  496.                         size_in_ipa);

  497.   return ipa_action;
  498. }

  499. static char *
  500. r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
  501. {
  502.   return buffer;
  503. }

  504. static const struct tracepoint_action_ops r_tracepoint_action_ops =
  505. {
  506.   r_tracepoint_action_download,
  507.   r_tracepoint_action_send,
  508. };

  509. static CORE_ADDR download_agent_expr (struct agent_expr *expr);

  510. static CORE_ADDR
  511. x_tracepoint_action_download (const struct tracepoint_action *action)
  512. {
  513.   int size_in_ipa = (sizeof (struct eval_expr_action)
  514.                      - offsetof (struct tracepoint_action, type));
  515.   CORE_ADDR ipa_action = target_malloc (size_in_ipa);
  516.   CORE_ADDR expr;

  517.   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
  518.                          size_in_ipa);
  519.   expr = download_agent_expr (((struct eval_expr_action *)action)->expr);
  520.   write_inferior_data_ptr (ipa_action + offsetof (struct eval_expr_action, expr)
  521.                            - offsetof (struct tracepoint_action, type),
  522.                            expr);

  523.   return ipa_action;
  524. }

  525. /* Copy agent expression AEXPR to buffer pointed by P.  If AEXPR is NULL,
  526.    copy 0 to P.  Return updated header of buffer.  */

  527. static char *
  528. agent_expr_send (char *p, const struct agent_expr *aexpr)
  529. {
  530.   /* Copy the length of condition first, and then copy its
  531.      content.  */
  532.   if (aexpr == NULL)
  533.     {
  534.       memset (p, 0, 4);
  535.       p += 4;
  536.     }
  537.   else
  538.     {
  539.       memcpy (p, &aexpr->length, 4);
  540.       p +=4;

  541.       memcpy (p, aexpr->bytes, aexpr->length);
  542.       p += aexpr->length;
  543.     }
  544.   return p;
  545. }

  546. static char *
  547. x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
  548. {
  549.   struct eval_expr_action *eaction = (struct eval_expr_action *) action;

  550.   return agent_expr_send (buffer, eaction->expr);
  551. }

  552. static const struct tracepoint_action_ops x_tracepoint_action_ops =
  553. {
  554.   x_tracepoint_action_download,
  555.   x_tracepoint_action_send,
  556. };

  557. static CORE_ADDR
  558. l_tracepoint_action_download (const struct tracepoint_action *action)
  559. {
  560.   int size_in_ipa = (sizeof (struct collect_static_trace_data_action)
  561.                      - offsetof (struct tracepoint_action, type));
  562.   CORE_ADDR ipa_action = target_malloc (size_in_ipa);

  563.   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
  564.                          size_in_ipa);

  565.   return ipa_action;
  566. }

  567. static char *
  568. l_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
  569. {
  570.   return buffer;
  571. }

  572. static const struct tracepoint_action_ops l_tracepoint_action_ops =
  573. {
  574.   l_tracepoint_action_download,
  575.   l_tracepoint_action_send,
  576. };
  577. #endif

  578. /* This structure describes a piece of the source-level definition of
  579.    the tracepoint.  The contents are not interpreted by the target,
  580.    but preserved verbatim for uploading upon reconnection.  */

  581. struct source_string
  582. {
  583.   /* The type of string, such as "cond" for a conditional.  */
  584.   char *type;

  585.   /* The source-level string itself.  For the sake of target
  586.      debugging, we store it in plaintext, even though it is always
  587.      transmitted in hex.  */
  588.   char *str;

  589.   /* Link to the next one in the list.  We link them in the order
  590.      received, in case some make up an ordered list of commands or
  591.      some such.  */
  592.   struct source_string *next;
  593. };

  594. enum tracepoint_type
  595. {
  596.   /* Trap based tracepoint.  */
  597.   trap_tracepoint,

  598.   /* A fast tracepoint implemented with a jump instead of a trap.  */
  599.   fast_tracepoint,

  600.   /* A static tracepoint, implemented by a program call into a tracing
  601.      library.  */
  602.   static_tracepoint
  603. };

  604. struct tracepoint_hit_ctx;

  605. typedef enum eval_result_type (*condfn) (struct tracepoint_hit_ctx *,
  606.                                          ULONGEST *);

  607. /* The definition of a tracepoint.  */

  608. /* Tracepoints may have multiple locations, each at a different
  609.    address.  This can occur with optimizations, template
  610.    instantiation, etc.  Since the locations may be in different
  611.    scopes, the conditions and actions may be different for each
  612.    location.  Our target version of tracepoints is more like GDB's
  613.    notion of "breakpoint locations", but we have almost nothing that
  614.    is not per-location, so we bother having two kinds of objects.  The
  615.    key consequence is that numbers are not unique, and that it takes
  616.    both number and address to identify a tracepoint uniquely.  */

  617. struct tracepoint
  618. {
  619.   /* The number of the tracepoint, as specified by GDB.  Several
  620.      tracepoint objects here may share a number.  */
  621.   uint32_t number;

  622.   /* Address at which the tracepoint is supposed to trigger.  Several
  623.      tracepoints may share an address.  */
  624.   CORE_ADDR address;

  625.   /* Tracepoint type.  */
  626.   enum tracepoint_type type;

  627.   /* True if the tracepoint is currently enabled.  */
  628.   int8_t enabled;

  629.   /* The number of single steps that will be performed after each
  630.      tracepoint hit.  */
  631.   uint64_t step_count;

  632.   /* The number of times the tracepoint may be hit before it will
  633.      terminate the entire tracing run.  */
  634.   uint64_t pass_count;

  635.   /* Pointer to the agent expression that is the tracepoint's
  636.      conditional, or NULL if the tracepoint is unconditional.  */
  637.   struct agent_expr *cond;

  638.   /* The list of actions to take when the tracepoint triggers.  */
  639.   uint32_t numactions;
  640.   struct tracepoint_action **actions;

  641.   /* Count of the times we've hit this tracepoint during the run.
  642.      Note that while-stepping steps are not counted as "hits".  */
  643.   uint64_t hit_count;

  644.   /* Cached sum of the sizes of traceframes created by this point.  */
  645.   uint64_t traceframe_usage;

  646.   CORE_ADDR compiled_cond;

  647.   /* Link to the next tracepoint in the list.  */
  648.   struct tracepoint *next;

  649. #ifndef IN_PROCESS_AGENT
  650.   /* The list of actions to take when the tracepoint triggers, in
  651.      string/packet form.  */
  652.   char **actions_str;

  653.   /* The collection of strings that describe the tracepoint as it was
  654.      entered into GDB.  These are not used by the target, but are
  655.      reported back to GDB upon reconnection.  */
  656.   struct source_string *source_strings;

  657.   /* The number of bytes displaced by fast tracepoints. It may subsume
  658.      multiple instructions, for multi-byte fast tracepoints.  This
  659.      field is only valid for fast tracepoints.  */
  660.   uint32_t orig_size;

  661.   /* Only for fast tracepoints.  */
  662.   CORE_ADDR obj_addr_on_target;

  663.   /* Address range where the original instruction under a fast
  664.      tracepoint was relocated to.  (_end is actually one byte past
  665.      the end).  */
  666.   CORE_ADDR adjusted_insn_addr;
  667.   CORE_ADDR adjusted_insn_addr_end;

  668.   /* The address range of the piece of the jump pad buffer that was
  669.      assigned to this fast tracepoint.  (_end is actually one byte
  670.      past the end).*/
  671.   CORE_ADDR jump_pad;
  672.   CORE_ADDR jump_pad_end;

  673.   /* The address range of the piece of the trampoline buffer that was
  674.      assigned to this fast tracepoint.  (_end is actually one byte
  675.      past the end).  */
  676.   CORE_ADDR trampoline;
  677.   CORE_ADDR trampoline_end;

  678.   /* The list of actions to take while in a stepping loop.  These
  679.      fields are only valid for patch-based tracepoints.  */
  680.   int num_step_actions;
  681.   struct tracepoint_action **step_actions;
  682.   /* Same, but in string/packet form.  */
  683.   char **step_actions_str;

  684.   /* Handle returned by the breakpoint or tracepoint module when we
  685.      inserted the trap or jump, or hooked into a static tracepoint.
  686.      NULL if we haven't inserted it yet.  */
  687.   void *handle;
  688. #endif

  689. };

  690. #ifndef IN_PROCESS_AGENT

  691. /* Given `while-stepping', a thread may be collecting data for more
  692.    than one tracepoint simultaneously.  On the other hand, the same
  693.    tracepoint with a while-stepping action may be hit by more than one
  694.    thread simultaneously (but not quite, each thread could be handling
  695.    a different step).  Each thread holds a list of these objects,
  696.    representing the current step of each while-stepping action being
  697.    collected.  */

  698. struct wstep_state
  699. {
  700.   struct wstep_state *next;

  701.   /* The tracepoint number.  */
  702.   int tp_number;
  703.   /* The tracepoint's address.  */
  704.   CORE_ADDR tp_address;

  705.   /* The number of the current step in this 'while-stepping'
  706.      action.  */
  707.   long current_step;
  708. };

  709. #endif

  710. /* The linked list of all tracepoints.  Marked explicitly as used as
  711.    the in-process library doesn't use it for the fast tracepoints
  712.    support.  */
  713. IP_AGENT_EXPORT struct tracepoint *tracepoints ATTR_USED;

  714. #ifndef IN_PROCESS_AGENT

  715. /* Pointer to the last tracepoint in the list, new tracepoints are
  716.    linked in at the end.  */

  717. static struct tracepoint *last_tracepoint;
  718. #endif

  719. /* The first tracepoint to exceed its pass count.  */

  720. IP_AGENT_EXPORT struct tracepoint *stopping_tracepoint;

  721. /* True if the trace buffer is full or otherwise no longer usable.  */

  722. IP_AGENT_EXPORT int trace_buffer_is_full;

  723. static enum eval_result_type expr_eval_result = expr_eval_no_error;

  724. #ifndef IN_PROCESS_AGENT

  725. static const char *eval_result_names[] =
  726.   {
  727.     "terror:in the attic"/* this should never be reported */
  728.     "terror:empty expression",
  729.     "terror:empty stack",
  730.     "terror:stack overflow",
  731.     "terror:stack underflow",
  732.     "terror:unhandled opcode",
  733.     "terror:unrecognized opcode",
  734.     "terror:divide by zero"
  735.   };

  736. #endif

  737. /* The tracepoint in which the error occurred.  */

  738. static struct tracepoint *error_tracepoint;

  739. struct trace_state_variable
  740. {
  741.   /* This is the name of the variable as used in GDB.  The target
  742.      doesn't use the name, but needs to have it for saving and
  743.      reconnection purposes.  */
  744.   char *name;

  745.   /* This number identifies the variable uniquely.  Numbers may be
  746.      assigned either by the target (in the case of builtin variables),
  747.      or by GDB, and are presumed unique during the course of a trace
  748.      experiment.  */
  749.   int number;

  750.   /* The variable's initial value, a 64-bit signed integer always.  */
  751.   LONGEST initial_value;

  752.   /* The variable's value, a 64-bit signed integer always.  */
  753.   LONGEST value;

  754.   /* Pointer to a getter function, used to supply computed values.  */
  755.   LONGEST (*getter) (void);

  756.   /* Link to the next variable.  */
  757.   struct trace_state_variable *next;
  758. };

  759. /* Linked list of all trace state variables.  */

  760. #ifdef IN_PROCESS_AGENT
  761. struct trace_state_variable *alloced_trace_state_variables;
  762. #endif

  763. IP_AGENT_EXPORT struct trace_state_variable *trace_state_variables;

  764. /* The results of tracing go into a fixed-size space known as the
  765.    "trace buffer".  Because usage follows a limited number of
  766.    patterns, we manage it ourselves rather than with malloc.  Basic
  767.    rules are that we create only one trace frame at a time, each is
  768.    variable in size, they are never moved once created, and we only
  769.    discard if we are doing a circular buffer, and then only the oldest
  770.    ones.  Each trace frame includes its own size, so we don't need to
  771.    link them together, and the trace frame number is relative to the
  772.    first one, so we don't need to record numbers.  A trace frame also
  773.    records the number of the tracepoint that created it.  The data
  774.    itself is a series of blocks, each introduced by a single character
  775.    and with a defined format.  Each type of block has enough
  776.    type/length info to allow scanners to jump quickly from one block
  777.    to the next without reading each byte in the block.  */

  778. /* Trace buffer management would be simple - advance a free pointer
  779.    from beginning to end, then stop - were it not for the circular
  780.    buffer option, which is a useful way to prevent a trace run from
  781.    stopping prematurely because the buffer filled up.  In the circular
  782.    case, the location of the first trace frame (trace_buffer_start)
  783.    moves as old trace frames are discarded.  Also, since we grow trace
  784.    frames incrementally as actions are performed, we wrap around to
  785.    the beginning of the trace buffer.  This is per-block, so each
  786.    block within a trace frame remains contiguous.  Things get messy
  787.    when the wrapped-around trace frame is the one being discarded; the
  788.    free space ends up in two parts at opposite ends of the buffer.  */

  789. #ifndef ATTR_PACKED
  790. #  if defined(__GNUC__)
  791. #    define ATTR_PACKED __attribute__ ((packed))
  792. #  else
  793. #    define ATTR_PACKED /* nothing */
  794. #  endif
  795. #endif

  796. /* The data collected at a tracepoint hit.  This object should be as
  797.    small as possible, since there may be a great many of them.  We do
  798.    not need to keep a frame number, because they are all sequential
  799.    and there are no deletions; so the Nth frame in the buffer is
  800.    always frame number N.  */

  801. struct traceframe
  802. {
  803.   /* Number of the tracepoint that collected this traceframeA value
  804.      of 0 indicates the current end of the trace buffer.  We make this
  805.      a 16-bit field because it's never going to happen that GDB's
  806.      numbering of tracepoints reaches 32,000.  */
  807.   int tpnum : 16;

  808.   /* The size of the data in this trace frame.  We limit this to 32
  809.      bits, even on a 64-bit target, because it's just implausible that
  810.      one is validly going to collect 4 gigabytes of data at a single
  811.      tracepoint hit.  */
  812.   unsigned int data_size : 32;

  813.   /* The base of the trace data, which is contiguous from this point.  */
  814.   unsigned char data[0];

  815. } ATTR_PACKED;

  816. /* The size of the EOB marker, in bytesA traceframe with zeroed
  817.    fields (and no data) marks the end of trace data.  */
  818. #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)

  819. /* The traceframe to be used as the source of data to send back to
  820.    GDB.  A value of -1 means to get data from the live program.  */

  821. int current_traceframe = -1;

  822. /* This flag is true if the trace buffer is circular, meaning that
  823.    when it fills, the oldest trace frames are discarded in order to
  824.    make room.  */

  825. #ifndef IN_PROCESS_AGENT
  826. static int circular_trace_buffer;
  827. #endif

  828. /* Size of the trace buffer.  */

  829. static LONGEST trace_buffer_size;

  830. /* Pointer to the block of memory that traceframes all go into.  */

  831. static unsigned char *trace_buffer_lo;

  832. /* Pointer to the end of the trace buffer, more precisely to the byte
  833.    after the end of the buffer.  */

  834. static unsigned char *trace_buffer_hi;

  835. /* Control structure holding the read/write/etc. pointers into the
  836.    trace buffer.  We need more than one of these to implement a
  837.    transaction-like mechanism to garantees that both GDBserver and the
  838.    in-process agent can try to change the trace buffer
  839.    simultaneously.  */

  840. struct trace_buffer_control
  841. {
  842.   /* Pointer to the first trace frame in the buffer.  In the
  843.      non-circular case, this is equal to trace_buffer_lo, otherwise it
  844.      moves around in the buffer.  */
  845.   unsigned char *start;

  846.   /* Pointer to the free part of the trace buffer.  Note that we clear
  847.      several bytes at and after this pointer, so that traceframe
  848.      scans/searches terminate properly.  */
  849.   unsigned char *free;

  850.   /* Pointer to the byte after the end of the free part.  Note that
  851.      this may be smaller than trace_buffer_free in the circular case,
  852.      and means that the free part is in two pieces.  Initially it is
  853.      equal to trace_buffer_hi, then is generally equivalent to
  854.      trace_buffer_start.  */
  855.   unsigned char *end_free;

  856.   /* Pointer to the wraparound.  If not equal to trace_buffer_hi, then
  857.      this is the point at which the trace data breaks, and resumes at
  858.      trace_buffer_lo.  */
  859.   unsigned char *wrap;
  860. };

  861. /* Same as above, to be used by GDBserver when updating the in-process
  862.    agent.  */
  863. struct ipa_trace_buffer_control
  864. {
  865.   uintptr_t start;
  866.   uintptr_t free;
  867.   uintptr_t end_free;
  868.   uintptr_t wrap;
  869. };


  870. /* We have possibly both GDBserver and an inferior thread accessing
  871.    the same IPA trace buffer memory.  The IPA is the producer (tries
  872.    to put new frames in the buffer), while GDBserver occasionally
  873.    consumes them, that is, flushes the IPA's buffer into its own
  874.    buffer.  Both sides need to update the trace buffer control
  875.    pointers (current head, tail, etc.).  We can't use a global lock to
  876.    synchronize the accesses, as otherwise we could deadlock GDBserver
  877.    (if the thread holding the lock stops for a signal, say).  So
  878.    instead of that, we use a transaction scheme where GDBserver writes
  879.    always prevail over the IPAs writes, and, we have the IPA detect
  880.    the commit failure/overwrite, and retry the whole attempt.  This is
  881.    mainly implemented by having a global token object that represents
  882.    who wrote last to the buffer control structure.  We need to freeze
  883.    any inferior writing to the buffer while GDBserver touches memory,
  884.    so that the inferior can correctly detect that GDBserver had been
  885.    there, otherwise, it could mistakingly think its commit was
  886.    successful; that's implemented by simply having GDBserver set a
  887.    breakpoint the inferior hits if it is the critical region.

  888.    There are three cycling trace buffer control structure copies
  889.    (buffer head, tail, etc.), with the token object including an index
  890.    indicating which is current live copy.  The IPA tentatively builds
  891.    an updated copy in a non-current control structure, while GDBserver
  892.    always clobbers the current version directly.  The IPA then tries
  893.    to atomically "commit" its version; if GDBserver clobbered the
  894.    structure meanwhile, that will fail, and the IPA restarts the
  895.    allocation process.

  896.    Listing the step in further detail, we have:

  897.   In-process agent (producer):

  898.   - passes by `about_to_request_buffer_space' breakpoint/lock

  899.   - reads current token, extracts current trace buffer control index,
  900.     and starts tentatively updating the rightmost one (0->1, 1->2,
  901.     2->0).  Note that only one inferior thread is executing this code
  902.     at any given time, due to an outer lock in the jump pads.

  903.   - updates counters, and tries to commit the token.

  904.   - passes by second `about_to_request_buffer_space' breakpoint/lock,
  905.     leaving the sync region.

  906.   - checks if the update was effective.

  907.   - if trace buffer was found full, hits flush_trace_buffer
  908.     breakpoint, and restarts later afterwards.

  909.   GDBserver (consumer):

  910.   - sets `about_to_request_buffer_space' breakpoint/lock.

  911.   - updates the token unconditionally, using the current buffer
  912.     control index, since it knows that the IP agent always writes to
  913.     the rightmost, and due to the breakpoint, at most one IP thread
  914.     can try to update the trace buffer concurrently to GDBserver, so
  915.     there will be no danger of trace buffer control index wrap making
  916.     the IPA write to the same index as GDBserver.

  917.   - flushes the IP agent's trace buffer completely, and updates the
  918.     current trace buffer control structure.  GDBserver *always* wins.

  919.   - removes the `about_to_request_buffer_space' breakpoint.

  920. The token is stored in the `trace_buffer_ctrl_curr' variable.
  921. Internally, it's bits are defined as:

  922. |-------------+-----+-------------+--------+-------------+--------------|
  923. | Bit offsets |  31 |   30 - 20   |   19   |    18-8     |     7-0      |
  924. |-------------+-----+-------------+--------+-------------+--------------|
  925. | What        | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
  926. |-------------+-----+-------------+--------+-------------+--------------|

  927. GSB  - GDBserver Stamp Bit
  928. PC   - Previous Counter
  929. CC   - Current Counter
  930. TBCI - Trace Buffer Control Index


  931. An IPA update of `trace_buffer_ctrl_curr' does:

  932.     - read CC from the current token, save as PC.
  933.     - updates pointers
  934.     - atomically tries to write PC+1,CC

  935. A GDBserver update of `trace_buffer_ctrl_curr' does:

  936.     - reads PC and CC from the current token.
  937.     - updates pointers
  938.     - writes GSB,PC,CC
  939. */

  940. /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
  941.    for the counters described below.  The cleared bits are used to
  942.    hold the index of the items of the `trace_buffer_ctrl' array that
  943.    is "current".  */
  944. #define GDBSERVER_FLUSH_COUNT_MASK        0xfffffff0

  945. /* `trace_buffer_ctrl_curr' contains two counters.  The `previous'
  946.    counter, and the `current' counter.  */

  947. #define GDBSERVER_FLUSH_COUNT_MASK_PREV   0x7ff00000
  948. #define GDBSERVER_FLUSH_COUNT_MASK_CURR   0x0007ff00

  949. /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
  950.    always stamps this bit as set.  */
  951. #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000

  952. #ifdef IN_PROCESS_AGENT
  953. IP_AGENT_EXPORT struct trace_buffer_control trace_buffer_ctrl[3];
  954. IP_AGENT_EXPORT unsigned int trace_buffer_ctrl_curr;

  955. # define TRACE_BUFFER_CTRL_CURR \
  956.   (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)

  957. #else

  958. /* The GDBserver side agent only needs one instance of this object, as
  959.    it doesn't need to sync with itself.  Define it as array anyway so
  960.    that the rest of the code base doesn't need to care for the
  961.    difference.  */
  962. struct trace_buffer_control trace_buffer_ctrl[1];
  963. # define TRACE_BUFFER_CTRL_CURR 0
  964. #endif

  965. /* These are convenience macros used to access the current trace
  966.    buffer control in effect.  */
  967. #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
  968. #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
  969. #define trace_buffer_end_free \
  970.   (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
  971. #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)


  972. /* Macro that returns a pointer to the first traceframe in the buffer.  */

  973. #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)

  974. /* Macro that returns a pointer to the next traceframe in the buffer.
  975.    If the computed location is beyond the wraparound point, subtract
  976.    the offset of the wraparound.  */

  977. #define NEXT_TRACEFRAME_1(TF) \
  978.   (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)

  979. #define NEXT_TRACEFRAME(TF) \
  980.   ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF)  \
  981.                           - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
  982.                              ? (trace_buffer_wrap - trace_buffer_lo)        \
  983.                              : 0)))

  984. /* The difference between these counters represents the total number
  985.    of complete traceframes present in the trace buffer.  The IP agent
  986.    writes to the write count, GDBserver writes to read count.  */

  987. IP_AGENT_EXPORT unsigned int traceframe_write_count;
  988. IP_AGENT_EXPORT unsigned int traceframe_read_count;

  989. /* Convenience macro.  */

  990. #define traceframe_count \
  991.   ((unsigned int) (traceframe_write_count - traceframe_read_count))

  992. /* The count of all traceframes created in the current run, including
  993.    ones that were discarded to make room.  */

  994. IP_AGENT_EXPORT int traceframes_created;

  995. #ifndef IN_PROCESS_AGENT

  996. /* Read-only regions are address ranges whose contents don't change,
  997.    and so can be read from target memory even while looking at a trace
  998.    frame.  Without these, disassembly for instance will likely fail,
  999.    because the program code is not usually collected into a trace
  1000.    frame.  This data structure does not need to be very complicated or
  1001.    particularly efficient, it's only going to be used occasionally,
  1002.    and only by some commands.  */

  1003. struct readonly_region
  1004. {
  1005.   /* The bounds of the region.  */
  1006.   CORE_ADDR start, end;

  1007.   /* Link to the next one.  */
  1008.   struct readonly_region *next;
  1009. };

  1010. /* Linked list of readonly regions.  This list stays in effect from
  1011.    one tstart to the next.  */

  1012. static struct readonly_region *readonly_regions;

  1013. #endif

  1014. /* The global that controls tracing overall.  */

  1015. IP_AGENT_EXPORT int tracing;

  1016. #ifndef IN_PROCESS_AGENT

  1017. /* Controls whether tracing should continue after GDB disconnects.  */

  1018. int disconnected_tracing;

  1019. /* The reason for the last tracing run to have stopped.  We initialize
  1020.    to a distinct string so that GDB can distinguish between "stopped
  1021.    after running" and "stopped because never run" cases.  */

  1022. static const char *tracing_stop_reason = "tnotrun";

  1023. static int tracing_stop_tpnum;

  1024. /* 64-bit timestamps for the trace run's start and finish, expressed
  1025.    in microseconds from the Unix epoch.  */

  1026. LONGEST tracing_start_time;
  1027. LONGEST tracing_stop_time;

  1028. /* The (optional) user-supplied name of the user that started the run.
  1029.    This is an arbitrary string, and may be NULL.  */

  1030. char *tracing_user_name;

  1031. /* Optional user-supplied text describing the run.  This is
  1032.    an arbitrary string, and may be NULL.  */

  1033. char *tracing_notes;

  1034. /* Optional user-supplied text explaining a tstop command.  This is an
  1035.    arbitrary string, and may be NULL.  */

  1036. char *tracing_stop_note;

  1037. #endif

  1038. /* Functions local to this file.  */

  1039. /* Base "class" for tracepoint type specific data to be passed down to
  1040.    collect_data_at_tracepoint.  */
  1041. struct tracepoint_hit_ctx
  1042. {
  1043.   enum tracepoint_type type;
  1044. };

  1045. #ifdef IN_PROCESS_AGENT

  1046. /* Fast/jump tracepoint specific data to be passed down to
  1047.    collect_data_at_tracepoint.  */
  1048. struct fast_tracepoint_ctx
  1049. {
  1050.   struct tracepoint_hit_ctx base;

  1051.   struct regcache regcache;
  1052.   int regcache_initted;
  1053.   unsigned char *regspace;

  1054.   unsigned char *regs;
  1055.   struct tracepoint *tpoint;
  1056. };

  1057. /* Static tracepoint specific data to be passed down to
  1058.    collect_data_at_tracepoint.  */
  1059. struct static_tracepoint_ctx
  1060. {
  1061.   struct tracepoint_hit_ctx base;

  1062.   /* The regcache corresponding to the registers state at the time of
  1063.      the tracepoint hit.  Initialized lazily, from REGS.  */
  1064.   struct regcache regcache;
  1065.   int regcache_initted;

  1066.   /* The buffer space REGCACHE above uses.  We use a separate buffer
  1067.      instead of letting the regcache malloc for both signal safety and
  1068.      performance reasons; this is allocated on the stack instead.  */
  1069.   unsigned char *regspace;

  1070.   /* The register buffer as passed on by lttng/ust.  */
  1071.   struct registers *regs;

  1072.   /* The "printf" formatter and the args the user passed to the marker
  1073.      call.  We use this to be able to collect "static trace data"
  1074.      ($_sdata).  */
  1075.   const char *fmt;
  1076.   va_list *args;

  1077.   /* The GDB tracepoint matching the probed marker that was "hit".  */
  1078.   struct tracepoint *tpoint;
  1079. };

  1080. #else

  1081. /* Static tracepoint specific data to be passed down to
  1082.    collect_data_at_tracepoint.  */
  1083. struct trap_tracepoint_ctx
  1084. {
  1085.   struct tracepoint_hit_ctx base;

  1086.   struct regcache *regcache;
  1087. };

  1088. #endif

  1089. #ifndef IN_PROCESS_AGENT
  1090. static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
  1091. static int traceframe_read_tsv (int num, LONGEST *val);
  1092. #endif

  1093. static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  1094.                                          struct tracepoint *tpoint);

  1095. #ifndef IN_PROCESS_AGENT
  1096. static void clear_readonly_regions (void);
  1097. static void clear_installed_tracepoints (void);
  1098. #endif

  1099. static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  1100.                                         CORE_ADDR stop_pc,
  1101.                                         struct tracepoint *tpoint);
  1102. #ifndef IN_PROCESS_AGENT
  1103. static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
  1104.                                   CORE_ADDR stop_pc,
  1105.                                   struct tracepoint *tpoint, int current_step);
  1106. static void compile_tracepoint_condition (struct tracepoint *tpoint,
  1107.                                           CORE_ADDR *jump_entry);
  1108. #endif
  1109. static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  1110.                                      CORE_ADDR stop_pc,
  1111.                                      struct tracepoint *tpoint,
  1112.                                      struct traceframe *tframe,
  1113.                                      struct tracepoint_action *taction);

  1114. #ifndef IN_PROCESS_AGENT
  1115. static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);

  1116. static void install_tracepoint (struct tracepoint *, char *own_buf);
  1117. static void download_tracepoint (struct tracepoint *);
  1118. static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
  1119. static void clone_fast_tracepoint (struct tracepoint *to,
  1120.                                    const struct tracepoint *from);
  1121. #endif

  1122. static LONGEST get_timestamp (void);

  1123. #if defined(__GNUC__)
  1124. #  define memory_barrier() asm volatile ("" : : : "memory")
  1125. #else
  1126. #  define memory_barrier() do {} while (0)
  1127. #endif

  1128. /* We only build the IPA if this builtin is supported, and there are
  1129.    no uses of this in GDBserver itself, so we're safe in defining this
  1130.    unconditionally.  */
  1131. #define cmpxchg(mem, oldval, newval) \
  1132.   __sync_val_compare_and_swap (mem, oldval, newval)

  1133. /* Record that an error occurred during expression evaluation.  */

  1134. static void
  1135. record_tracepoint_error (struct tracepoint *tpoint, const char *which,
  1136.                          enum eval_result_type rtype)
  1137. {
  1138.   trace_debug ("Tracepoint %d at %s %s eval reports error %d",
  1139.                tpoint->number, paddress (tpoint->address), which, rtype);

  1140. #ifdef IN_PROCESS_AGENT
  1141.   /* Only record the first error we get.  */
  1142.   if (cmpxchg (&expr_eval_result,
  1143.                expr_eval_no_error,
  1144.                rtype) != expr_eval_no_error)
  1145.     return;
  1146. #else
  1147.   if (expr_eval_result != expr_eval_no_error)
  1148.     return;
  1149. #endif

  1150.   error_tracepoint = tpoint;
  1151. }

  1152. /* Trace buffer management.  */

  1153. static void
  1154. clear_trace_buffer (void)
  1155. {
  1156.   trace_buffer_start = trace_buffer_lo;
  1157.   trace_buffer_free = trace_buffer_lo;
  1158.   trace_buffer_end_free = trace_buffer_hi;
  1159.   trace_buffer_wrap = trace_buffer_hi;
  1160.   /* A traceframe with zeroed fields marks the end of trace data.  */
  1161.   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
  1162.   ((struct traceframe *) trace_buffer_free)->data_size = 0;
  1163.   traceframe_read_count = traceframe_write_count = 0;
  1164.   traceframes_created = 0;
  1165. }

  1166. #ifndef IN_PROCESS_AGENT

  1167. static void
  1168. clear_inferior_trace_buffer (void)
  1169. {
  1170.   CORE_ADDR ipa_trace_buffer_lo;
  1171.   CORE_ADDR ipa_trace_buffer_hi;
  1172.   struct traceframe ipa_traceframe = { 0 };
  1173.   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;

  1174.   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
  1175.                               &ipa_trace_buffer_lo);
  1176.   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
  1177.                               &ipa_trace_buffer_hi);

  1178.   ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
  1179.   ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
  1180.   ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
  1181.   ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;

  1182.   /* A traceframe with zeroed fields marks the end of trace data.  */
  1183.   write_inferior_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
  1184.                          (unsigned char *) &ipa_trace_buffer_ctrl,
  1185.                          sizeof (ipa_trace_buffer_ctrl));

  1186.   write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);

  1187.   /* A traceframe with zeroed fields marks the end of trace data.  */
  1188.   write_inferior_memory (ipa_trace_buffer_lo,
  1189.                          (unsigned char *) &ipa_traceframe,
  1190.                          sizeof (ipa_traceframe));

  1191.   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
  1192.   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
  1193.   write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
  1194. }

  1195. #endif

  1196. static void
  1197. init_trace_buffer (LONGEST bufsize)
  1198. {
  1199.   size_t alloc_size;

  1200.   trace_buffer_size = bufsize;

  1201.   /* Make sure to internally allocate at least space for the EOB
  1202.      marker.  */
  1203.   alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
  1204.                 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
  1205.   trace_buffer_lo = xrealloc (trace_buffer_lo, alloc_size);

  1206.   trace_buffer_hi = trace_buffer_lo + trace_buffer_size;

  1207.   clear_trace_buffer ();
  1208. }

  1209. #ifdef IN_PROCESS_AGENT

  1210. IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
  1211. about_to_request_buffer_space (void)
  1212. {
  1213.   /* GDBserver places breakpoint here while it goes about to flush
  1214.      data at random times.  */
  1215.   UNKNOWN_SIDE_EFFECTS();
  1216. }

  1217. #endif

  1218. /* Carve out a piece of the trace buffer, returning NULL in case of
  1219.    failure.  */

  1220. static void *
  1221. trace_buffer_alloc (size_t amt)
  1222. {
  1223.   unsigned char *rslt;
  1224.   struct trace_buffer_control *tbctrl;
  1225.   unsigned int curr;
  1226. #ifdef IN_PROCESS_AGENT
  1227.   unsigned int prev, prev_filtered;
  1228.   unsigned int commit_count;
  1229.   unsigned int commit;
  1230.   unsigned int readout;
  1231. #else
  1232.   struct traceframe *oldest;
  1233.   unsigned char *new_start;
  1234. #endif

  1235.   trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
  1236.                (long) amt, (long) sizeof (struct traceframe));

  1237.   /* Account for the EOB marker.  */
  1238.   amt += TRACEFRAME_EOB_MARKER_SIZE;

  1239. #ifdef IN_PROCESS_AGENT
  1240. again:
  1241.   memory_barrier ();

  1242.   /* Read the current token and extract the index to try to write to,
  1243.      storing it in CURR.  */
  1244.   prev = trace_buffer_ctrl_curr;
  1245.   prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
  1246.   curr = prev_filtered + 1;
  1247.   if (curr > 2)
  1248.     curr = 0;

  1249.   about_to_request_buffer_space ();

  1250.   /* Start out with a copy of the current state.  GDBserver may be
  1251.      midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
  1252.      be able to commit anyway if that happens.  */
  1253.   trace_buffer_ctrl[curr]
  1254.     = trace_buffer_ctrl[prev_filtered];
  1255.   trace_debug ("trying curr=%u", curr);
  1256. #else
  1257.   /* The GDBserver's agent doesn't need all that syncing, and always
  1258.      updates TCB 0 (there's only one, mind you).  */
  1259.   curr = 0;
  1260. #endif
  1261.   tbctrl = &trace_buffer_ctrl[curr];

  1262.   /* Offsets are easier to grok for debugging than raw addresses,
  1263.      especially for the small trace buffer sizes that are useful for
  1264.      testing.  */
  1265.   trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
  1266.                curr,
  1267.                (int) (tbctrl->start - trace_buffer_lo),
  1268.                (int) (tbctrl->free - trace_buffer_lo),
  1269.                (int) (tbctrl->end_free - trace_buffer_lo),
  1270.                (int) (tbctrl->wrap - trace_buffer_lo),
  1271.                (int) (trace_buffer_hi - trace_buffer_lo));

  1272.   /* The algorithm here is to keep trying to get a contiguous block of
  1273.      the requested size, possibly discarding older traceframes to free
  1274.      up space.  Since free space might come in one or two pieces,
  1275.      depending on whether discarded traceframes wrapped around at the
  1276.      high end of the buffer, we test both pieces after each
  1277.      discard.  */
  1278.   while (1)
  1279.     {
  1280.       /* First, if we have two free parts, try the upper one first.  */
  1281.       if (tbctrl->end_free < tbctrl->free)
  1282.         {
  1283.           if (tbctrl->free + amt <= trace_buffer_hi)
  1284.             /* We have enough in the upper part.  */
  1285.             break;
  1286.           else
  1287.             {
  1288.               /* Our high part of free space wasn't enough.  Give up
  1289.                  on it for now, set wraparound.  We will recover the
  1290.                  space later, if/when the wrapped-around traceframe is
  1291.                  discarded.  */
  1292.               trace_debug ("Upper part too small, setting wraparound");
  1293.               tbctrl->wrap = tbctrl->free;
  1294.               tbctrl->free = trace_buffer_lo;
  1295.             }
  1296.         }

  1297.       /* The normal case.  */
  1298.       if (tbctrl->free + amt <= tbctrl->end_free)
  1299.         break;

  1300. #ifdef IN_PROCESS_AGENT
  1301.       /* The IP Agent's buffer is always circular.  It isn't used
  1302.          currently, but `circular_trace_buffer' could represent
  1303.          GDBserver's mode.  If we didn't find space, ask GDBserver to
  1304.          flush.  */

  1305.       flush_trace_buffer ();
  1306.       memory_barrier ();
  1307.       if (tracing)
  1308.         {
  1309.           trace_debug ("gdbserver flushed buffer, retrying");
  1310.           goto again;
  1311.         }

  1312.       /* GDBserver cancelled the tracing.  Bail out as well.  */
  1313.       return NULL;
  1314. #else
  1315.       /* If we're here, then neither part is big enough, and
  1316.          non-circular trace buffers are now full.  */
  1317.       if (!circular_trace_buffer)
  1318.         {
  1319.           trace_debug ("Not enough space in the trace buffer");
  1320.           return NULL;
  1321.         }

  1322.       trace_debug ("Need more space in the trace buffer");

  1323.       /* If we have a circular buffer, we can try discarding the
  1324.          oldest traceframe and see if that helps.  */
  1325.       oldest = FIRST_TRACEFRAME ();
  1326.       if (oldest->tpnum == 0)
  1327.         {
  1328.           /* Not good; we have no traceframes to free.  Perhaps we're
  1329.              asking for a block that is larger than the buffer?  In
  1330.              any case, give up.  */
  1331.           trace_debug ("No traceframes to discard");
  1332.           return NULL;
  1333.         }

  1334.       /* We don't run this code in the in-process agent currently.
  1335.          E.g., we could leave the in-process agent in autonomous
  1336.          circular mode if we only have fast tracepoints.  If we do
  1337.          that, then this bit becomes racy with GDBserver, which also
  1338.          writes to this counter.  */
  1339.       --traceframe_write_count;

  1340.       new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
  1341.       /* If we freed the traceframe that wrapped around, go back
  1342.          to the non-wrap case.  */
  1343.       if (new_start < tbctrl->start)
  1344.         {
  1345.           trace_debug ("Discarding past the wraparound");
  1346.           tbctrl->wrap = trace_buffer_hi;
  1347.         }
  1348.       tbctrl->start = new_start;
  1349.       tbctrl->end_free = tbctrl->start;

  1350.       trace_debug ("Discarded a traceframe\n"
  1351.                    "Trace buffer [%d], start=%d free=%d "
  1352.                    "endfree=%d wrap=%d hi=%d",
  1353.                    curr,
  1354.                    (int) (tbctrl->start - trace_buffer_lo),
  1355.                    (int) (tbctrl->free - trace_buffer_lo),
  1356.                    (int) (tbctrl->end_free - trace_buffer_lo),
  1357.                    (int) (tbctrl->wrap - trace_buffer_lo),
  1358.                    (int) (trace_buffer_hi - trace_buffer_lo));

  1359.       /* Now go back around the loop.  The discard might have resulted
  1360.          in either one or two pieces of free space, so we want to try
  1361.          both before freeing any more traceframes.  */
  1362. #endif
  1363.     }

  1364.   /* If we get here, we know we can provide the asked-for space.  */

  1365.   rslt = tbctrl->free;

  1366.   /* Adjust the request back down, now that we know we have space for
  1367.      the marker, but don't commit to AMT yet, we may still need to
  1368.      restart the operation if GDBserver touches the trace buffer
  1369.      (obviously only important in the in-process agent's version).  */
  1370.   tbctrl->free += (amt - sizeof (struct traceframe));

  1371.   /* Or not.  If GDBserver changed the trace buffer behind our back,
  1372.      we get to restart a new allocation attempt.  */

  1373. #ifdef IN_PROCESS_AGENT
  1374.   /* Build the tentative token.  */
  1375.   commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
  1376.                   & GDBSERVER_FLUSH_COUNT_MASK_CURR);
  1377.   commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
  1378.             | commit_count
  1379.             | curr);

  1380.   /* Try to commit it.  */
  1381.   readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
  1382.   if (readout != prev)
  1383.     {
  1384.       trace_debug ("GDBserver has touched the trace buffer, restarting."
  1385.                    " (prev=%08x, commit=%08x, readout=%08x)",
  1386.                    prev, commit, readout);
  1387.       goto again;
  1388.     }

  1389.   /* Hold your horses here.  Even if that change was committed,
  1390.      GDBserver could come in, and clobber it.  We need to hold to be
  1391.      able to tell if GDBserver clobbers before or after we committed
  1392.      the change.  Whenever GDBserver goes about touching the IPA
  1393.      buffer, it sets a breakpoint in this routine, so we have a sync
  1394.      point here.  */
  1395.   about_to_request_buffer_space ();

  1396.   /* Check if the change has been effective, even if GDBserver stopped
  1397.      us at the breakpoint.  */

  1398.   {
  1399.     unsigned int refetch;

  1400.     memory_barrier ();

  1401.     refetch = trace_buffer_ctrl_curr;

  1402.     if (refetch == commit
  1403.         || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
  1404.       {
  1405.         /* effective */
  1406.         trace_debug ("change is effective: (prev=%08x, commit=%08x, "
  1407.                      "readout=%08x, refetch=%08x)",
  1408.                      prev, commit, readout, refetch);
  1409.       }
  1410.     else
  1411.       {
  1412.         trace_debug ("GDBserver has touched the trace buffer, not effective."
  1413.                      " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
  1414.                      prev, commit, readout, refetch);
  1415.         goto again;
  1416.       }
  1417.   }
  1418. #endif

  1419.   /* We have a new piece of the trace buffer.  Hurray!  */

  1420.   /* Add an EOB marker just past this allocation.  */
  1421.   ((struct traceframe *) tbctrl->free)->tpnum = 0;
  1422.   ((struct traceframe *) tbctrl->free)->data_size = 0;

  1423.   /* Adjust the request back down, now that we know we have space for
  1424.      the marker.  */
  1425.   amt -= sizeof (struct traceframe);

  1426.   if (debug_threads)
  1427.     {
  1428.       trace_debug ("Allocated %d bytes", (int) amt);
  1429.       trace_debug ("Trace buffer [%d] start=%d free=%d "
  1430.                    "endfree=%d wrap=%d hi=%d",
  1431.                    curr,
  1432.                    (int) (tbctrl->start - trace_buffer_lo),
  1433.                    (int) (tbctrl->free - trace_buffer_lo),
  1434.                    (int) (tbctrl->end_free - trace_buffer_lo),
  1435.                    (int) (tbctrl->wrap - trace_buffer_lo),
  1436.                    (int) (trace_buffer_hi - trace_buffer_lo));
  1437.     }

  1438.   return rslt;
  1439. }

  1440. #ifndef IN_PROCESS_AGENT

  1441. /* Return the total free space.  This is not necessarily the largest
  1442.    block we can allocate, because of the two-part case.  */

  1443. static int
  1444. free_space (void)
  1445. {
  1446.   if (trace_buffer_free <= trace_buffer_end_free)
  1447.     return trace_buffer_end_free - trace_buffer_free;
  1448.   else
  1449.     return ((trace_buffer_end_free - trace_buffer_lo)
  1450.             + (trace_buffer_hi - trace_buffer_free));
  1451. }

  1452. /* An 'S' in continuation packets indicates remainder are for
  1453.    while-stepping.  */

  1454. static int seen_step_action_flag;

  1455. /* Create a tracepoint (location) with given number and address.  Add this
  1456.    new tracepoint to list and sort this list.  */

  1457. static struct tracepoint *
  1458. add_tracepoint (int num, CORE_ADDR addr)
  1459. {
  1460.   struct tracepoint *tpoint, **tp_next;

  1461.   tpoint = xmalloc (sizeof (struct tracepoint));
  1462.   tpoint->number = num;
  1463.   tpoint->address = addr;
  1464.   tpoint->numactions = 0;
  1465.   tpoint->actions = NULL;
  1466.   tpoint->actions_str = NULL;
  1467.   tpoint->cond = NULL;
  1468.   tpoint->num_step_actions = 0;
  1469.   tpoint->step_actions = NULL;
  1470.   tpoint->step_actions_str = NULL;
  1471.   /* Start all off as regular (slow) tracepoints.  */
  1472.   tpoint->type = trap_tracepoint;
  1473.   tpoint->orig_size = -1;
  1474.   tpoint->source_strings = NULL;
  1475.   tpoint->compiled_cond = 0;
  1476.   tpoint->handle = NULL;
  1477.   tpoint->next = NULL;

  1478.   /* Find a place to insert this tracepoint into list in order to keep
  1479.      the tracepoint list still in the ascending order.  There may be
  1480.      multiple tracepoints at the same address as TPOINT's, and this
  1481.      guarantees TPOINT is inserted after all the tracepoints which are
  1482.      set at the same address.  For example, fast tracepoints A, B, C are
  1483.      set at the same address, and D is to be insert at the same place as
  1484.      well,

  1485.      -->| A |--> | B |-->| C |->...

  1486.      One jump pad was created for tracepoint A, B, and C, and the target
  1487.      address of A is referenced/used in jump pad.  So jump pad will let
  1488.      inferior jump to A.  If D is inserted in front of A, like this,

  1489.      -->| D |-->| A |--> | B |-->| C |->...

  1490.      without updating jump pad, D is not reachable during collect, which
  1491.      is wrong.  As we can see, the order of B, C and D doesn't matter, but
  1492.      A should always be the `first' one.  */
  1493.   for (tp_next = &tracepoints;
  1494.        (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
  1495.        tp_next = &(*tp_next)->next)
  1496.     ;
  1497.   tpoint->next = *tp_next;
  1498.   *tp_next = tpoint;
  1499.   last_tracepoint = tpoint;

  1500.   seen_step_action_flag = 0;

  1501.   return tpoint;
  1502. }

  1503. #ifndef IN_PROCESS_AGENT

  1504. /* Return the tracepoint with the given number and address, or NULL.  */

  1505. static struct tracepoint *
  1506. find_tracepoint (int id, CORE_ADDR addr)
  1507. {
  1508.   struct tracepoint *tpoint;

  1509.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  1510.     if (tpoint->number == id && tpoint->address == addr)
  1511.       return tpoint;

  1512.   return NULL;
  1513. }

  1514. /* Remove TPOINT from global list.  */

  1515. static void
  1516. remove_tracepoint (struct tracepoint *tpoint)
  1517. {
  1518.   struct tracepoint *tp, *tp_prev;

  1519.   for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
  1520.        tp_prev = tp, tp = tp->next)
  1521.     ;

  1522.   if (tp)
  1523.     {
  1524.       if (tp_prev)
  1525.         tp_prev->next = tp->next;
  1526.       else
  1527.         tracepoints = tp->next;

  1528.       xfree (tp);
  1529.     }
  1530. }

  1531. /* There may be several tracepoints with the same number (because they
  1532.    are "locations", in GDB parlance); return the next one after the
  1533.    given tracepoint, or search from the beginning of the list if the
  1534.    first argument is NULL.  */

  1535. static struct tracepoint *
  1536. find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
  1537. {
  1538.   struct tracepoint *tpoint;

  1539.   if (prev_tp)
  1540.     tpoint = prev_tp->next;
  1541.   else
  1542.     tpoint = tracepoints;
  1543.   for (; tpoint; tpoint = tpoint->next)
  1544.     if (tpoint->number == num)
  1545.       return tpoint;

  1546.   return NULL;
  1547. }

  1548. #endif

  1549. /* Append another action to perform when the tracepoint triggers.  */

  1550. static void
  1551. add_tracepoint_action (struct tracepoint *tpoint, char *packet)
  1552. {
  1553.   char *act;

  1554.   if (*packet == 'S')
  1555.     {
  1556.       seen_step_action_flag = 1;
  1557.       ++packet;
  1558.     }

  1559.   act = packet;

  1560.   while (*act)
  1561.     {
  1562.       char *act_start = act;
  1563.       struct tracepoint_action *action = NULL;

  1564.       switch (*act)
  1565.         {
  1566.         case 'M':
  1567.           {
  1568.             struct collect_memory_action *maction;
  1569.             ULONGEST basereg;
  1570.             int is_neg;

  1571.             maction = xmalloc (sizeof *maction);
  1572.             maction->base.type = *act;
  1573.             maction->base.ops = &m_tracepoint_action_ops;
  1574.             action = &maction->base;

  1575.             ++act;
  1576.             is_neg = (*act == '-');
  1577.             if (*act == '-')
  1578.               ++act;
  1579.             act = unpack_varlen_hex (act, &basereg);
  1580.             ++act;
  1581.             act = unpack_varlen_hex (act, &maction->addr);
  1582.             ++act;
  1583.             act = unpack_varlen_hex (act, &maction->len);
  1584.             maction->basereg = (is_neg
  1585.                                 ? - (int) basereg
  1586.                                 : (int) basereg);
  1587.             trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
  1588.                          pulongest (maction->len),
  1589.                          paddress (maction->addr), maction->basereg);
  1590.             break;
  1591.           }
  1592.         case 'R':
  1593.           {
  1594.             struct collect_registers_action *raction;

  1595.             raction = xmalloc (sizeof *raction);
  1596.             raction->base.type = *act;
  1597.             raction->base.ops = &r_tracepoint_action_ops;
  1598.             action = &raction->base;

  1599.             trace_debug ("Want to collect registers");
  1600.             ++act;
  1601.             /* skip past hex digits of mask for now */
  1602.             while (isxdigit(*act))
  1603.               ++act;
  1604.             break;
  1605.           }
  1606.         case 'L':
  1607.           {
  1608.             struct collect_static_trace_data_action *raction;

  1609.             raction = xmalloc (sizeof *raction);
  1610.             raction->base.type = *act;
  1611.             raction->base.ops = &l_tracepoint_action_ops;
  1612.             action = &raction->base;

  1613.             trace_debug ("Want to collect static trace data");
  1614.             ++act;
  1615.             break;
  1616.           }
  1617.         case 'S':
  1618.           trace_debug ("Unexpected step action, ignoring");
  1619.           ++act;
  1620.           break;
  1621.         case 'X':
  1622.           {
  1623.             struct eval_expr_action *xaction;

  1624.             xaction = xmalloc (sizeof (*xaction));
  1625.             xaction->base.type = *act;
  1626.             xaction->base.ops = &x_tracepoint_action_ops;
  1627.             action = &xaction->base;

  1628.             trace_debug ("Want to evaluate expression");
  1629.             xaction->expr = gdb_parse_agent_expr (&act);
  1630.             break;
  1631.           }
  1632.         default:
  1633.           trace_debug ("unknown trace action '%c', ignoring...", *act);
  1634.           break;
  1635.         case '-':
  1636.           break;
  1637.         }

  1638.       if (action == NULL)
  1639.         break;

  1640.       if (seen_step_action_flag)
  1641.         {
  1642.           tpoint->num_step_actions++;

  1643.           tpoint->step_actions
  1644.             = xrealloc (tpoint->step_actions,
  1645.                         (sizeof (*tpoint->step_actions)
  1646.                          * tpoint->num_step_actions));
  1647.           tpoint->step_actions_str
  1648.             = xrealloc (tpoint->step_actions_str,
  1649.                         (sizeof (*tpoint->step_actions_str)
  1650.                          * tpoint->num_step_actions));
  1651.           tpoint->step_actions[tpoint->num_step_actions - 1] = action;
  1652.           tpoint->step_actions_str[tpoint->num_step_actions - 1]
  1653.             = savestring (act_start, act - act_start);
  1654.         }
  1655.       else
  1656.         {
  1657.           tpoint->numactions++;
  1658.           tpoint->actions
  1659.             = xrealloc (tpoint->actions,
  1660.                         sizeof (*tpoint->actions) * tpoint->numactions);
  1661.           tpoint->actions_str
  1662.             = xrealloc (tpoint->actions_str,
  1663.                         sizeof (*tpoint->actions_str) * tpoint->numactions);
  1664.           tpoint->actions[tpoint->numactions - 1] = action;
  1665.           tpoint->actions_str[tpoint->numactions - 1]
  1666.             = savestring (act_start, act - act_start);
  1667.         }
  1668.     }
  1669. }

  1670. #endif

  1671. /* Find or create a trace state variable with the given number.  */

  1672. static struct trace_state_variable *
  1673. get_trace_state_variable (int num)
  1674. {
  1675.   struct trace_state_variable *tsv;

  1676. #ifdef IN_PROCESS_AGENT
  1677.   /* Search for an existing variable.  */
  1678.   for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
  1679.     if (tsv->number == num)
  1680.       return tsv;
  1681. #endif

  1682.   /* Search for an existing variable.  */
  1683.   for (tsv = trace_state_variables; tsv; tsv = tsv->next)
  1684.     if (tsv->number == num)
  1685.       return tsv;

  1686.   return NULL;
  1687. }

  1688. /* Find or create a trace state variable with the given number.  */

  1689. static struct trace_state_variable *
  1690. create_trace_state_variable (int num, int gdb)
  1691. {
  1692.   struct trace_state_variable *tsv;

  1693.   tsv = get_trace_state_variable (num);
  1694.   if (tsv != NULL)
  1695.     return tsv;

  1696.   /* Create a new variable.  */
  1697.   tsv = xmalloc (sizeof (struct trace_state_variable));
  1698.   tsv->number = num;
  1699.   tsv->initial_value = 0;
  1700.   tsv->value = 0;
  1701.   tsv->getter = NULL;
  1702.   tsv->name = NULL;
  1703. #ifdef IN_PROCESS_AGENT
  1704.   if (!gdb)
  1705.     {
  1706.       tsv->next = alloced_trace_state_variables;
  1707.       alloced_trace_state_variables = tsv;
  1708.     }
  1709.   else
  1710. #endif
  1711.     {
  1712.       tsv->next = trace_state_variables;
  1713.       trace_state_variables = tsv;
  1714.     }
  1715.   return tsv;
  1716. }

  1717. IP_AGENT_EXPORT LONGEST
  1718. get_trace_state_variable_value (int num)
  1719. {
  1720.   struct trace_state_variable *tsv;

  1721.   tsv = get_trace_state_variable (num);

  1722.   if (!tsv)
  1723.     {
  1724.       trace_debug ("No trace state variable %d, skipping value get", num);
  1725.       return 0;
  1726.     }

  1727.   /* Call a getter function if we have one.  While it's tempting to
  1728.      set up something to only call the getter once per tracepoint hit,
  1729.      it could run afoul of thread races. Better to let the getter
  1730.      handle it directly, if necessary to worry about it.  */
  1731.   if (tsv->getter)
  1732.     tsv->value = (tsv->getter) ();

  1733.   trace_debug ("get_trace_state_variable_value(%d) ==> %s",
  1734.                num, plongest (tsv->value));

  1735.   return tsv->value;
  1736. }

  1737. IP_AGENT_EXPORT void
  1738. set_trace_state_variable_value (int num, LONGEST val)
  1739. {
  1740.   struct trace_state_variable *tsv;

  1741.   tsv = get_trace_state_variable (num);

  1742.   if (!tsv)
  1743.     {
  1744.       trace_debug ("No trace state variable %d, skipping value set", num);
  1745.       return;
  1746.     }

  1747.   tsv->value = val;
  1748. }

  1749. LONGEST
  1750. agent_get_trace_state_variable_value (int num)
  1751. {
  1752.   return get_trace_state_variable_value (num);
  1753. }

  1754. void
  1755. agent_set_trace_state_variable_value (int num, LONGEST val)
  1756. {
  1757.   set_trace_state_variable_value (num, val);
  1758. }

  1759. static void
  1760. set_trace_state_variable_name (int num, const char *name)
  1761. {
  1762.   struct trace_state_variable *tsv;

  1763.   tsv = get_trace_state_variable (num);

  1764.   if (!tsv)
  1765.     {
  1766.       trace_debug ("No trace state variable %d, skipping name set", num);
  1767.       return;
  1768.     }

  1769.   tsv->name = (char *) name;
  1770. }

  1771. static void
  1772. set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
  1773. {
  1774.   struct trace_state_variable *tsv;

  1775.   tsv = get_trace_state_variable (num);

  1776.   if (!tsv)
  1777.     {
  1778.       trace_debug ("No trace state variable %d, skipping getter set", num);
  1779.       return;
  1780.     }

  1781.   tsv->getter = getter;
  1782. }

  1783. /* Add a raw traceframe for the given tracepoint.  */

  1784. static struct traceframe *
  1785. add_traceframe (struct tracepoint *tpoint)
  1786. {
  1787.   struct traceframe *tframe;

  1788.   tframe = trace_buffer_alloc (sizeof (struct traceframe));

  1789.   if (tframe == NULL)
  1790.     return NULL;

  1791.   tframe->tpnum = tpoint->number;
  1792.   tframe->data_size = 0;

  1793.   return tframe;
  1794. }

  1795. /* Add a block to the traceframe currently being worked on.  */

  1796. static unsigned char *
  1797. add_traceframe_block (struct traceframe *tframe,
  1798.                       struct tracepoint *tpoint, int amt)
  1799. {
  1800.   unsigned char *block;

  1801.   if (!tframe)
  1802.     return NULL;

  1803.   block = trace_buffer_alloc (amt);

  1804.   if (!block)
  1805.     return NULL;

  1806.   gdb_assert (tframe->tpnum == tpoint->number);

  1807.   tframe->data_size += amt;
  1808.   tpoint->traceframe_usage += amt;

  1809.   return block;
  1810. }

  1811. /* Flag that the current traceframe is finished.  */

  1812. static void
  1813. finish_traceframe (struct traceframe *tframe)
  1814. {
  1815.   ++traceframe_write_count;
  1816.   ++traceframes_created;
  1817. }

  1818. #ifndef IN_PROCESS_AGENT

  1819. /* Given a traceframe number NUM, find the NUMth traceframe in the
  1820.    buffer.  */

  1821. static struct traceframe *
  1822. find_traceframe (int num)
  1823. {
  1824.   struct traceframe *tframe;
  1825.   int tfnum = 0;

  1826.   for (tframe = FIRST_TRACEFRAME ();
  1827.        tframe->tpnum != 0;
  1828.        tframe = NEXT_TRACEFRAME (tframe))
  1829.     {
  1830.       if (tfnum == num)
  1831.         return tframe;
  1832.       ++tfnum;
  1833.     }

  1834.   return NULL;
  1835. }

  1836. static CORE_ADDR
  1837. get_traceframe_address (struct traceframe *tframe)
  1838. {
  1839.   CORE_ADDR addr;
  1840.   struct tracepoint *tpoint;

  1841.   addr = traceframe_get_pc (tframe);

  1842.   if (addr)
  1843.     return addr;

  1844.   /* Fallback strategy, will be incorrect for while-stepping frames
  1845.      and multi-location tracepoints.  */
  1846.   tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
  1847.   return tpoint->address;
  1848. }

  1849. /* Search for the next traceframe whose address is inside or outside
  1850.    the given range.  */

  1851. static struct traceframe *
  1852. find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
  1853.                                int *tfnump)
  1854. {
  1855.   struct traceframe *tframe;
  1856.   CORE_ADDR tfaddr;

  1857.   *tfnump = current_traceframe + 1;
  1858.   tframe = find_traceframe (*tfnump);
  1859.   /* The search is not supposed to wrap around.  */
  1860.   if (!tframe)
  1861.     {
  1862.       *tfnump = -1;
  1863.       return NULL;
  1864.     }

  1865.   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
  1866.     {
  1867.       tfaddr = get_traceframe_address (tframe);
  1868.       if (inside_p
  1869.           ? (lo <= tfaddr && tfaddr <= hi)
  1870.           : (lo > tfaddr || tfaddr > hi))
  1871.         return tframe;
  1872.       ++*tfnump;
  1873.     }

  1874.   *tfnump = -1;
  1875.   return NULL;
  1876. }

  1877. /* Search for the next traceframe recorded by the given tracepoint.
  1878.    Note that for multi-location tracepoints, this will find whatever
  1879.    location appears first.  */

  1880. static struct traceframe *
  1881. find_next_traceframe_by_tracepoint (int num, int *tfnump)
  1882. {
  1883.   struct traceframe *tframe;

  1884.   *tfnump = current_traceframe + 1;
  1885.   tframe = find_traceframe (*tfnump);
  1886.   /* The search is not supposed to wrap around.  */
  1887.   if (!tframe)
  1888.     {
  1889.       *tfnump = -1;
  1890.       return NULL;
  1891.     }

  1892.   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
  1893.     {
  1894.       if (tframe->tpnum == num)
  1895.         return tframe;
  1896.       ++*tfnump;
  1897.     }

  1898.   *tfnump = -1;
  1899.   return NULL;
  1900. }

  1901. #endif

  1902. #ifndef IN_PROCESS_AGENT

  1903. /* Clear all past trace state.  */

  1904. static void
  1905. cmd_qtinit (char *packet)
  1906. {
  1907.   struct trace_state_variable *tsv, *prev, *next;

  1908.   /* Make sure we don't try to read from a trace frame.  */
  1909.   current_traceframe = -1;

  1910.   stop_tracing ();

  1911.   trace_debug ("Initializing the trace");

  1912.   clear_installed_tracepoints ();
  1913.   clear_readonly_regions ();

  1914.   tracepoints = NULL;
  1915.   last_tracepoint = NULL;

  1916.   /* Clear out any leftover trace state variables.  Ones with target
  1917.      defined getters should be kept however.  */
  1918.   prev = NULL;
  1919.   tsv = trace_state_variables;
  1920.   while (tsv)
  1921.     {
  1922.       trace_debug ("Looking at var %d", tsv->number);
  1923.       if (tsv->getter == NULL)
  1924.         {
  1925.           next = tsv->next;
  1926.           if (prev)
  1927.             prev->next = next;
  1928.           else
  1929.             trace_state_variables = next;
  1930.           trace_debug ("Deleting var %d", tsv->number);
  1931.           free (tsv);
  1932.           tsv = next;
  1933.         }
  1934.       else
  1935.         {
  1936.           prev = tsv;
  1937.           tsv = tsv->next;
  1938.         }
  1939.     }

  1940.   clear_trace_buffer ();
  1941.   clear_inferior_trace_buffer ();

  1942.   write_ok (packet);
  1943. }

  1944. /* Unprobe the UST marker at ADDRESS.  */

  1945. static void
  1946. unprobe_marker_at (CORE_ADDR address)
  1947. {
  1948.   char cmd[IPA_CMD_BUF_SIZE];

  1949.   sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
  1950.   run_inferior_command (cmd, strlen (cmd) + 1);
  1951. }

  1952. /* Restore the program to its pre-tracing state.  This routine may be called
  1953.    in error situations, so it needs to be careful about only restoring
  1954.    from known-valid bits.  */

  1955. static void
  1956. clear_installed_tracepoints (void)
  1957. {
  1958.   struct tracepoint *tpoint;
  1959.   struct tracepoint *prev_stpoint;

  1960.   pause_all (1);

  1961.   prev_stpoint = NULL;

  1962.   /* Restore any bytes overwritten by tracepoints.  */
  1963.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  1964.     {
  1965.       /* Catch the case where we might try to remove a tracepoint that
  1966.          was never actually installed.  */
  1967.       if (tpoint->handle == NULL)
  1968.         {
  1969.           trace_debug ("Tracepoint %d at 0x%s was "
  1970.                        "never installed, nothing to clear",
  1971.                        tpoint->number, paddress (tpoint->address));
  1972.           continue;
  1973.         }

  1974.       switch (tpoint->type)
  1975.         {
  1976.         case trap_tracepoint:
  1977.           delete_breakpoint (tpoint->handle);
  1978.           break;
  1979.         case fast_tracepoint:
  1980.           delete_fast_tracepoint_jump (tpoint->handle);
  1981.           break;
  1982.         case static_tracepoint:
  1983.           if (prev_stpoint != NULL
  1984.               && prev_stpoint->address == tpoint->address)
  1985.             /* Nothing to do.  We already unprobed a tracepoint set at
  1986.                this marker address (and there can only be one probe
  1987.                per marker).  */
  1988.             ;
  1989.           else
  1990.             {
  1991.               unprobe_marker_at (tpoint->address);
  1992.               prev_stpoint = tpoint;
  1993.             }
  1994.           break;
  1995.         }

  1996.       tpoint->handle = NULL;
  1997.     }

  1998.   unpause_all (1);
  1999. }

  2000. /* Parse a packet that defines a tracepoint.  */

  2001. static void
  2002. cmd_qtdp (char *own_buf)
  2003. {
  2004.   int tppacket;
  2005.   /* Whether there is a trailing hyphen at the end of the QTDP packet.  */
  2006.   int trail_hyphen = 0;
  2007.   ULONGEST num;
  2008.   ULONGEST addr;
  2009.   ULONGEST count;
  2010.   struct tracepoint *tpoint;
  2011.   char *actparm;
  2012.   char *packet = own_buf;

  2013.   packet += strlen ("QTDP:");

  2014.   /* A hyphen at the beginning marks a packet specifying actions for a
  2015.      tracepoint already supplied.  */
  2016.   tppacket = 1;
  2017.   if (*packet == '-')
  2018.     {
  2019.       tppacket = 0;
  2020.       ++packet;
  2021.     }
  2022.   packet = unpack_varlen_hex (packet, &num);
  2023.   ++packet; /* skip a colon */
  2024.   packet = unpack_varlen_hex (packet, &addr);
  2025.   ++packet; /* skip a colon */

  2026.   /* See if we already have this tracepoint.  */
  2027.   tpoint = find_tracepoint (num, addr);

  2028.   if (tppacket)
  2029.     {
  2030.       /* Duplicate tracepoints are never allowed.  */
  2031.       if (tpoint)
  2032.         {
  2033.           trace_debug ("Tracepoint error: tracepoint %d"
  2034.                        " at 0x%s already exists",
  2035.                        (int) num, paddress (addr));
  2036.           write_enn (own_buf);
  2037.           return;
  2038.         }

  2039.       tpoint = add_tracepoint (num, addr);

  2040.       tpoint->enabled = (*packet == 'E');
  2041.       ++packet; /* skip 'E' */
  2042.       ++packet; /* skip a colon */
  2043.       packet = unpack_varlen_hex (packet, &count);
  2044.       tpoint->step_count = count;
  2045.       ++packet; /* skip a colon */
  2046.       packet = unpack_varlen_hex (packet, &count);
  2047.       tpoint->pass_count = count;
  2048.       /* See if we have any of the additional optional fields.  */
  2049.       while (*packet == ':')
  2050.         {
  2051.           ++packet;
  2052.           if (*packet == 'F')
  2053.             {
  2054.               tpoint->type = fast_tracepoint;
  2055.               ++packet;
  2056.               packet = unpack_varlen_hex (packet, &count);
  2057.               tpoint->orig_size = count;
  2058.             }
  2059.           else if (*packet == 'S')
  2060.             {
  2061.               tpoint->type = static_tracepoint;
  2062.               ++packet;
  2063.             }
  2064.           else if (*packet == 'X')
  2065.             {
  2066.               actparm = (char *) packet;
  2067.               tpoint->cond = gdb_parse_agent_expr (&actparm);
  2068.               packet = actparm;
  2069.             }
  2070.           else if (*packet == '-')
  2071.             break;
  2072.           else if (*packet == '\0')
  2073.             break;
  2074.           else
  2075.             trace_debug ("Unknown optional tracepoint field");
  2076.         }
  2077.       if (*packet == '-')
  2078.         {
  2079.           trail_hyphen = 1;
  2080.           trace_debug ("Also has actions\n");
  2081.         }

  2082.       trace_debug ("Defined %stracepoint %d at 0x%s, "
  2083.                    "enabled %d step %" PRIu64 " pass %" PRIu64,
  2084.                    tpoint->type == fast_tracepoint ? "fast "
  2085.                    : tpoint->type == static_tracepoint ? "static " : "",
  2086.                    tpoint->number, paddress (tpoint->address), tpoint->enabled,
  2087.                    tpoint->step_count, tpoint->pass_count);
  2088.     }
  2089.   else if (tpoint)
  2090.     add_tracepoint_action (tpoint, packet);
  2091.   else
  2092.     {
  2093.       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
  2094.                    (int) num, paddress (addr));
  2095.       write_enn (own_buf);
  2096.       return;
  2097.     }

  2098.   /* Install tracepoint during tracing only once for each tracepoint location.
  2099.      For each tracepoint loc, GDB may send multiple QTDP packets, and we can
  2100.      determine the last QTDP packet for one tracepoint location by checking
  2101.      trailing hyphen in QTDP packet.  */
  2102.   if (tracing && !trail_hyphen)
  2103.     {
  2104.       struct tracepoint *tp = NULL;

  2105.       /* Pause all threads temporarily while we patch tracepoints.  */
  2106.       pause_all (0);

  2107.       /* download_tracepoint will update global `tracepoints'
  2108.          list, so it is unsafe to leave threads in jump pad.  */
  2109.       stabilize_threads ();

  2110.       /* Freeze threads.  */
  2111.       pause_all (1);


  2112.       if (tpoint->type != trap_tracepoint)
  2113.         {
  2114.           /* Find another fast or static tracepoint at the same address.  */
  2115.           for (tp = tracepoints; tp; tp = tp->next)
  2116.             {
  2117.               if (tp->address == tpoint->address && tp->type == tpoint->type
  2118.                   && tp->number != tpoint->number)
  2119.                 break;
  2120.             }

  2121.           /* TPOINT is installed at the same address as TP.  */
  2122.           if (tp)
  2123.             {
  2124.               if (tpoint->type == fast_tracepoint)
  2125.                 clone_fast_tracepoint (tpoint, tp);
  2126.               else if (tpoint->type == static_tracepoint)
  2127.                 tpoint->handle = (void *) -1;
  2128.             }
  2129.         }

  2130.       if (use_agent && tpoint->type == fast_tracepoint
  2131.           && agent_capability_check (AGENT_CAPA_FAST_TRACE))
  2132.         {
  2133.           /* Download and install fast tracepoint by agent.  */
  2134.           if (tracepoint_send_agent (tpoint) == 0)
  2135.             write_ok (own_buf);
  2136.           else
  2137.             {
  2138.               write_enn (own_buf);
  2139.               remove_tracepoint (tpoint);
  2140.             }
  2141.         }
  2142.       else
  2143.         {
  2144.           download_tracepoint (tpoint);

  2145.           if (tpoint->type == trap_tracepoint || tp == NULL)
  2146.             {
  2147.               install_tracepoint (tpoint, own_buf);
  2148.               if (strcmp (own_buf, "OK") != 0)
  2149.                 remove_tracepoint (tpoint);
  2150.             }
  2151.           else
  2152.             write_ok (own_buf);
  2153.         }

  2154.       unpause_all (1);
  2155.       return;
  2156.     }

  2157.   write_ok (own_buf);
  2158. }

  2159. static void
  2160. cmd_qtdpsrc (char *own_buf)
  2161. {
  2162.   ULONGEST num, addr, start, slen;
  2163.   struct tracepoint *tpoint;
  2164.   char *packet = own_buf;
  2165.   char *saved, *srctype, *src;
  2166.   size_t nbytes;
  2167.   struct source_string *last, *newlast;

  2168.   packet += strlen ("QTDPsrc:");

  2169.   packet = unpack_varlen_hex (packet, &num);
  2170.   ++packet; /* skip a colon */
  2171.   packet = unpack_varlen_hex (packet, &addr);
  2172.   ++packet; /* skip a colon */

  2173.   /* See if we already have this tracepoint.  */
  2174.   tpoint = find_tracepoint (num, addr);

  2175.   if (!tpoint)
  2176.     {
  2177.       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
  2178.                    (int) num, paddress (addr));
  2179.       write_enn (own_buf);
  2180.       return;
  2181.     }

  2182.   saved = packet;
  2183.   packet = strchr (packet, ':');
  2184.   srctype = xmalloc (packet - saved + 1);
  2185.   memcpy (srctype, saved, packet - saved);
  2186.   srctype[packet - saved] = '\0';
  2187.   ++packet;
  2188.   packet = unpack_varlen_hex (packet, &start);
  2189.   ++packet; /* skip a colon */
  2190.   packet = unpack_varlen_hex (packet, &slen);
  2191.   ++packet; /* skip a colon */
  2192.   src = xmalloc (slen + 1);
  2193.   nbytes = hex2bin (packet, (gdb_byte *) src, strlen (packet) / 2);
  2194.   src[nbytes] = '\0';

  2195.   newlast = xmalloc (sizeof (struct source_string));
  2196.   newlast->type = srctype;
  2197.   newlast->str = src;
  2198.   newlast->next = NULL;
  2199.   /* Always add a source string to the end of the list;
  2200.      this keeps sequences of actions/commands in the right
  2201.      order.  */
  2202.   if (tpoint->source_strings)
  2203.     {
  2204.       for (last = tpoint->source_strings; last->next; last = last->next)
  2205.         ;
  2206.       last->next = newlast;
  2207.     }
  2208.   else
  2209.     tpoint->source_strings = newlast;

  2210.   write_ok (own_buf);
  2211. }

  2212. static void
  2213. cmd_qtdv (char *own_buf)
  2214. {
  2215.   ULONGEST num, val, builtin;
  2216.   char *varname;
  2217.   size_t nbytes;
  2218.   struct trace_state_variable *tsv;
  2219.   char *packet = own_buf;

  2220.   packet += strlen ("QTDV:");

  2221.   packet = unpack_varlen_hex (packet, &num);
  2222.   ++packet; /* skip a colon */
  2223.   packet = unpack_varlen_hex (packet, &val);
  2224.   ++packet; /* skip a colon */
  2225.   packet = unpack_varlen_hex (packet, &builtin);
  2226.   ++packet; /* skip a colon */

  2227.   nbytes = strlen (packet) / 2;
  2228.   varname = xmalloc (nbytes + 1);
  2229.   nbytes = hex2bin (packet, (gdb_byte *) varname, nbytes);
  2230.   varname[nbytes] = '\0';

  2231.   tsv = create_trace_state_variable (num, 1);
  2232.   tsv->initial_value = (LONGEST) val;
  2233.   tsv->name = varname;

  2234.   set_trace_state_variable_value (num, (LONGEST) val);

  2235.   write_ok (own_buf);
  2236. }

  2237. static void
  2238. cmd_qtenable_disable (char *own_buf, int enable)
  2239. {
  2240.   char *packet = own_buf;
  2241.   ULONGEST num, addr;
  2242.   struct tracepoint *tp;

  2243.   packet += strlen (enable ? "QTEnable:" : "QTDisable:");
  2244.   packet = unpack_varlen_hex (packet, &num);
  2245.   ++packet; /* skip a colon */
  2246.   packet = unpack_varlen_hex (packet, &addr);

  2247.   tp = find_tracepoint (num, addr);

  2248.   if (tp)
  2249.     {
  2250.       if ((enable && tp->enabled) || (!enable && !tp->enabled))
  2251.         {
  2252.           trace_debug ("Tracepoint %d at 0x%s is already %s",
  2253.                        (int) num, paddress (addr),
  2254.                        enable ? "enabled" : "disabled");
  2255.           write_ok (own_buf);
  2256.           return;
  2257.         }

  2258.       trace_debug ("%s tracepoint %d at 0x%s",
  2259.                    enable ? "Enabling" : "Disabling",
  2260.                    (int) num, paddress (addr));

  2261.       tp->enabled = enable;

  2262.       if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
  2263.         {
  2264.           int ret;
  2265.           int offset = offsetof (struct tracepoint, enabled);
  2266.           CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;

  2267.           ret = prepare_to_access_memory ();
  2268.           if (ret)
  2269.             {
  2270.               trace_debug ("Failed to temporarily stop inferior threads");
  2271.               write_enn (own_buf);
  2272.               return;
  2273.             }

  2274.           ret = write_inferior_integer (obj_addr, enable);
  2275.           done_accessing_memory ();

  2276.           if (ret)
  2277.             {
  2278.               trace_debug ("Cannot write enabled flag into "
  2279.                            "inferior process memory");
  2280.               write_enn (own_buf);
  2281.               return;
  2282.             }
  2283.         }

  2284.       write_ok (own_buf);
  2285.     }
  2286.   else
  2287.     {
  2288.       trace_debug ("Tracepoint %d at 0x%s not found",
  2289.                    (int) num, paddress (addr));
  2290.       write_enn (own_buf);
  2291.     }
  2292. }

  2293. static void
  2294. cmd_qtv (char *own_buf)
  2295. {
  2296.   ULONGEST num;
  2297.   LONGEST val = 0;
  2298.   int err;
  2299.   char *packet = own_buf;

  2300.   packet += strlen ("qTV:");
  2301.   unpack_varlen_hex (packet, &num);

  2302.   if (current_traceframe >= 0)
  2303.     {
  2304.       err = traceframe_read_tsv ((int) num, &val);
  2305.       if (err)
  2306.         {
  2307.           strcpy (own_buf, "U");
  2308.           return;
  2309.         }
  2310.     }
  2311.   /* Only make tsv's be undefined before the first trace run.  After a
  2312.      trace run is over, the user might want to see the last value of
  2313.      the tsv, and it might not be available in a traceframe.  */
  2314.   else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
  2315.     {
  2316.       strcpy (own_buf, "U");
  2317.       return;
  2318.     }
  2319.   else
  2320.     val = get_trace_state_variable_value (num);

  2321.   sprintf (own_buf, "V%s", phex_nz (val, 0));
  2322. }

  2323. /* Clear out the list of readonly regions.  */

  2324. static void
  2325. clear_readonly_regions (void)
  2326. {
  2327.   struct readonly_region *roreg;

  2328.   while (readonly_regions)
  2329.     {
  2330.       roreg = readonly_regions;
  2331.       readonly_regions = readonly_regions->next;
  2332.       free (roreg);
  2333.     }
  2334. }

  2335. /* Parse the collection of address ranges whose contents GDB believes
  2336.    to be unchanging and so can be read directly from target memory
  2337.    even while looking at a traceframe.  */

  2338. static void
  2339. cmd_qtro (char *own_buf)
  2340. {
  2341.   ULONGEST start, end;
  2342.   struct readonly_region *roreg;
  2343.   char *packet = own_buf;

  2344.   trace_debug ("Want to mark readonly regions");

  2345.   clear_readonly_regions ();

  2346.   packet += strlen ("QTro");

  2347.   while (*packet == ':')
  2348.     {
  2349.       ++packet;  /* skip a colon */
  2350.       packet = unpack_varlen_hex (packet, &start);
  2351.       ++packet;  /* skip a comma */
  2352.       packet = unpack_varlen_hex (packet, &end);
  2353.       roreg = xmalloc (sizeof (struct readonly_region));
  2354.       roreg->start = start;
  2355.       roreg->end = end;
  2356.       roreg->next = readonly_regions;
  2357.       readonly_regions = roreg;
  2358.       trace_debug ("Added readonly region from 0x%s to 0x%s",
  2359.                    paddress (roreg->start), paddress (roreg->end));
  2360.     }

  2361.   write_ok (own_buf);
  2362. }

  2363. /* Test to see if the given range is in our list of readonly ranges.
  2364.    We only test for being entirely within a range, GDB is not going to
  2365.    send a single memory packet that spans multiple regions.  */

  2366. int
  2367. in_readonly_region (CORE_ADDR addr, ULONGEST length)
  2368. {
  2369.   struct readonly_region *roreg;

  2370.   for (roreg = readonly_regions; roreg; roreg = roreg->next)
  2371.     if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
  2372.       return 1;

  2373.   return 0;
  2374. }

  2375. /* The maximum size of a jump pad entry.  */
  2376. static const int max_jump_pad_size = 0x100;

  2377. static CORE_ADDR gdb_jump_pad_head;

  2378. /* Return the address of the next free jump space.  */

  2379. static CORE_ADDR
  2380. get_jump_space_head (void)
  2381. {
  2382.   if (gdb_jump_pad_head == 0)
  2383.     {
  2384.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
  2385.                                       &gdb_jump_pad_head))
  2386.         {
  2387.           internal_error (__FILE__, __LINE__,
  2388.                           "error extracting jump_pad_buffer");
  2389.         }
  2390.     }

  2391.   return gdb_jump_pad_head;
  2392. }

  2393. /* Reserve USED bytes from the jump space.  */

  2394. static void
  2395. claim_jump_space (ULONGEST used)
  2396. {
  2397.   trace_debug ("claim_jump_space reserves %s bytes at %s",
  2398.                pulongest (used), paddress (gdb_jump_pad_head));
  2399.   gdb_jump_pad_head += used;
  2400. }

  2401. static CORE_ADDR trampoline_buffer_head = 0;
  2402. static CORE_ADDR trampoline_buffer_tail;

  2403. /* Reserve USED bytes from the trampoline buffer and return the
  2404.    address of the start of the reserved space in TRAMPOLINE.  Returns
  2405.    non-zero if the space is successfully claimed.  */

  2406. int
  2407. claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
  2408. {
  2409.   if (!trampoline_buffer_head)
  2410.     {
  2411.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
  2412.                                       &trampoline_buffer_tail))
  2413.         {
  2414.           internal_error (__FILE__, __LINE__,
  2415.                           "error extracting trampoline_buffer");
  2416.         }

  2417.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
  2418.                                       &trampoline_buffer_head))
  2419.         {
  2420.           internal_error (__FILE__, __LINE__,
  2421.                           "error extracting trampoline_buffer_end");
  2422.         }
  2423.     }

  2424.   /* Start claiming space from the top of the trampoline space.  If
  2425.      the space is located at the bottom of the virtual address space,
  2426.      this reduces the possibility that corruption will occur if a null
  2427.      pointer is used to write to memory.  */
  2428.   if (trampoline_buffer_head - trampoline_buffer_tail < used)
  2429.     {
  2430.       trace_debug ("claim_trampoline_space failed to reserve %s bytes",
  2431.                    pulongest (used));
  2432.       return 0;
  2433.     }

  2434.   trampoline_buffer_head -= used;

  2435.   trace_debug ("claim_trampoline_space reserves %s bytes at %s",
  2436.                pulongest (used), paddress (trampoline_buffer_head));

  2437.   *trampoline = trampoline_buffer_head;
  2438.   return 1;
  2439. }

  2440. /* Returns non-zero if there is space allocated for use in trampolines
  2441.    for fast tracepoints.  */

  2442. int
  2443. have_fast_tracepoint_trampoline_buffer (char *buf)
  2444. {
  2445.   CORE_ADDR trampoline_end, errbuf;

  2446.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
  2447.                                   &trampoline_end))
  2448.     {
  2449.       internal_error (__FILE__, __LINE__,
  2450.                       "error extracting trampoline_buffer_end");
  2451.     }

  2452.   if (buf)
  2453.     {
  2454.       buf[0] = '\0';
  2455.       strcpy (buf, "was claiming");
  2456.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
  2457.                                   &errbuf))
  2458.         {
  2459.           internal_error (__FILE__, __LINE__,
  2460.                           "error extracting errbuf");
  2461.         }

  2462.       read_inferior_memory (errbuf, (unsigned char *) buf, 100);
  2463.     }

  2464.   return trampoline_end != 0;
  2465. }

  2466. /* Ask the IPA to probe the marker at ADDRESS.  Returns -1 if running
  2467.    the command fails, or 0 otherwise.  If the command ran
  2468.    successfully, but probing the marker failed, ERROUT will be filled
  2469.    with the error to reply to GDB, and -1 is also returned.  This
  2470.    allows directly passing IPA errors to GDB.  */

  2471. static int
  2472. probe_marker_at (CORE_ADDR address, char *errout)
  2473. {
  2474.   char cmd[IPA_CMD_BUF_SIZE];
  2475.   int err;

  2476.   sprintf (cmd, "probe_marker_at:%s", paddress (address));
  2477.   err = run_inferior_command (cmd, strlen (cmd) + 1);

  2478.   if (err == 0)
  2479.     {
  2480.       if (*cmd == 'E')
  2481.         {
  2482.           strcpy (errout, cmd);
  2483.           return -1;
  2484.         }
  2485.     }

  2486.   return err;
  2487. }

  2488. static void
  2489. clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
  2490. {
  2491.   to->jump_pad = from->jump_pad;
  2492.   to->jump_pad_end = from->jump_pad_end;
  2493.   to->trampoline = from->trampoline;
  2494.   to->trampoline_end = from->trampoline_end;
  2495.   to->adjusted_insn_addr = from->adjusted_insn_addr;
  2496.   to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
  2497.   to->handle = from->handle;

  2498.   gdb_assert (from->handle);
  2499.   inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
  2500. }

  2501. #define MAX_JUMP_SIZE 20

  2502. /* Install fast tracepoint.  Return 0 if successful, otherwise return
  2503.    non-zero.  */

  2504. static int
  2505. install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
  2506. {
  2507.   CORE_ADDR jentry, jump_entry;
  2508.   CORE_ADDR trampoline;
  2509.   ULONGEST trampoline_size;
  2510.   int err = 0;
  2511.   /* The jump to the jump pad of the last fast tracepoint
  2512.      installed.  */
  2513.   unsigned char fjump[MAX_JUMP_SIZE];
  2514.   ULONGEST fjump_size;

  2515.   if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
  2516.     {
  2517.       trace_debug ("Requested a fast tracepoint on an instruction "
  2518.                    "that is of less than the minimum length.");
  2519.       return 0;
  2520.     }

  2521.   jentry = jump_entry = get_jump_space_head ();

  2522.   trampoline = 0;
  2523.   trampoline_size = 0;

  2524.   /* Install the jump pad.  */
  2525.   err = install_fast_tracepoint_jump_pad (tpoint->obj_addr_on_target,
  2526.                                           tpoint->address,
  2527.                                           ipa_sym_addrs.addr_gdb_collect,
  2528.                                           ipa_sym_addrs.addr_collecting,
  2529.                                           tpoint->orig_size,
  2530.                                           &jentry,
  2531.                                           &trampoline, &trampoline_size,
  2532.                                           fjump, &fjump_size,
  2533.                                           &tpoint->adjusted_insn_addr,
  2534.                                           &tpoint->adjusted_insn_addr_end,
  2535.                                           errbuf);

  2536.   if (err)
  2537.     return 1;

  2538.   /* Wire it in.  */
  2539.   tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
  2540.                                              fjump_size);

  2541.   if (tpoint->handle != NULL)
  2542.     {
  2543.       tpoint->jump_pad = jump_entry;
  2544.       tpoint->jump_pad_end = jentry;
  2545.       tpoint->trampoline = trampoline;
  2546.       tpoint->trampoline_end = trampoline + trampoline_size;

  2547.       /* Pad to 8-byte alignment.  */
  2548.       jentry = ((jentry + 7) & ~0x7);
  2549.       claim_jump_space (jentry - jump_entry);
  2550.     }

  2551.   return 0;
  2552. }


  2553. /* Install tracepoint TPOINT, and write reply message in OWN_BUF.  */

  2554. static void
  2555. install_tracepoint (struct tracepoint *tpoint, char *own_buf)
  2556. {
  2557.   tpoint->handle = NULL;
  2558.   *own_buf = '\0';

  2559.   if (tpoint->type == trap_tracepoint)
  2560.     {
  2561.       /* Tracepoints are installed as memory breakpoints.  Just go
  2562.          ahead and install the trap.  The breakpoints module
  2563.          handles duplicated breakpoints, and the memory read
  2564.          routine handles un-patching traps from memory reads.  */
  2565.       tpoint->handle = set_breakpoint_at (tpoint->address,
  2566.                                           tracepoint_handler);
  2567.     }
  2568.   else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
  2569.     {
  2570.       if (!agent_loaded_p ())
  2571.         {
  2572.           trace_debug ("Requested a %s tracepoint, but fast "
  2573.                        "tracepoints aren't supported.",
  2574.                        tpoint->type == static_tracepoint ? "static" : "fast");
  2575.           write_e_ipa_not_loaded (own_buf);
  2576.           return;
  2577.         }
  2578.       if (tpoint->type == static_tracepoint
  2579.           && !in_process_agent_supports_ust ())
  2580.         {
  2581.           trace_debug ("Requested a static tracepoint, but static "
  2582.                        "tracepoints are not supported.");
  2583.           write_e_ust_not_loaded (own_buf);
  2584.           return;
  2585.         }

  2586.       if (tpoint->type == fast_tracepoint)
  2587.         install_fast_tracepoint (tpoint, own_buf);
  2588.       else
  2589.         {
  2590.           if (probe_marker_at (tpoint->address, own_buf) == 0)
  2591.             tpoint->handle = (void *) -1;
  2592.         }

  2593.     }
  2594.   else
  2595.     internal_error (__FILE__, __LINE__, "Unknown tracepoint type");

  2596.   if (tpoint->handle == NULL)
  2597.     {
  2598.       if (*own_buf == '\0')
  2599.         write_enn (own_buf);
  2600.     }
  2601.   else
  2602.     write_ok (own_buf);
  2603. }

  2604. static void download_tracepoint_1 (struct tracepoint *tpoint);

  2605. static void
  2606. cmd_qtstart (char *packet)
  2607. {
  2608.   struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
  2609.   CORE_ADDR tpptr = 0, prev_tpptr = 0;

  2610.   trace_debug ("Starting the trace");

  2611.   /* Pause all threads temporarily while we patch tracepoints.  */
  2612.   pause_all (0);

  2613.   /* Get threads out of jump pads.  Safe to do here, since this is a
  2614.      top level command.  And, required to do here, since we're
  2615.      deleting/rewriting jump pads.  */

  2616.   stabilize_threads ();

  2617.   /* Freeze threads.  */
  2618.   pause_all (1);

  2619.   /* Sync the fast tracepoints list in the inferior ftlib.  */
  2620.   if (agent_loaded_p ())
  2621.     download_trace_state_variables ();

  2622.   /* No previous fast tpoint yet.  */
  2623.   prev_ftpoint = NULL;

  2624.   /* No previous static tpoint yet.  */
  2625.   prev_stpoint = NULL;

  2626.   *packet = '\0';

  2627.   /* Start out empty.  */
  2628.   if (agent_loaded_p ())
  2629.     write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, 0);

  2630.   /* Download and install tracepoints.  */
  2631.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  2632.     {
  2633.       /* Ensure all the hit counts start at zero.  */
  2634.       tpoint->hit_count = 0;
  2635.       tpoint->traceframe_usage = 0;

  2636.       if (tpoint->type == trap_tracepoint)
  2637.         {
  2638.           /* Tracepoints are installed as memory breakpoints.  Just go
  2639.              ahead and install the trap.  The breakpoints module
  2640.              handles duplicated breakpoints, and the memory read
  2641.              routine handles un-patching traps from memory reads.  */
  2642.           tpoint->handle = set_breakpoint_at (tpoint->address,
  2643.                                               tracepoint_handler);
  2644.         }
  2645.       else if (tpoint->type == fast_tracepoint
  2646.                || tpoint->type == static_tracepoint)
  2647.         {
  2648.           if (maybe_write_ipa_not_loaded (packet))
  2649.             {
  2650.               trace_debug ("Requested a %s tracepoint, but fast "
  2651.                            "tracepoints aren't supported.",
  2652.                            tpoint->type == static_tracepoint
  2653.                            ? "static" : "fast");
  2654.               break;
  2655.             }

  2656.           if (tpoint->type == fast_tracepoint)
  2657.             {
  2658.               int use_agent_p
  2659.                 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);

  2660.               if (prev_ftpoint != NULL
  2661.                   && prev_ftpoint->address == tpoint->address)
  2662.                 {
  2663.                   if (use_agent_p)
  2664.                     tracepoint_send_agent (tpoint);
  2665.                   else
  2666.                     download_tracepoint_1 (tpoint);

  2667.                   clone_fast_tracepoint (tpoint, prev_ftpoint);
  2668.                 }
  2669.               else
  2670.                 {
  2671.                   /* Tracepoint is installed successfully?  */
  2672.                   int installed = 0;

  2673.                   /* Download and install fast tracepoint by agent.  */
  2674.                   if (use_agent_p)
  2675.                     installed = !tracepoint_send_agent (tpoint);
  2676.                   else
  2677.                     {
  2678.                       download_tracepoint_1 (tpoint);
  2679.                       installed = !install_fast_tracepoint (tpoint, packet);
  2680.                     }

  2681.                   if (installed)
  2682.                     prev_ftpoint = tpoint;
  2683.                 }
  2684.             }
  2685.           else
  2686.             {
  2687.               if (!in_process_agent_supports_ust ())
  2688.                 {
  2689.                   trace_debug ("Requested a static tracepoint, but static "
  2690.                                "tracepoints are not supported.");
  2691.                   break;
  2692.                 }

  2693.               download_tracepoint_1 (tpoint);
  2694.               /* Can only probe a given marker once.  */
  2695.               if (prev_stpoint != NULL
  2696.                   && prev_stpoint->address == tpoint->address)
  2697.                 tpoint->handle = (void *) -1;
  2698.               else
  2699.                 {
  2700.                   if (probe_marker_at (tpoint->address, packet) == 0)
  2701.                     {
  2702.                       tpoint->handle = (void *) -1;

  2703.                       /* So that we can handle multiple static tracepoints
  2704.                          at the same address easily.  */
  2705.                       prev_stpoint = tpoint;
  2706.                     }
  2707.                 }
  2708.             }

  2709.           prev_tpptr = tpptr;
  2710.           tpptr = tpoint->obj_addr_on_target;

  2711.           if (tpoint == tracepoints)
  2712.             /* First object in list, set the head pointer in the
  2713.                inferior.  */
  2714.             write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, tpptr);
  2715.           else
  2716.             write_inferior_data_ptr (prev_tpptr + offsetof (struct tracepoint,
  2717.                                                             next),
  2718.                                      tpptr);
  2719.         }

  2720.       /* Any failure in the inner loop is sufficient cause to give
  2721.          up.  */
  2722.       if (tpoint->handle == NULL)
  2723.         break;
  2724.     }

  2725.   /* Any error in tracepoint insertion is unacceptable; better to
  2726.      address the problem now, than end up with a useless or misleading
  2727.      trace run.  */
  2728.   if (tpoint != NULL)
  2729.     {
  2730.       clear_installed_tracepoints ();
  2731.       if (*packet == '\0')
  2732.         write_enn (packet);
  2733.       unpause_all (1);
  2734.       return;
  2735.     }

  2736.   stopping_tracepoint = NULL;
  2737.   trace_buffer_is_full = 0;
  2738.   expr_eval_result = expr_eval_no_error;
  2739.   error_tracepoint = NULL;
  2740.   tracing_start_time = get_timestamp ();

  2741.   /* Tracing is now active, hits will now start being logged.  */
  2742.   tracing = 1;

  2743.   if (agent_loaded_p ())
  2744.     {
  2745.       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
  2746.         {
  2747.           internal_error (__FILE__, __LINE__,
  2748.                           "Error setting tracing variable in lib");
  2749.         }

  2750.       if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
  2751.                                        0))
  2752.         {
  2753.           internal_error (__FILE__, __LINE__,
  2754.                           "Error clearing stopping_tracepoint variable"
  2755.                           " in lib");
  2756.         }

  2757.       if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
  2758.         {
  2759.           internal_error (__FILE__, __LINE__,
  2760.                           "Error clearing trace_buffer_is_full variable"
  2761.                           " in lib");
  2762.         }

  2763.       stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
  2764.                                              stop_tracing_handler);
  2765.       if (stop_tracing_bkpt == NULL)
  2766.         error ("Error setting stop_tracing breakpoint");

  2767.       flush_trace_buffer_bkpt
  2768.         = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
  2769.                              flush_trace_buffer_handler);
  2770.       if (flush_trace_buffer_bkpt == NULL)
  2771.         error ("Error setting flush_trace_buffer breakpoint");
  2772.     }

  2773.   unpause_all (1);

  2774.   write_ok (packet);
  2775. }

  2776. /* End a tracing run, filling in a stop reason to report back to GDB,
  2777.    and removing the tracepoints from the code.  */

  2778. void
  2779. stop_tracing (void)
  2780. {
  2781.   if (!tracing)
  2782.     {
  2783.       trace_debug ("Tracing is already off, ignoring");
  2784.       return;
  2785.     }

  2786.   trace_debug ("Stopping the trace");

  2787.   /* Pause all threads before removing fast jumps from memory,
  2788.      breakpoints, and touching IPA state variables (inferior memory).
  2789.      Some thread may hit the internal tracing breakpoints, or be
  2790.      collecting this moment, but that's ok, we don't release the
  2791.      tpoint object's memory or the jump pads here (we only do that
  2792.      when we're sure we can move all threads out of the jump pads).
  2793.      We can't now, since we may be getting here due to the inferior
  2794.      agent calling us.  */
  2795.   pause_all (1);

  2796.   /* Stop logging. Tracepoints can still be hit, but they will not be
  2797.      recorded.  */
  2798.   tracing = 0;
  2799.   if (agent_loaded_p ())
  2800.     {
  2801.       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
  2802.         {
  2803.           internal_error (__FILE__, __LINE__,
  2804.                           "Error clearing tracing variable in lib");
  2805.         }
  2806.     }

  2807.   tracing_stop_time = get_timestamp ();
  2808.   tracing_stop_reason = "t???";
  2809.   tracing_stop_tpnum = 0;
  2810.   if (stopping_tracepoint)
  2811.     {
  2812.       trace_debug ("Stopping the trace because "
  2813.                    "tracepoint %d was hit %" PRIu64 " times",
  2814.                    stopping_tracepoint->number,
  2815.                    stopping_tracepoint->pass_count);
  2816.       tracing_stop_reason = "tpasscount";
  2817.       tracing_stop_tpnum = stopping_tracepoint->number;
  2818.     }
  2819.   else if (trace_buffer_is_full)
  2820.     {
  2821.       trace_debug ("Stopping the trace because the trace buffer is full");
  2822.       tracing_stop_reason = "tfull";
  2823.     }
  2824.   else if (expr_eval_result != expr_eval_no_error)
  2825.     {
  2826.       trace_debug ("Stopping the trace because of an expression eval error");
  2827.       tracing_stop_reason = eval_result_names[expr_eval_result];
  2828.       tracing_stop_tpnum = error_tracepoint->number;
  2829.     }
  2830. #ifndef IN_PROCESS_AGENT
  2831.   else if (!gdb_connected ())
  2832.     {
  2833.       trace_debug ("Stopping the trace because GDB disconnected");
  2834.       tracing_stop_reason = "tdisconnected";
  2835.     }
  2836. #endif
  2837.   else
  2838.     {
  2839.       trace_debug ("Stopping the trace because of a tstop command");
  2840.       tracing_stop_reason = "tstop";
  2841.     }

  2842.   stopping_tracepoint = NULL;
  2843.   error_tracepoint = NULL;

  2844.   /* Clear out the tracepoints.  */
  2845.   clear_installed_tracepoints ();

  2846.   if (agent_loaded_p ())
  2847.     {
  2848.       /* Pull in fast tracepoint trace frames from the inferior lib
  2849.          buffer into our buffer, even if our buffer is already full,
  2850.          because we want to present the full number of created frames
  2851.          in addition to what fit in the trace buffer.  */
  2852.       upload_fast_traceframes ();
  2853.     }

  2854.   if (stop_tracing_bkpt != NULL)
  2855.     {
  2856.       delete_breakpoint (stop_tracing_bkpt);
  2857.       stop_tracing_bkpt = NULL;
  2858.     }

  2859.   if (flush_trace_buffer_bkpt != NULL)
  2860.     {
  2861.       delete_breakpoint (flush_trace_buffer_bkpt);
  2862.       flush_trace_buffer_bkpt = NULL;
  2863.     }

  2864.   unpause_all (1);
  2865. }

  2866. static int
  2867. stop_tracing_handler (CORE_ADDR addr)
  2868. {
  2869.   trace_debug ("lib hit stop_tracing");

  2870.   /* Don't actually handle it here.  When we stop tracing we remove
  2871.      breakpoints from the inferior, and that is not allowed in a
  2872.      breakpoint handler (as the caller is walking the breakpoint
  2873.      list).  */
  2874.   return 0;
  2875. }

  2876. static int
  2877. flush_trace_buffer_handler (CORE_ADDR addr)
  2878. {
  2879.   trace_debug ("lib hit flush_trace_buffer");
  2880.   return 0;
  2881. }

  2882. static void
  2883. cmd_qtstop (char *packet)
  2884. {
  2885.   stop_tracing ();
  2886.   write_ok (packet);
  2887. }

  2888. static void
  2889. cmd_qtdisconnected (char *own_buf)
  2890. {
  2891.   ULONGEST setting;
  2892.   char *packet = own_buf;

  2893.   packet += strlen ("QTDisconnected:");

  2894.   unpack_varlen_hex (packet, &setting);

  2895.   write_ok (own_buf);

  2896.   disconnected_tracing = setting;
  2897. }

  2898. static void
  2899. cmd_qtframe (char *own_buf)
  2900. {
  2901.   ULONGEST frame, pc, lo, hi, num;
  2902.   int tfnum, tpnum;
  2903.   struct traceframe *tframe;
  2904.   char *packet = own_buf;

  2905.   packet += strlen ("QTFrame:");

  2906.   if (strncmp (packet, "pc:", strlen ("pc:")) == 0)
  2907.     {
  2908.       packet += strlen ("pc:");
  2909.       unpack_varlen_hex (packet, &pc);
  2910.       trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
  2911.       tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
  2912.     }
  2913.   else if (strncmp (packet, "range:", strlen ("range:")) == 0)
  2914.     {
  2915.       packet += strlen ("range:");
  2916.       packet = unpack_varlen_hex (packet, &lo);
  2917.       ++packet;
  2918.       unpack_varlen_hex (packet, &hi);
  2919.       trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
  2920.                    paddress (lo), paddress (hi));
  2921.       tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
  2922.     }
  2923.   else if (strncmp (packet, "outside:", strlen ("outside:")) == 0)
  2924.     {
  2925.       packet += strlen ("outside:");
  2926.       packet = unpack_varlen_hex (packet, &lo);
  2927.       ++packet;
  2928.       unpack_varlen_hex (packet, &hi);
  2929.       trace_debug ("Want to find next traceframe "
  2930.                    "outside the range 0x%s to 0x%s",
  2931.                    paddress (lo), paddress (hi));
  2932.       tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
  2933.     }
  2934.   else if (strncmp (packet, "tdp:", strlen ("tdp:")) == 0)
  2935.     {
  2936.       packet += strlen ("tdp:");
  2937.       unpack_varlen_hex (packet, &num);
  2938.       tpnum = (int) num;
  2939.       trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
  2940.       tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
  2941.     }
  2942.   else
  2943.     {
  2944.       unpack_varlen_hex (packet, &frame);
  2945.       tfnum = (int) frame;
  2946.       if (tfnum == -1)
  2947.         {
  2948.           trace_debug ("Want to stop looking at traceframes");
  2949.           current_traceframe = -1;
  2950.           write_ok (own_buf);
  2951.           return;
  2952.         }
  2953.       trace_debug ("Want to look at traceframe %d", tfnum);
  2954.       tframe = find_traceframe (tfnum);
  2955.     }

  2956.   if (tframe)
  2957.     {
  2958.       current_traceframe = tfnum;
  2959.       sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
  2960.     }
  2961.   else
  2962.     sprintf (own_buf, "F-1");
  2963. }

  2964. static void
  2965. cmd_qtstatus (char *packet)
  2966. {
  2967.   char *stop_reason_rsp = NULL;
  2968.   char *buf1, *buf2, *buf3, *str;
  2969.   int slen;

  2970.   /* Translate the plain text of the notes back into hex for
  2971.      transmission.  */

  2972.   str = (tracing_user_name ? tracing_user_name : "");
  2973.   slen = strlen (str);
  2974.   buf1 = (char *) alloca (slen * 2 + 1);
  2975.   bin2hex ((gdb_byte *) str, buf1, slen);

  2976.   str = (tracing_notes ? tracing_notes : "");
  2977.   slen = strlen (str);
  2978.   buf2 = (char *) alloca (slen * 2 + 1);
  2979.   bin2hex ((gdb_byte *) str, buf2, slen);

  2980.   str = (tracing_stop_note ? tracing_stop_note : "");
  2981.   slen = strlen (str);
  2982.   buf3 = (char *) alloca (slen * 2 + 1);
  2983.   bin2hex ((gdb_byte *) str, buf3, slen);

  2984.   trace_debug ("Returning trace status as %d, stop reason %s",
  2985.                tracing, tracing_stop_reason);

  2986.   if (agent_loaded_p ())
  2987.     {
  2988.       pause_all (1);

  2989.       upload_fast_traceframes ();

  2990.       unpause_all (1);
  2991.    }

  2992.   stop_reason_rsp = (char *) tracing_stop_reason;

  2993.   /* The user visible error string in terror needs to be hex encoded.
  2994.      We leave it as plain string in `tracing_stop_reason' to ease
  2995.      debugging.  */
  2996.   if (strncmp (stop_reason_rsp, "terror:", strlen ("terror:")) == 0)
  2997.     {
  2998.       const char *result_name;
  2999.       int hexstr_len;
  3000.       char *p;

  3001.       result_name = stop_reason_rsp + strlen ("terror:");
  3002.       hexstr_len = strlen (result_name) * 2;
  3003.       p = stop_reason_rsp = alloca (strlen ("terror:") + hexstr_len + 1);
  3004.       strcpy (p, "terror:");
  3005.       p += strlen (p);
  3006.       bin2hex ((gdb_byte *) result_name, p, strlen (result_name));
  3007.     }

  3008.   /* If this was a forced stop, include any stop note that was supplied.  */
  3009.   if (strcmp (stop_reason_rsp, "tstop") == 0)
  3010.     {
  3011.       stop_reason_rsp = alloca (strlen ("tstop:") + strlen (buf3) + 1);
  3012.       strcpy (stop_reason_rsp, "tstop:");
  3013.       strcat (stop_reason_rsp, buf3);
  3014.     }

  3015.   sprintf (packet,
  3016.            "T%d;"
  3017.            "%s:%x;"
  3018.            "tframes:%x;tcreated:%x;"
  3019.            "tfree:%x;tsize:%s;"
  3020.            "circular:%d;"
  3021.            "disconn:%d;"
  3022.            "starttime:%s;stoptime:%s;"
  3023.            "username:%s;notes:%s:",
  3024.            tracing ? 1 : 0,
  3025.            stop_reason_rsp, tracing_stop_tpnum,
  3026.            traceframe_count, traceframes_created,
  3027.            free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
  3028.            circular_trace_buffer,
  3029.            disconnected_tracing,
  3030.            phex_nz (tracing_start_time, sizeof (tracing_start_time)),
  3031.            phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
  3032.            buf1, buf2);
  3033. }

  3034. static void
  3035. cmd_qtp (char *own_buf)
  3036. {
  3037.   ULONGEST num, addr;
  3038.   struct tracepoint *tpoint;
  3039.   char *packet = own_buf;

  3040.   packet += strlen ("qTP:");

  3041.   packet = unpack_varlen_hex (packet, &num);
  3042.   ++packet; /* skip a colon */
  3043.   packet = unpack_varlen_hex (packet, &addr);

  3044.   /* See if we already have this tracepoint.  */
  3045.   tpoint = find_tracepoint (num, addr);

  3046.   if (!tpoint)
  3047.     {
  3048.       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
  3049.                    (int) num, paddress (addr));
  3050.       write_enn (own_buf);
  3051.       return;
  3052.     }

  3053.   sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
  3054.            tpoint->traceframe_usage);
  3055. }

  3056. /* State variables to help return all the tracepoint bits.  */
  3057. static struct tracepoint *cur_tpoint;
  3058. static unsigned int cur_action;
  3059. static unsigned int cur_step_action;
  3060. static struct source_string *cur_source_string;
  3061. static struct trace_state_variable *cur_tsv;

  3062. /* Compose a response that is an imitation of the syntax by which the
  3063.    tracepoint was originally downloaded.  */

  3064. static void
  3065. response_tracepoint (char *packet, struct tracepoint *tpoint)
  3066. {
  3067.   char *buf;

  3068.   sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
  3069.            paddress (tpoint->address),
  3070.            (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
  3071.            tpoint->pass_count);
  3072.   if (tpoint->type == fast_tracepoint)
  3073.     sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
  3074.   else if (tpoint->type == static_tracepoint)
  3075.     sprintf (packet + strlen (packet), ":S");

  3076.   if (tpoint->cond)
  3077.     {
  3078.       buf = gdb_unparse_agent_expr (tpoint->cond);
  3079.       sprintf (packet + strlen (packet), ":X%x,%s",
  3080.                tpoint->cond->length, buf);
  3081.       free (buf);
  3082.     }
  3083. }

  3084. /* Compose a response that is an imitation of the syntax by which the
  3085.    tracepoint action was originally downloaded (with the difference
  3086.    that due to the way we store the actions, this will output a packet
  3087.    per action, while GDB could have combined more than one action
  3088.    per-packet.  */

  3089. static void
  3090. response_action (char *packet, struct tracepoint *tpoint,
  3091.                  char *taction, int step)
  3092. {
  3093.   sprintf (packet, "%c%x:%s:%s",
  3094.            (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
  3095.            taction);
  3096. }

  3097. /* Compose a response that is an imitation of the syntax by which the
  3098.    tracepoint source piece was originally downloaded.  */

  3099. static void
  3100. response_source (char *packet,
  3101.                  struct tracepoint *tpoint, struct source_string *src)
  3102. {
  3103.   char *buf;
  3104.   int len;

  3105.   len = strlen (src->str);
  3106.   buf = alloca (len * 2 + 1);
  3107.   bin2hex ((gdb_byte *) src->str, buf, len);

  3108.   sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
  3109.            tpoint->number, paddress (tpoint->address),
  3110.            src->type, 0, len, buf);
  3111. }

  3112. /* Return the first piece of tracepoint definition, and initialize the
  3113.    state machine that will iterate through all the tracepoint
  3114.    bits.  */

  3115. static void
  3116. cmd_qtfp (char *packet)
  3117. {
  3118.   trace_debug ("Returning first tracepoint definition piece");

  3119.   cur_tpoint = tracepoints;
  3120.   cur_action = cur_step_action = 0;
  3121.   cur_source_string = NULL;

  3122.   if (cur_tpoint)
  3123.     response_tracepoint (packet, cur_tpoint);
  3124.   else
  3125.     strcpy (packet, "l");
  3126. }

  3127. /* Return additional pieces of tracepoint definition.  Each action and
  3128.    stepping action must go into its own packet, because of packet size
  3129.    limits, and so we use state variables to deliver one piece at a
  3130.    time.  */

  3131. static void
  3132. cmd_qtsp (char *packet)
  3133. {
  3134.   trace_debug ("Returning subsequent tracepoint definition piece");

  3135.   if (!cur_tpoint)
  3136.     {
  3137.       /* This case would normally never occur, but be prepared for
  3138.          GDB misbehavior.  */
  3139.       strcpy (packet, "l");
  3140.     }
  3141.   else if (cur_action < cur_tpoint->numactions)
  3142.     {
  3143.       response_action (packet, cur_tpoint,
  3144.                        cur_tpoint->actions_str[cur_action], 0);
  3145.       ++cur_action;
  3146.     }
  3147.   else if (cur_step_action < cur_tpoint->num_step_actions)
  3148.     {
  3149.       response_action (packet, cur_tpoint,
  3150.                        cur_tpoint->step_actions_str[cur_step_action], 1);
  3151.       ++cur_step_action;
  3152.     }
  3153.   else if ((cur_source_string
  3154.             ? cur_source_string->next
  3155.             : cur_tpoint->source_strings))
  3156.     {
  3157.       if (cur_source_string)
  3158.         cur_source_string = cur_source_string->next;
  3159.       else
  3160.         cur_source_string = cur_tpoint->source_strings;
  3161.       response_source (packet, cur_tpoint, cur_source_string);
  3162.     }
  3163.   else
  3164.     {
  3165.       cur_tpoint = cur_tpoint->next;
  3166.       cur_action = cur_step_action = 0;
  3167.       cur_source_string = NULL;
  3168.       if (cur_tpoint)
  3169.         response_tracepoint (packet, cur_tpoint);
  3170.       else
  3171.         strcpy (packet, "l");
  3172.     }
  3173. }

  3174. /* Compose a response that is an imitation of the syntax by which the
  3175.    trace state variable was originally downloaded.  */

  3176. static void
  3177. response_tsv (char *packet, struct trace_state_variable *tsv)
  3178. {
  3179.   char *buf = (char *) "";
  3180.   int namelen;

  3181.   if (tsv->name)
  3182.     {
  3183.       namelen = strlen (tsv->name);
  3184.       buf = alloca (namelen * 2 + 1);
  3185.       bin2hex ((gdb_byte *) tsv->name, buf, namelen);
  3186.     }

  3187.   sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
  3188.            tsv->getter ? 1 : 0, buf);
  3189. }

  3190. /* Return the first trace state variable definition, and initialize
  3191.    the state machine that will iterate through all the tsv bits.  */

  3192. static void
  3193. cmd_qtfv (char *packet)
  3194. {
  3195.   trace_debug ("Returning first trace state variable definition");

  3196.   cur_tsv = trace_state_variables;

  3197.   if (cur_tsv)
  3198.     response_tsv (packet, cur_tsv);
  3199.   else
  3200.     strcpy (packet, "l");
  3201. }

  3202. /* Return additional trace state variable definitions. */

  3203. static void
  3204. cmd_qtsv (char *packet)
  3205. {
  3206.   trace_debug ("Returning additional trace state variable definition");

  3207.   if (cur_tsv)
  3208.     {
  3209.       cur_tsv = cur_tsv->next;
  3210.       if (cur_tsv)
  3211.         response_tsv (packet, cur_tsv);
  3212.       else
  3213.         strcpy (packet, "l");
  3214.     }
  3215.   else
  3216.     strcpy (packet, "l");
  3217. }

  3218. /* Return the first static tracepoint marker, and initialize the state
  3219.    machine that will iterate through all the static tracepoints
  3220.    markers.  */

  3221. static void
  3222. cmd_qtfstm (char *packet)
  3223. {
  3224.   if (!maybe_write_ipa_ust_not_loaded (packet))
  3225.     run_inferior_command (packet, strlen (packet) + 1);
  3226. }

  3227. /* Return additional static tracepoints markers.  */

  3228. static void
  3229. cmd_qtsstm (char *packet)
  3230. {
  3231.   if (!maybe_write_ipa_ust_not_loaded (packet))
  3232.     run_inferior_command (packet, strlen (packet) + 1);
  3233. }

  3234. /* Return the definition of the static tracepoint at a given address.
  3235.    Result packet is the same as qTsST's.  */

  3236. static void
  3237. cmd_qtstmat (char *packet)
  3238. {
  3239.   if (!maybe_write_ipa_ust_not_loaded (packet))
  3240.     run_inferior_command (packet, strlen (packet) + 1);
  3241. }

  3242. /* Helper for gdb_agent_about_to_close.
  3243.    Return non-zero if thread ENTRY is in the same process in DATA.  */

  3244. static int
  3245. same_process_p (struct inferior_list_entry *entry, void *data)
  3246. {
  3247.   int *pid = data;

  3248.   return ptid_get_pid (entry->id) == *pid;
  3249. }

  3250. /* Sent the agent a command to close it.  */

  3251. void
  3252. gdb_agent_about_to_close (int pid)
  3253. {
  3254.   char buf[IPA_CMD_BUF_SIZE];

  3255.   if (!maybe_write_ipa_not_loaded (buf))
  3256.     {
  3257.       struct thread_info *saved_thread;

  3258.       saved_thread = current_thread;

  3259.       /* Find any thread which belongs to process PID.  */
  3260.       current_thread = (struct thread_info *)
  3261.         find_inferior (&all_threads, same_process_p, &pid);

  3262.       strcpy (buf, "close");

  3263.       run_inferior_command (buf, strlen (buf) + 1);

  3264.       current_thread = saved_thread;
  3265.     }
  3266. }

  3267. /* Return the minimum instruction size needed for fast tracepoints as a
  3268.    hexadecimal number.  */

  3269. static void
  3270. cmd_qtminftpilen (char *packet)
  3271. {
  3272.   if (current_thread == NULL)
  3273.     {
  3274.       /* Indicate that the minimum length is currently unknown.  */
  3275.       strcpy (packet, "0");
  3276.       return;
  3277.     }

  3278.   sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
  3279. }

  3280. /* Respond to qTBuffer packet with a block of raw data from the trace
  3281.    buffer.  GDB may ask for a lot, but we are allowed to reply with
  3282.    only as much as will fit within packet limits or whatever.  */

  3283. static void
  3284. cmd_qtbuffer (char *own_buf)
  3285. {
  3286.   ULONGEST offset, num, tot;
  3287.   unsigned char *tbp;
  3288.   char *packet = own_buf;

  3289.   packet += strlen ("qTBuffer:");

  3290.   packet = unpack_varlen_hex (packet, &offset);
  3291.   ++packet; /* skip a comma */
  3292.   unpack_varlen_hex (packet, &num);

  3293.   trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
  3294.                (int) num, phex_nz (offset, 0));

  3295.   tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();

  3296.   /* If we're right at the end, reply specially that we're done.  */
  3297.   if (offset == tot)
  3298.     {
  3299.       strcpy (own_buf, "l");
  3300.       return;
  3301.     }

  3302.   /* Object to any other out-of-bounds request.  */
  3303.   if (offset > tot)
  3304.     {
  3305.       write_enn (own_buf);
  3306.       return;
  3307.     }

  3308.   /* Compute the pointer corresponding to the given offset, accounting
  3309.      for wraparound.  */
  3310.   tbp = trace_buffer_start + offset;
  3311.   if (tbp >= trace_buffer_wrap)
  3312.     tbp -= (trace_buffer_wrap - trace_buffer_lo);

  3313.   /* Trim to the remaining bytes if we're close to the end.  */
  3314.   if (num > tot - offset)
  3315.     num = tot - offset;

  3316.   /* Trim to available packet size.  */
  3317.   if (num >= (PBUFSIZ - 16) / 2 )
  3318.     num = (PBUFSIZ - 16) / 2;

  3319.   bin2hex (tbp, own_buf, num);
  3320. }

  3321. static void
  3322. cmd_bigqtbuffer_circular (char *own_buf)
  3323. {
  3324.   ULONGEST val;
  3325.   char *packet = own_buf;

  3326.   packet += strlen ("QTBuffer:circular:");

  3327.   unpack_varlen_hex (packet, &val);
  3328.   circular_trace_buffer = val;
  3329.   trace_debug ("Trace buffer is now %s",
  3330.                circular_trace_buffer ? "circular" : "linear");
  3331.   write_ok (own_buf);
  3332. }

  3333. static void
  3334. cmd_bigqtbuffer_size (char *own_buf)
  3335. {
  3336.   ULONGEST val;
  3337.   LONGEST sval;
  3338.   char *packet = own_buf;

  3339.   /* Can't change the size during a tracing run.  */
  3340.   if (tracing)
  3341.     {
  3342.       write_enn (own_buf);
  3343.       return;
  3344.     }

  3345.   packet += strlen ("QTBuffer:size:");

  3346.   /* -1 is sent as literal "-1".  */
  3347.   if (strcmp (packet, "-1") == 0)
  3348.     sval = DEFAULT_TRACE_BUFFER_SIZE;
  3349.   else
  3350.     {
  3351.       unpack_varlen_hex (packet, &val);
  3352.       sval = (LONGEST) val;
  3353.     }

  3354.   init_trace_buffer (sval);
  3355.   trace_debug ("Trace buffer is now %s bytes",
  3356.                plongest (trace_buffer_size));
  3357.   write_ok (own_buf);
  3358. }

  3359. static void
  3360. cmd_qtnotes (char *own_buf)
  3361. {
  3362.   size_t nbytes;
  3363.   char *saved, *user, *notes, *stopnote;
  3364.   char *packet = own_buf;

  3365.   packet += strlen ("QTNotes:");

  3366.   while (*packet)
  3367.     {
  3368.       if (strncmp ("user:", packet, strlen ("user:")) == 0)
  3369.         {
  3370.           packet += strlen ("user:");
  3371.           saved = packet;
  3372.           packet = strchr (packet, ';');
  3373.           nbytes = (packet - saved) / 2;
  3374.           user = xmalloc (nbytes + 1);
  3375.           nbytes = hex2bin (saved, (gdb_byte *) user, nbytes);
  3376.           user[nbytes] = '\0';
  3377.           ++packet; /* skip the semicolon */
  3378.           trace_debug ("User is '%s'", user);
  3379.           xfree (tracing_user_name);
  3380.           tracing_user_name = user;
  3381.         }
  3382.       else if (strncmp ("notes:", packet, strlen ("notes:")) == 0)
  3383.         {
  3384.           packet += strlen ("notes:");
  3385.           saved = packet;
  3386.           packet = strchr (packet, ';');
  3387.           nbytes = (packet - saved) / 2;
  3388.           notes = xmalloc (nbytes + 1);
  3389.           nbytes = hex2bin (saved, (gdb_byte *) notes, nbytes);
  3390.           notes[nbytes] = '\0';
  3391.           ++packet; /* skip the semicolon */
  3392.           trace_debug ("Notes is '%s'", notes);
  3393.           xfree (tracing_notes);
  3394.           tracing_notes = notes;
  3395.         }
  3396.       else if (strncmp ("tstop:", packet, strlen ("tstop:")) == 0)
  3397.         {
  3398.           packet += strlen ("tstop:");
  3399.           saved = packet;
  3400.           packet = strchr (packet, ';');
  3401.           nbytes = (packet - saved) / 2;
  3402.           stopnote = xmalloc (nbytes + 1);
  3403.           nbytes = hex2bin (saved, (gdb_byte *) stopnote, nbytes);
  3404.           stopnote[nbytes] = '\0';
  3405.           ++packet; /* skip the semicolon */
  3406.           trace_debug ("tstop note is '%s'", stopnote);
  3407.           xfree (tracing_stop_note);
  3408.           tracing_stop_note = stopnote;
  3409.         }
  3410.       else
  3411.         break;
  3412.     }

  3413.   write_ok (own_buf);
  3414. }

  3415. int
  3416. handle_tracepoint_general_set (char *packet)
  3417. {
  3418.   if (strcmp ("QTinit", packet) == 0)
  3419.     {
  3420.       cmd_qtinit (packet);
  3421.       return 1;
  3422.     }
  3423.   else if (strncmp ("QTDP:", packet, strlen ("QTDP:")) == 0)
  3424.     {
  3425.       cmd_qtdp (packet);
  3426.       return 1;
  3427.     }
  3428.   else if (strncmp ("QTDPsrc:", packet, strlen ("QTDPsrc:")) == 0)
  3429.     {
  3430.       cmd_qtdpsrc (packet);
  3431.       return 1;
  3432.     }
  3433.   else if (strncmp ("QTEnable:", packet, strlen ("QTEnable:")) == 0)
  3434.     {
  3435.       cmd_qtenable_disable (packet, 1);
  3436.       return 1;
  3437.     }
  3438.   else if (strncmp ("QTDisable:", packet, strlen ("QTDisable:")) == 0)
  3439.     {
  3440.       cmd_qtenable_disable (packet, 0);
  3441.       return 1;
  3442.     }
  3443.   else if (strncmp ("QTDV:", packet, strlen ("QTDV:")) == 0)
  3444.     {
  3445.       cmd_qtdv (packet);
  3446.       return 1;
  3447.     }
  3448.   else if (strncmp ("QTro:", packet, strlen ("QTro:")) == 0)
  3449.     {
  3450.       cmd_qtro (packet);
  3451.       return 1;
  3452.     }
  3453.   else if (strcmp ("QTStart", packet) == 0)
  3454.     {
  3455.       cmd_qtstart (packet);
  3456.       return 1;
  3457.     }
  3458.   else if (strcmp ("QTStop", packet) == 0)
  3459.     {
  3460.       cmd_qtstop (packet);
  3461.       return 1;
  3462.     }
  3463.   else if (strncmp ("QTDisconnected:", packet,
  3464.                     strlen ("QTDisconnected:")) == 0)
  3465.     {
  3466.       cmd_qtdisconnected (packet);
  3467.       return 1;
  3468.     }
  3469.   else if (strncmp ("QTFrame:", packet, strlen ("QTFrame:")) == 0)
  3470.     {
  3471.       cmd_qtframe (packet);
  3472.       return 1;
  3473.     }
  3474.   else if (strncmp ("QTBuffer:circular:", packet, strlen ("QTBuffer:circular:")) == 0)
  3475.     {
  3476.       cmd_bigqtbuffer_circular (packet);
  3477.       return 1;
  3478.     }
  3479.   else if (strncmp ("QTBuffer:size:", packet, strlen ("QTBuffer:size:")) == 0)
  3480.     {
  3481.       cmd_bigqtbuffer_size (packet);
  3482.       return 1;
  3483.     }
  3484.   else if (strncmp ("QTNotes:", packet, strlen ("QTNotes:")) == 0)
  3485.     {
  3486.       cmd_qtnotes (packet);
  3487.       return 1;
  3488.     }

  3489.   return 0;
  3490. }

  3491. int
  3492. handle_tracepoint_query (char *packet)
  3493. {
  3494.   if (strcmp ("qTStatus", packet) == 0)
  3495.     {
  3496.       cmd_qtstatus (packet);
  3497.       return 1;
  3498.     }
  3499.   else if (strncmp ("qTP:", packet, strlen ("qTP:")) == 0)
  3500.     {
  3501.       cmd_qtp (packet);
  3502.       return 1;
  3503.     }
  3504.   else if (strcmp ("qTfP", packet) == 0)
  3505.     {
  3506.       cmd_qtfp (packet);
  3507.       return 1;
  3508.     }
  3509.   else if (strcmp ("qTsP", packet) == 0)
  3510.     {
  3511.       cmd_qtsp (packet);
  3512.       return 1;
  3513.     }
  3514.   else if (strcmp ("qTfV", packet) == 0)
  3515.     {
  3516.       cmd_qtfv (packet);
  3517.       return 1;
  3518.     }
  3519.   else if (strcmp ("qTsV", packet) == 0)
  3520.     {
  3521.       cmd_qtsv (packet);
  3522.       return 1;
  3523.     }
  3524.   else if (strncmp ("qTV:", packet, strlen ("qTV:")) == 0)
  3525.     {
  3526.       cmd_qtv (packet);
  3527.       return 1;
  3528.     }
  3529.   else if (strncmp ("qTBuffer:", packet, strlen ("qTBuffer:")) == 0)
  3530.     {
  3531.       cmd_qtbuffer (packet);
  3532.       return 1;
  3533.     }
  3534.   else if (strcmp ("qTfSTM", packet) == 0)
  3535.     {
  3536.       cmd_qtfstm (packet);
  3537.       return 1;
  3538.     }
  3539.   else if (strcmp ("qTsSTM", packet) == 0)
  3540.     {
  3541.       cmd_qtsstm (packet);
  3542.       return 1;
  3543.     }
  3544.   else if (strncmp ("qTSTMat:", packet, strlen ("qTSTMat:")) == 0)
  3545.     {
  3546.       cmd_qtstmat (packet);
  3547.       return 1;
  3548.     }
  3549.   else if (strcmp ("qTMinFTPILen", packet) == 0)
  3550.     {
  3551.       cmd_qtminftpilen (packet);
  3552.       return 1;
  3553.     }

  3554.   return 0;
  3555. }

  3556. #endif
  3557. #ifndef IN_PROCESS_AGENT

  3558. /* Call this when thread TINFO has hit the tracepoint defined by
  3559.    TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
  3560.    action.  This adds a while-stepping collecting state item to the
  3561.    threads' collecting state list, so that we can keep track of
  3562.    multiple simultaneous while-stepping actions being collected by the
  3563.    same thread.  This can happen in cases like:

  3564.     ff0001  INSN1 <-- TP1, while-stepping 10 collect $regs
  3565.     ff0002  INSN2
  3566.     ff0003  INSN3 <-- TP2, collect $regs
  3567.     ff0004  INSN4 <-- TP3, while-stepping 10 collect $regs
  3568.     ff0005  INSN5

  3569.    Notice that when instruction INSN5 is reached, the while-stepping
  3570.    actions of both TP1 and TP3 are still being collected, and that TP2
  3571.    had been collected meanwhile.  The whole range of ff0001-ff0005
  3572.    should be single-stepped, due to at least TP1's while-stepping
  3573.    action covering the whole range.  */

  3574. static void
  3575. add_while_stepping_state (struct thread_info *tinfo,
  3576.                           int tp_number, CORE_ADDR tp_address)
  3577. {
  3578.   struct wstep_state *wstep;

  3579.   wstep = xmalloc (sizeof (*wstep));
  3580.   wstep->next = tinfo->while_stepping;

  3581.   wstep->tp_number = tp_number;
  3582.   wstep->tp_address = tp_address;
  3583.   wstep->current_step = 0;

  3584.   tinfo->while_stepping = wstep;
  3585. }

  3586. /* Release the while-stepping collecting state WSTEP.  */

  3587. static void
  3588. release_while_stepping_state (struct wstep_state *wstep)
  3589. {
  3590.   free (wstep);
  3591. }

  3592. /* Release all while-stepping collecting states currently associated
  3593.    with thread TINFO.  */

  3594. void
  3595. release_while_stepping_state_list (struct thread_info *tinfo)
  3596. {
  3597.   struct wstep_state *head;

  3598.   while (tinfo->while_stepping)
  3599.     {
  3600.       head = tinfo->while_stepping;
  3601.       tinfo->while_stepping = head->next;
  3602.       release_while_stepping_state (head);
  3603.     }
  3604. }

  3605. /* If TINFO was handling a 'while-stepping' action, the step has
  3606.    finished, so collect any step data needed, and check if any more
  3607.    steps are required.  Return true if the thread was indeed
  3608.    collecting tracepoint data, false otherwise.  */

  3609. int
  3610. tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
  3611. {
  3612.   struct tracepoint *tpoint;
  3613.   struct wstep_state *wstep;
  3614.   struct wstep_state **wstep_link;
  3615.   struct trap_tracepoint_ctx ctx;

  3616.   /* Pull in fast tracepoint trace frames from the inferior lib buffer into
  3617.      our buffer.  */
  3618.   if (agent_loaded_p ())
  3619.     upload_fast_traceframes ();

  3620.   /* Check if we were indeed collecting data for one of more
  3621.      tracepoints with a 'while-stepping' count.  */
  3622.   if (tinfo->while_stepping == NULL)
  3623.     return 0;

  3624.   if (!tracing)
  3625.     {
  3626.       /* We're not even tracing anymore.  Stop this thread from
  3627.          collecting.  */
  3628.       release_while_stepping_state_list (tinfo);

  3629.       /* The thread had stopped due to a single-step request indeed
  3630.          explained by a tracepoint.  */
  3631.       return 1;
  3632.     }

  3633.   wstep = tinfo->while_stepping;
  3634.   wstep_link = &tinfo->while_stepping;

  3635.   trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
  3636.                target_pid_to_str (tinfo->entry.id),
  3637.                wstep->tp_number, paddress (wstep->tp_address));

  3638.   ctx.base.type = trap_tracepoint;
  3639.   ctx.regcache = get_thread_regcache (tinfo, 1);

  3640.   while (wstep != NULL)
  3641.     {
  3642.       tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
  3643.       if (tpoint == NULL)
  3644.         {
  3645.           trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
  3646.                        wstep->tp_number, paddress (wstep->tp_address),
  3647.                        target_pid_to_str (tinfo->entry.id));

  3648.           /* Unlink.  */
  3649.           *wstep_link = wstep->next;
  3650.           release_while_stepping_state (wstep);
  3651.           wstep = *wstep_link;
  3652.           continue;
  3653.         }

  3654.       /* We've just finished one step.  */
  3655.       ++wstep->current_step;

  3656.       /* Collect data.  */
  3657.       collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
  3658.                             stop_pc, tpoint, wstep->current_step);

  3659.       if (wstep->current_step >= tpoint->step_count)
  3660.         {
  3661.           /* The requested numbers of steps have occurred.  */
  3662.           trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
  3663.                        target_pid_to_str (tinfo->entry.id),
  3664.                        wstep->tp_number, paddress (wstep->tp_address));

  3665.           /* Unlink the wstep.  */
  3666.           *wstep_link = wstep->next;
  3667.           release_while_stepping_state (wstep);
  3668.           wstep = *wstep_link;

  3669.           /* Only check the hit count now, which ensure that we do all
  3670.              our stepping before stopping the run.  */
  3671.           if (tpoint->pass_count > 0
  3672.               && tpoint->hit_count >= tpoint->pass_count
  3673.               && stopping_tracepoint == NULL)
  3674.             stopping_tracepoint = tpoint;
  3675.         }
  3676.       else
  3677.         {
  3678.           /* Keep single-stepping until the requested numbers of steps
  3679.              have occurred.  */
  3680.           wstep_link = &wstep->next;
  3681.           wstep = *wstep_link;
  3682.         }

  3683.       if (stopping_tracepoint
  3684.           || trace_buffer_is_full
  3685.           || expr_eval_result != expr_eval_no_error)
  3686.         {
  3687.           stop_tracing ();
  3688.           break;
  3689.         }
  3690.     }

  3691.   return 1;
  3692. }

  3693. /* Handle any internal tracing control breakpoint hits.  That means,
  3694.    pull traceframes from the IPA to our buffer, and syncing both
  3695.    tracing agents when the IPA's tracing stops for some reason.  */

  3696. int
  3697. handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
  3698. {
  3699.   /* Pull in fast tracepoint trace frames from the inferior in-process
  3700.      agent's buffer into our buffer.  */

  3701.   if (!agent_loaded_p ())
  3702.     return 0;

  3703.   upload_fast_traceframes ();

  3704.   /* Check if the in-process agent had decided we should stop
  3705.      tracing.  */
  3706.   if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
  3707.     {
  3708.       int ipa_trace_buffer_is_full;
  3709.       CORE_ADDR ipa_stopping_tracepoint;
  3710.       int ipa_expr_eval_result;
  3711.       CORE_ADDR ipa_error_tracepoint;

  3712.       trace_debug ("lib stopped at stop_tracing");

  3713.       read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
  3714.                              &ipa_trace_buffer_is_full);

  3715.       read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
  3716.                                   &ipa_stopping_tracepoint);
  3717.       write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);

  3718.       read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
  3719.                                   &ipa_error_tracepoint);
  3720.       write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);

  3721.       read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
  3722.                              &ipa_expr_eval_result);
  3723.       write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);

  3724.       trace_debug ("lib: trace_buffer_is_full: %d, "
  3725.                    "stopping_tracepoint: %s, "
  3726.                    "ipa_expr_eval_result: %d, "
  3727.                    "error_tracepoint: %s, ",
  3728.                    ipa_trace_buffer_is_full,
  3729.                    paddress (ipa_stopping_tracepoint),
  3730.                    ipa_expr_eval_result,
  3731.                    paddress (ipa_error_tracepoint));

  3732.       if (debug_threads)
  3733.         {
  3734.           if (ipa_trace_buffer_is_full)
  3735.             trace_debug ("lib stopped due to full buffer.");
  3736.           if (ipa_stopping_tracepoint)
  3737.             trace_debug ("lib stopped due to tpoint");
  3738.           if (ipa_stopping_tracepoint)
  3739.             trace_debug ("lib stopped due to error");
  3740.         }

  3741.       if (ipa_stopping_tracepoint != 0)
  3742.         {
  3743.           stopping_tracepoint
  3744.             = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
  3745.         }
  3746.       else if (ipa_expr_eval_result != expr_eval_no_error)
  3747.         {
  3748.           expr_eval_result = ipa_expr_eval_result;
  3749.           error_tracepoint
  3750.             = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
  3751.         }
  3752.       stop_tracing ();
  3753.       return 1;
  3754.     }
  3755.   else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
  3756.     {
  3757.       trace_debug ("lib stopped at flush_trace_buffer");
  3758.       return 1;
  3759.     }

  3760.   return 0;
  3761. }

  3762. /* Return true if TINFO just hit a tracepoint.  Collect data if
  3763.    so.  */

  3764. int
  3765. tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
  3766. {
  3767.   struct tracepoint *tpoint;
  3768.   int ret = 0;
  3769.   struct trap_tracepoint_ctx ctx;

  3770.   /* Not tracing, don't handle.  */
  3771.   if (!tracing)
  3772.     return 0;

  3773.   ctx.base.type = trap_tracepoint;
  3774.   ctx.regcache = get_thread_regcache (tinfo, 1);

  3775.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  3776.     {
  3777.       /* Note that we collect fast tracepoints here as well.  We'll
  3778.          step over the fast tracepoint jump later, which avoids the
  3779.          double collect.  However, we don't collect for static
  3780.          tracepoints here, because UST markers are compiled in program,
  3781.          and probes will be executed in program.  So static tracepoints
  3782.          are collected there.   */
  3783.       if (tpoint->enabled && stop_pc == tpoint->address
  3784.           && tpoint->type != static_tracepoint)
  3785.         {
  3786.           trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
  3787.                        target_pid_to_str (tinfo->entry.id),
  3788.                        tpoint->number, paddress (tpoint->address));

  3789.           /* Test the condition if present, and collect if true.  */
  3790.           if (!tpoint->cond
  3791.               || (condition_true_at_tracepoint
  3792.                   ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
  3793.             collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
  3794.                                         stop_pc, tpoint);

  3795.           if (stopping_tracepoint
  3796.               || trace_buffer_is_full
  3797.               || expr_eval_result != expr_eval_no_error)
  3798.             {
  3799.               stop_tracing ();
  3800.             }
  3801.           /* If the tracepoint had a 'while-stepping' action, then set
  3802.              the thread to collect this tracepoint on the following
  3803.              single-steps.  */
  3804.           else if (tpoint->step_count > 0)
  3805.             {
  3806.               add_while_stepping_state (tinfo,
  3807.                                         tpoint->number, tpoint->address);
  3808.             }

  3809.           ret = 1;
  3810.         }
  3811.     }

  3812.   return ret;
  3813. }

  3814. #endif

  3815. #if defined IN_PROCESS_AGENT && defined HAVE_UST
  3816. struct ust_marker_data;
  3817. static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  3818.                                             struct traceframe *tframe);
  3819. #endif

  3820. /* Create a trace frame for the hit of the given tracepoint in the
  3821.    given thread.  */

  3822. static void
  3823. collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
  3824.                             struct tracepoint *tpoint)
  3825. {
  3826.   struct traceframe *tframe;
  3827.   int acti;

  3828.   /* Only count it as a hit when we actually collect data.  */
  3829.   tpoint->hit_count++;

  3830.   /* If we've exceeded a defined pass count, record the event for
  3831.      later, and finish the collection for this hit.  This test is only
  3832.      for nonstepping tracepoints, stepping tracepoints test at the end
  3833.      of their while-stepping loop.  */
  3834.   if (tpoint->pass_count > 0
  3835.       && tpoint->hit_count >= tpoint->pass_count
  3836.       && tpoint->step_count == 0
  3837.       && stopping_tracepoint == NULL)
  3838.     stopping_tracepoint = tpoint;

  3839.   trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
  3840.                tpoint->number, paddress (tpoint->address), tpoint->hit_count);

  3841.   tframe = add_traceframe (tpoint);

  3842.   if (tframe)
  3843.     {
  3844.       for (acti = 0; acti < tpoint->numactions; ++acti)
  3845.         {
  3846. #ifndef IN_PROCESS_AGENT
  3847.           trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
  3848.                        tpoint->number, paddress (tpoint->address),
  3849.                        tpoint->actions_str[acti]);
  3850. #endif

  3851.           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
  3852.                                    tpoint->actions[acti]);
  3853.         }

  3854.       finish_traceframe (tframe);
  3855.     }

  3856.   if (tframe == NULL && tracing)
  3857.     trace_buffer_is_full = 1;
  3858. }

  3859. #ifndef IN_PROCESS_AGENT

  3860. static void
  3861. collect_data_at_step (struct tracepoint_hit_ctx *ctx,
  3862.                       CORE_ADDR stop_pc,
  3863.                       struct tracepoint *tpoint, int current_step)
  3864. {
  3865.   struct traceframe *tframe;
  3866.   int acti;

  3867.   trace_debug ("Making new step traceframe for "
  3868.                "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
  3869.                tpoint->number, paddress (tpoint->address),
  3870.                current_step, tpoint->step_count,
  3871.                tpoint->hit_count);

  3872.   tframe = add_traceframe (tpoint);

  3873.   if (tframe)
  3874.     {
  3875.       for (acti = 0; acti < tpoint->num_step_actions; ++acti)
  3876.         {
  3877.           trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
  3878.                        tpoint->number, paddress (tpoint->address),
  3879.                        tpoint->step_actions_str[acti]);

  3880.           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
  3881.                                    tpoint->step_actions[acti]);
  3882.         }

  3883.       finish_traceframe (tframe);
  3884.     }

  3885.   if (tframe == NULL && tracing)
  3886.     trace_buffer_is_full = 1;
  3887. }

  3888. #endif

  3889. #ifdef IN_PROCESS_AGENT
  3890. /* The target description used by the IPA.  Given that the IPA library
  3891.    is built for a specific architecture that is loaded into the
  3892.    inferior, there only needs to be one such description per
  3893.    build.  */
  3894. const struct target_desc *ipa_tdesc;
  3895. #endif

  3896. static struct regcache *
  3897. get_context_regcache (struct tracepoint_hit_ctx *ctx)
  3898. {
  3899.   struct regcache *regcache = NULL;

  3900. #ifdef IN_PROCESS_AGENT
  3901.   if (ctx->type == fast_tracepoint)
  3902.     {
  3903.       struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
  3904.       if (!fctx->regcache_initted)
  3905.         {
  3906.           fctx->regcache_initted = 1;
  3907.           init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
  3908.           supply_regblock (&fctx->regcache, NULL);
  3909.           supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
  3910.         }
  3911.       regcache = &fctx->regcache;
  3912.     }
  3913. #ifdef HAVE_UST
  3914.   if (ctx->type == static_tracepoint)
  3915.     {
  3916.       struct static_tracepoint_ctx *sctx
  3917.         = (struct static_tracepoint_ctx *) ctx;

  3918.       if (!sctx->regcache_initted)
  3919.         {
  3920.           sctx->regcache_initted = 1;
  3921.           init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
  3922.           supply_regblock (&sctx->regcache, NULL);
  3923.           /* Pass down the tracepoint address, because REGS doesn't
  3924.              include the PC, but we know what it must have been.  */
  3925.           supply_static_tracepoint_registers (&sctx->regcache,
  3926.                                               (const unsigned char *)
  3927.                                               sctx->regs,
  3928.                                               sctx->tpoint->address);
  3929.         }
  3930.       regcache = &sctx->regcache;
  3931.     }
  3932. #endif
  3933. #else
  3934.   if (ctx->type == trap_tracepoint)
  3935.     {
  3936.       struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
  3937.       regcache = tctx->regcache;
  3938.     }
  3939. #endif

  3940.   gdb_assert (regcache != NULL);

  3941.   return regcache;
  3942. }

  3943. static void
  3944. do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  3945.                          CORE_ADDR stop_pc,
  3946.                          struct tracepoint *tpoint,
  3947.                          struct traceframe *tframe,
  3948.                          struct tracepoint_action *taction)
  3949. {
  3950.   enum eval_result_type err;

  3951.   switch (taction->type)
  3952.     {
  3953.     case 'M':
  3954.       {
  3955.         struct collect_memory_action *maction;
  3956.         struct eval_agent_expr_context ax_ctx;

  3957.         maction = (struct collect_memory_action *) taction;
  3958.         ax_ctx.regcache = NULL;
  3959.         ax_ctx.tframe = tframe;
  3960.         ax_ctx.tpoint = tpoint;

  3961.         trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
  3962.                      pulongest (maction->len),
  3963.                      paddress (maction->addr), maction->basereg);
  3964.         /* (should use basereg) */
  3965.         agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
  3966.                         maction->len);
  3967.         break;
  3968.       }
  3969.     case 'R':
  3970.       {
  3971.         unsigned char *regspace;
  3972.         struct regcache tregcache;
  3973.         struct regcache *context_regcache;
  3974.         int regcache_size;

  3975.         trace_debug ("Want to collect registers");

  3976.         context_regcache = get_context_regcache (ctx);
  3977.         regcache_size = register_cache_size (context_regcache->tdesc);

  3978.         /* Collect all registers for now.  */
  3979.         regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
  3980.         if (regspace == NULL)
  3981.           {
  3982.             trace_debug ("Trace buffer block allocation failed, skipping");
  3983.             break;
  3984.           }
  3985.         /* Identify a register block.  */
  3986.         *regspace = 'R';

  3987.         /* Wrap the regblock in a register cache (in the stack, we
  3988.            don't want to malloc here).  */
  3989.         init_register_cache (&tregcache, context_regcache->tdesc,
  3990.                              regspace + 1);

  3991.         /* Copy the register data to the regblock.  */
  3992.         regcache_cpy (&tregcache, context_regcache);

  3993. #ifndef IN_PROCESS_AGENT
  3994.         /* On some platforms, trap-based tracepoints will have the PC
  3995.            pointing to the next instruction after the trap, but we
  3996.            don't want the user or GDB trying to guess whether the
  3997.            saved PC needs adjusting; so always record the adjusted
  3998.            stop_pc.  Note that we can't use tpoint->address instead,
  3999.            since it will be wrong for while-stepping actions.  This
  4000.            adjustment is a nop for fast tracepoints collected from the
  4001.            in-process lib (but not if GDBserver is collecting one
  4002.            preemptively), since the PC had already been adjusted to
  4003.            contain the tracepoint's address by the jump pad.  */
  4004.         trace_debug ("Storing stop pc (0x%s) in regblock",
  4005.                      paddress (stop_pc));

  4006.         /* This changes the regblock, not the thread's
  4007.            regcache.  */
  4008.         regcache_write_pc (&tregcache, stop_pc);
  4009. #endif
  4010.       }
  4011.       break;
  4012.     case 'X':
  4013.       {
  4014.         struct eval_expr_action *eaction;
  4015.         struct eval_agent_expr_context ax_ctx;

  4016.         eaction = (struct eval_expr_action *) taction;
  4017.         ax_ctx.regcache = get_context_regcache (ctx);
  4018.         ax_ctx.tframe = tframe;
  4019.         ax_ctx.tpoint = tpoint;

  4020.         trace_debug ("Want to evaluate expression");

  4021.         err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);

  4022.         if (err != expr_eval_no_error)
  4023.           {
  4024.             record_tracepoint_error (tpoint, "action expression", err);
  4025.             return;
  4026.           }
  4027.       }
  4028.       break;
  4029.     case 'L':
  4030.       {
  4031. #if defined IN_PROCESS_AGENT && defined HAVE_UST
  4032.         trace_debug ("Want to collect static trace data");
  4033.         collect_ust_data_at_tracepoint (ctx, tframe);
  4034. #else
  4035.         trace_debug ("warning: collecting static trace data, "
  4036.                      "but static tracepoints are not supported");
  4037. #endif
  4038.       }
  4039.       break;
  4040.     default:
  4041.       trace_debug ("unknown trace action '%c', ignoring", taction->type);
  4042.       break;
  4043.     }
  4044. }

  4045. static int
  4046. condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  4047.                               struct tracepoint *tpoint)
  4048. {
  4049.   ULONGEST value = 0;
  4050.   enum eval_result_type err;

  4051.   /* Presently, gdbserver doesn't run compiled conditions, only the
  4052.      IPA does.  If the program stops at a fast tracepoint's address
  4053.      (e.g., due to a breakpoint, trap tracepoint, or stepping),
  4054.      gdbserver preemptively collect the fast tracepoint.  Later, on
  4055.      resume, gdbserver steps over the fast tracepoint like it steps
  4056.      over breakpoints, so that the IPA doesn't see that fast
  4057.      tracepoint.  This avoids double collects of fast tracepoints in
  4058.      that stopping scenario.  Having gdbserver itself handle the fast
  4059.      tracepoint gives the user a consistent view of when fast or trap
  4060.      tracepoints are collected, compared to an alternative where only
  4061.      trap tracepoints are collected on stop, and fast tracepoints on
  4062.      resume.  When a fast tracepoint is being processed by gdbserver,
  4063.      it is always the non-compiled condition expression that is
  4064.      used.  */
  4065. #ifdef IN_PROCESS_AGENT
  4066.   if (tpoint->compiled_cond)
  4067.     err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (ctx, &value);
  4068.   else
  4069. #endif
  4070.     {
  4071.       struct eval_agent_expr_context ax_ctx;

  4072.       ax_ctx.regcache = get_context_regcache (ctx);
  4073.       ax_ctx.tframe = NULL;
  4074.       ax_ctx.tpoint = tpoint;

  4075.       err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
  4076.     }
  4077.   if (err != expr_eval_no_error)
  4078.     {
  4079.       record_tracepoint_error (tpoint, "condition", err);
  4080.       /* The error case must return false.  */
  4081.       return 0;
  4082.     }

  4083.   trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
  4084.                tpoint->number, paddress (tpoint->address),
  4085.                pulongest (value));
  4086.   return (value ? 1 : 0);
  4087. }

  4088. /* Do memory copies for bytecodes.  */
  4089. /* Do the recording of memory blocks for actions and bytecodes.  */

  4090. int
  4091. agent_mem_read (struct eval_agent_expr_context *ctx,
  4092.                 unsigned char *to, CORE_ADDR from, ULONGEST len)
  4093. {
  4094.   unsigned char *mspace;
  4095.   ULONGEST remaining = len;
  4096.   unsigned short blocklen;

  4097.   /* If a 'to' buffer is specified, use it.  */
  4098.   if (to != NULL)
  4099.     {
  4100.       read_inferior_memory (from, to, len);
  4101.       return 0;
  4102.     }

  4103.   /* Otherwise, create a new memory block in the trace buffer.  */
  4104.   while (remaining > 0)
  4105.     {
  4106.       size_t sp;

  4107.       blocklen = (remaining > 65535 ? 65535 : remaining);
  4108.       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
  4109.       mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
  4110.       if (mspace == NULL)
  4111.         return 1;
  4112.       /* Identify block as a memory block.  */
  4113.       *mspace = 'M';
  4114.       ++mspace;
  4115.       /* Record address and size.  */
  4116.       memcpy (mspace, &from, sizeof (from));
  4117.       mspace += sizeof (from);
  4118.       memcpy (mspace, &blocklen, sizeof (blocklen));
  4119.       mspace += sizeof (blocklen);
  4120.       /* Record the memory block proper.  */
  4121.       read_inferior_memory (from, mspace, blocklen);
  4122.       trace_debug ("%d bytes recorded", blocklen);
  4123.       remaining -= blocklen;
  4124.       from += blocklen;
  4125.     }
  4126.   return 0;
  4127. }

  4128. int
  4129. agent_mem_read_string (struct eval_agent_expr_context *ctx,
  4130.                        unsigned char *to, CORE_ADDR from, ULONGEST len)
  4131. {
  4132.   unsigned char *buf, *mspace;
  4133.   ULONGEST remaining = len;
  4134.   unsigned short blocklen, i;

  4135.   /* To save a bit of space, block lengths are 16-bit, so break large
  4136.      requests into multiple blocks.  Bordering on overkill for strings,
  4137.      but it could happen that someone specifies a large max length.  */
  4138.   while (remaining > 0)
  4139.     {
  4140.       size_t sp;

  4141.       blocklen = (remaining > 65535 ? 65535 : remaining);
  4142.       /* We want working space to accumulate nonzero bytes, since
  4143.          traceframes must have a predecided size (otherwise it gets
  4144.          harder to wrap correctly for the circular case, etc).  */
  4145.       buf = (unsigned char *) xmalloc (blocklen + 1);
  4146.       for (i = 0; i < blocklen; ++i)
  4147.         {
  4148.           /* Read the string one byte at a time, in case the string is
  4149.              at the end of a valid memory area - we don't want a
  4150.              correctly-terminated string to engender segvio
  4151.              complaints.  */
  4152.           read_inferior_memory (from + i, buf + i, 1);

  4153.           if (buf[i] == '\0')
  4154.             {
  4155.               blocklen = i + 1;
  4156.               /* Make sure outer loop stops now too.  */
  4157.               remaining = blocklen;
  4158.               break;
  4159.             }
  4160.         }
  4161.       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
  4162.       mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
  4163.       if (mspace == NULL)
  4164.         {
  4165.           xfree (buf);
  4166.           return 1;
  4167.         }
  4168.       /* Identify block as a memory block.  */
  4169.       *mspace = 'M';
  4170.       ++mspace;
  4171.       /* Record address and size.  */
  4172.       memcpy ((void *) mspace, (void *) &from, sizeof (from));
  4173.       mspace += sizeof (from);
  4174.       memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
  4175.       mspace += sizeof (blocklen);
  4176.       /* Copy the string contents.  */
  4177.       memcpy ((void *) mspace, (void *) buf, blocklen);
  4178.       remaining -= blocklen;
  4179.       from += blocklen;
  4180.       xfree (buf);
  4181.     }
  4182.   return 0;
  4183. }

  4184. /* Record the value of a trace state variable.  */

  4185. int
  4186. agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
  4187. {
  4188.   unsigned char *vspace;
  4189.   LONGEST val;

  4190.   vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
  4191.                                  1 + sizeof (n) + sizeof (LONGEST));
  4192.   if (vspace == NULL)
  4193.     return 1;
  4194.   /* Identify block as a variable.  */
  4195.   *vspace = 'V';
  4196.   /* Record variable's number and value.  */
  4197.   memcpy (vspace + 1, &n, sizeof (n));
  4198.   val = get_trace_state_variable_value (n);
  4199.   memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
  4200.   trace_debug ("Variable %d recorded", n);
  4201.   return 0;
  4202. }

  4203. #ifndef IN_PROCESS_AGENT

  4204. /* Callback for traceframe_walk_blocks, used to find a given block
  4205.    type in a traceframe.  */

  4206. static int
  4207. match_blocktype (char blocktype, unsigned char *dataptr, void *data)
  4208. {
  4209.   char *wantedp = data;

  4210.   if (*wantedp == blocktype)
  4211.     return 1;

  4212.   return 0;
  4213. }

  4214. /* Walk over all traceframe blocks of the traceframe buffer starting
  4215.    at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
  4216.    block found, passing in DATA unmodified.  If CALLBACK returns true,
  4217.    this returns a pointer to where the block is found.  Returns NULL
  4218.    if no callback call returned true, indicating that all blocks have
  4219.    been walked.  */

  4220. static unsigned char *
  4221. traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
  4222.                         int tfnum,
  4223.                         int (*callback) (char blocktype,
  4224.                                          unsigned char *dataptr,
  4225.                                          void *data),
  4226.                         void *data)
  4227. {
  4228.   unsigned char *dataptr;

  4229.   if (datasize == 0)
  4230.     {
  4231.       trace_debug ("traceframe %d has no data", tfnum);
  4232.       return NULL;
  4233.     }

  4234.   /* Iterate through a traceframe's blocks, looking for a block of the
  4235.      requested type.  */
  4236.   for (dataptr = database;
  4237.        dataptr < database + datasize;
  4238.        /* nothing */)
  4239.     {
  4240.       char blocktype;
  4241.       unsigned short mlen;

  4242.       if (dataptr == trace_buffer_wrap)
  4243.         {
  4244.           /* Adjust to reflect wrapping part of the frame around to
  4245.              the beginning.  */
  4246.           datasize = dataptr - database;
  4247.           dataptr = database = trace_buffer_lo;
  4248.         }

  4249.       blocktype = *dataptr++;

  4250.       if ((*callback) (blocktype, dataptr, data))
  4251.         return dataptr;

  4252.       switch (blocktype)
  4253.         {
  4254.         case 'R':
  4255.           /* Skip over the registers block.  */
  4256.           dataptr += current_target_desc ()->registers_size;
  4257.           break;
  4258.         case 'M':
  4259.           /* Skip over the memory block.  */
  4260.           dataptr += sizeof (CORE_ADDR);
  4261.           memcpy (&mlen, dataptr, sizeof (mlen));
  4262.           dataptr += (sizeof (mlen) + mlen);
  4263.           break;
  4264.         case 'V':
  4265.           /* Skip over the TSV block.  */
  4266.           dataptr += (sizeof (int) + sizeof (LONGEST));
  4267.           break;
  4268.         case 'S':
  4269.           /* Skip over the static trace data block.  */
  4270.           memcpy (&mlen, dataptr, sizeof (mlen));
  4271.           dataptr += (sizeof (mlen) + mlen);
  4272.           break;
  4273.         default:
  4274.           trace_debug ("traceframe %d has unknown block type 0x%x",
  4275.                        tfnum, blocktype);
  4276.           return NULL;
  4277.         }
  4278.     }

  4279.   return NULL;
  4280. }

  4281. /* Look for the block of type TYPE_WANTED in the trameframe starting
  4282.    at DATABASE of DATASIZE bytes long.  TFNUM is the traceframe
  4283.    number.  */

  4284. static unsigned char *
  4285. traceframe_find_block_type (unsigned char *database, unsigned int datasize,
  4286.                             int tfnum, char type_wanted)
  4287. {
  4288.   return traceframe_walk_blocks (database, datasize, tfnum,
  4289.                                  match_blocktype, &type_wanted);
  4290. }

  4291. static unsigned char *
  4292. traceframe_find_regblock (struct traceframe *tframe, int tfnum)
  4293. {
  4294.   unsigned char *regblock;

  4295.   regblock = traceframe_find_block_type (tframe->data,
  4296.                                          tframe->data_size,
  4297.                                          tfnum, 'R');

  4298.   if (regblock == NULL)
  4299.     trace_debug ("traceframe %d has no register data", tfnum);

  4300.   return regblock;
  4301. }

  4302. /* Get registers from a traceframe.  */

  4303. int
  4304. fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
  4305. {
  4306.   unsigned char *dataptr;
  4307.   struct tracepoint *tpoint;
  4308.   struct traceframe *tframe;

  4309.   tframe = find_traceframe (tfnum);

  4310.   if (tframe == NULL)
  4311.     {
  4312.       trace_debug ("traceframe %d not found", tfnum);
  4313.       return 1;
  4314.     }

  4315.   dataptr = traceframe_find_regblock (tframe, tfnum);
  4316.   if (dataptr == NULL)
  4317.     {
  4318.       /* Mark registers unavailable.  */
  4319.       supply_regblock (regcache, NULL);

  4320.       /* We can generally guess at a PC, although this will be
  4321.          misleading for while-stepping frames and multi-location
  4322.          tracepoints.  */
  4323.       tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
  4324.       if (tpoint != NULL)
  4325.         regcache_write_pc (regcache, tpoint->address);
  4326.     }
  4327.   else
  4328.     supply_regblock (regcache, dataptr);

  4329.   return 0;
  4330. }

  4331. static CORE_ADDR
  4332. traceframe_get_pc (struct traceframe *tframe)
  4333. {
  4334.   struct regcache regcache;
  4335.   unsigned char *dataptr;
  4336.   const struct target_desc *tdesc = current_target_desc ();

  4337.   dataptr = traceframe_find_regblock (tframe, -1);
  4338.   if (dataptr == NULL)
  4339.     return 0;

  4340.   init_register_cache (&regcache, tdesc, dataptr);
  4341.   return regcache_read_pc (&regcache);
  4342. }

  4343. /* Read a requested block of memory from a trace frame.  */

  4344. int
  4345. traceframe_read_mem (int tfnum, CORE_ADDR addr,
  4346.                      unsigned char *buf, ULONGEST length,
  4347.                      ULONGEST *nbytes)
  4348. {
  4349.   struct traceframe *tframe;
  4350.   unsigned char *database, *dataptr;
  4351.   unsigned int datasize;
  4352.   CORE_ADDR maddr;
  4353.   unsigned short mlen;

  4354.   trace_debug ("traceframe_read_mem");

  4355.   tframe = find_traceframe (tfnum);

  4356.   if (!tframe)
  4357.     {
  4358.       trace_debug ("traceframe %d not found", tfnum);
  4359.       return 1;
  4360.     }

  4361.   datasize = tframe->data_size;
  4362.   database = dataptr = &tframe->data[0];

  4363.   /* Iterate through a traceframe's blocks, looking for memory.  */
  4364.   while ((dataptr = traceframe_find_block_type (dataptr,
  4365.                                                 datasize
  4366.                                                 - (dataptr - database),
  4367.                                                 tfnum, 'M')) != NULL)
  4368.     {
  4369.       memcpy (&maddr, dataptr, sizeof (maddr));
  4370.       dataptr += sizeof (maddr);
  4371.       memcpy (&mlen, dataptr, sizeof (mlen));
  4372.       dataptr += sizeof (mlen);
  4373.       trace_debug ("traceframe %d has %d bytes at %s",
  4374.                    tfnum, mlen, paddress (maddr));

  4375.       /* If the block includes the first part of the desired range,
  4376.          return as much it has; GDB will re-request the remainder,
  4377.          which might be in a different block of this trace frame.  */
  4378.       if (maddr <= addr && addr < (maddr + mlen))
  4379.         {
  4380.           ULONGEST amt = (maddr + mlen) - addr;
  4381.           if (amt > length)
  4382.             amt = length;

  4383.           memcpy (buf, dataptr + (addr - maddr), amt);
  4384.           *nbytes = amt;
  4385.           return 0;
  4386.         }

  4387.       /* Skip over this block.  */
  4388.       dataptr += mlen;
  4389.     }

  4390.   trace_debug ("traceframe %d has no memory data for the desired region",
  4391.                tfnum);

  4392.   *nbytes = 0;
  4393.   return 0;
  4394. }

  4395. static int
  4396. traceframe_read_tsv (int tsvnum, LONGEST *val)
  4397. {
  4398.   int tfnum;
  4399.   struct traceframe *tframe;
  4400.   unsigned char *database, *dataptr;
  4401.   unsigned int datasize;
  4402.   int vnum;
  4403.   int found = 0;

  4404.   trace_debug ("traceframe_read_tsv");

  4405.   tfnum = current_traceframe;

  4406.   if (tfnum < 0)
  4407.     {
  4408.       trace_debug ("no current traceframe");
  4409.       return 1;
  4410.     }

  4411.   tframe = find_traceframe (tfnum);

  4412.   if (tframe == NULL)
  4413.     {
  4414.       trace_debug ("traceframe %d not found", tfnum);
  4415.       return 1;
  4416.     }

  4417.   datasize = tframe->data_size;
  4418.   database = dataptr = &tframe->data[0];

  4419.   /* Iterate through a traceframe's blocks, looking for the last
  4420.      matched tsv.  */
  4421.   while ((dataptr = traceframe_find_block_type (dataptr,
  4422.                                                 datasize
  4423.                                                 - (dataptr - database),
  4424.                                                 tfnum, 'V')) != NULL)
  4425.     {
  4426.       memcpy (&vnum, dataptr, sizeof (vnum));
  4427.       dataptr += sizeof (vnum);

  4428.       trace_debug ("traceframe %d has variable %d", tfnum, vnum);

  4429.       /* Check that this is the variable we want.  */
  4430.       if (tsvnum == vnum)
  4431.         {
  4432.           memcpy (val, dataptr, sizeof (*val));
  4433.           found = 1;
  4434.         }

  4435.       /* Skip over this block.  */
  4436.       dataptr += sizeof (LONGEST);
  4437.     }

  4438.   if (!found)
  4439.     trace_debug ("traceframe %d has no data for variable %d",
  4440.                  tfnum, tsvnum);
  4441.   return !found;
  4442. }

  4443. /* Read a requested block of static tracepoint data from a trace
  4444.    frame.  */

  4445. int
  4446. traceframe_read_sdata (int tfnum, ULONGEST offset,
  4447.                        unsigned char *buf, ULONGEST length,
  4448.                        ULONGEST *nbytes)
  4449. {
  4450.   struct traceframe *tframe;
  4451.   unsigned char *database, *dataptr;
  4452.   unsigned int datasize;
  4453.   unsigned short mlen;

  4454.   trace_debug ("traceframe_read_sdata");

  4455.   tframe = find_traceframe (tfnum);

  4456.   if (!tframe)
  4457.     {
  4458.       trace_debug ("traceframe %d not found", tfnum);
  4459.       return 1;
  4460.     }

  4461.   datasize = tframe->data_size;
  4462.   database = &tframe->data[0];

  4463.   /* Iterate through a traceframe's blocks, looking for static
  4464.      tracepoint data.  */
  4465.   dataptr = traceframe_find_block_type (database, datasize,
  4466.                                         tfnum, 'S');
  4467.   if (dataptr != NULL)
  4468.     {
  4469.       memcpy (&mlen, dataptr, sizeof (mlen));
  4470.       dataptr += sizeof (mlen);
  4471.       if (offset < mlen)
  4472.         {
  4473.           if (offset + length > mlen)
  4474.             length = mlen - offset;

  4475.           memcpy (buf, dataptr, length);
  4476.           *nbytes = length;
  4477.         }
  4478.       else
  4479.         *nbytes = 0;
  4480.       return 0;
  4481.     }

  4482.   trace_debug ("traceframe %d has no static trace data", tfnum);

  4483.   *nbytes = 0;
  4484.   return 0;
  4485. }

  4486. /* Callback for traceframe_walk_blocks.  Builds a traceframe-info
  4487.    object.  DATA is pointer to a struct buffer holding the
  4488.    traceframe-info object being built.  */

  4489. static int
  4490. build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
  4491. {
  4492.   struct buffer *buffer = data;

  4493.   switch (blocktype)
  4494.     {
  4495.     case 'M':
  4496.       {
  4497.         unsigned short mlen;
  4498.         CORE_ADDR maddr;

  4499.         memcpy (&maddr, dataptr, sizeof (maddr));
  4500.         dataptr += sizeof (maddr);
  4501.         memcpy (&mlen, dataptr, sizeof (mlen));
  4502.         dataptr += sizeof (mlen);
  4503.         buffer_xml_printf (buffer,
  4504.                            "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
  4505.                            paddress (maddr), phex_nz (mlen, sizeof (mlen)));
  4506.         break;
  4507.       }
  4508.     case 'V':
  4509.       {
  4510.         int vnum;

  4511.         memcpy (&vnum, dataptr, sizeof (vnum));
  4512.         buffer_xml_printf (buffer, "<tvar id=\"%d\"/>\n", vnum);
  4513.         break;
  4514.       }
  4515.     case 'R':
  4516.     case 'S':
  4517.       {
  4518.         break;
  4519.       }
  4520.     default:
  4521.       warning ("Unhandled trace block type (%d) '%c ' "
  4522.                "while building trace frame info.",
  4523.                blocktype, blocktype);
  4524.       break;
  4525.     }

  4526.   return 0;
  4527. }

  4528. /* Build a traceframe-info object for traceframe number TFNUM into
  4529.    BUFFER.  */

  4530. int
  4531. traceframe_read_info (int tfnum, struct buffer *buffer)
  4532. {
  4533.   struct traceframe *tframe;

  4534.   trace_debug ("traceframe_read_info");

  4535.   tframe = find_traceframe (tfnum);

  4536.   if (!tframe)
  4537.     {
  4538.       trace_debug ("traceframe %d not found", tfnum);
  4539.       return 1;
  4540.     }

  4541.   buffer_grow_str (buffer, "<traceframe-info>\n");
  4542.   traceframe_walk_blocks (tframe->data, tframe->data_size,
  4543.                           tfnum, build_traceframe_info_xml, buffer);
  4544.   buffer_grow_str0 (buffer, "</traceframe-info>\n");
  4545.   return 0;
  4546. }

  4547. /* Return the first fast tracepoint whose jump pad contains PC.  */

  4548. static struct tracepoint *
  4549. fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
  4550. {
  4551.   struct tracepoint *tpoint;

  4552.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  4553.     if (tpoint->type == fast_tracepoint)
  4554.       if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
  4555.         return tpoint;

  4556.   return NULL;
  4557. }

  4558. /* Return the first fast tracepoint whose trampoline contains PC.  */

  4559. static struct tracepoint *
  4560. fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
  4561. {
  4562.   struct tracepoint *tpoint;

  4563.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  4564.     {
  4565.       if (tpoint->type == fast_tracepoint
  4566.           && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
  4567.         return tpoint;
  4568.     }

  4569.   return NULL;
  4570. }

  4571. /* Return GDBserver's tracepoint that matches the IP Agent's
  4572.    tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
  4573.    address space.  */

  4574. static struct tracepoint *
  4575. fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
  4576. {
  4577.   struct tracepoint *tpoint;

  4578.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  4579.     if (tpoint->type == fast_tracepoint)
  4580.       if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
  4581.         return tpoint;

  4582.   return NULL;
  4583. }

  4584. #endif

  4585. /* The type of the object that is used to synchronize fast tracepoint
  4586.    collection.  */

  4587. typedef struct collecting_t
  4588. {
  4589.   /* The fast tracepoint number currently collecting.  */
  4590.   uintptr_t tpoint;

  4591.   /* A number that GDBserver can use to identify the thread that is
  4592.      presently holding the collect lock.  This need not (and usually
  4593.      is not) the thread id, as getting the current thread ID usually
  4594.      requires a system call, which we want to avoid like the plague.
  4595.      Usually this is thread's TCB, found in the TLS (pseudo-)
  4596.      register, which is readable with a single insn on several
  4597.      architectures.  */
  4598.   uintptr_t thread_area;
  4599. } collecting_t;

  4600. #ifndef IN_PROCESS_AGENT

  4601. void
  4602. force_unlock_trace_buffer (void)
  4603. {
  4604.   write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
  4605. }

  4606. /* Check if the thread identified by THREAD_AREA which is stopped at
  4607.    STOP_PC, is presently locking the fast tracepoint collection, and
  4608.    if so, gather some status of said collection.  Returns 0 if the
  4609.    thread isn't collecting or in the jump pad at all.  1, if in the
  4610.    jump pad (or within gdb_collect) and hasn't executed the adjusted
  4611.    original insn yet (can set a breakpoint there and run to it).  2,
  4612.    if presently executing the adjusted original insn --- in which
  4613.    case, if we want to move the thread out of the jump pad, we need to
  4614.    single-step it until this function returns 0.  */

  4615. int
  4616. fast_tracepoint_collecting (CORE_ADDR thread_area,
  4617.                             CORE_ADDR stop_pc,
  4618.                             struct fast_tpoint_collect_status *status)
  4619. {
  4620.   CORE_ADDR ipa_collecting;
  4621.   CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
  4622.   CORE_ADDR ipa_gdb_trampoline_buffer;
  4623.   CORE_ADDR ipa_gdb_trampoline_buffer_end;
  4624.   struct tracepoint *tpoint;
  4625.   int needs_breakpoint;

  4626.   /* The thread THREAD_AREA is either:

  4627.       0. not collecting at all, not within the jump pad, or within
  4628.          gdb_collect or one of its callees.

  4629.       1. in the jump pad and haven't reached gdb_collect

  4630.       2. within gdb_collect (out of the jump pad) (collect is set)

  4631.       3. we're in the jump pad, after gdb_collect having returned,
  4632.          possibly executing the adjusted insns.

  4633.       For cases 1 and 3, `collecting' may or not be set.  The jump pad
  4634.       doesn't have any complicated jump logic, so we can tell if the
  4635.       thread is executing the adjust original insn or not by just
  4636.       matching STOP_PC with known jump pad addresses.  If we it isn't
  4637.       yet executing the original insn, set a breakpoint there, and let
  4638.       the thread run to it, so to quickly step over a possible (many
  4639.       insns) gdb_collect call.  Otherwise, or when the breakpoint is
  4640.       hit, only a few (small number of) insns are left to be executed
  4641.       in the jump pad.  Single-step the thread until it leaves the
  4642.       jump pad.  */

  4643. again:
  4644.   tpoint = NULL;
  4645.   needs_breakpoint = 0;
  4646.   trace_debug ("fast_tracepoint_collecting");

  4647.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
  4648.                                   &ipa_gdb_jump_pad_buffer))
  4649.     {
  4650.       internal_error (__FILE__, __LINE__,
  4651.                       "error extracting `gdb_jump_pad_buffer'");
  4652.     }
  4653.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
  4654.                                   &ipa_gdb_jump_pad_buffer_end))
  4655.     {
  4656.       internal_error (__FILE__, __LINE__,
  4657.                       "error extracting `gdb_jump_pad_buffer_end'");
  4658.     }

  4659.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
  4660.                                   &ipa_gdb_trampoline_buffer))
  4661.     {
  4662.       internal_error (__FILE__, __LINE__,
  4663.                       "error extracting `gdb_trampoline_buffer'");
  4664.     }
  4665.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
  4666.                                   &ipa_gdb_trampoline_buffer_end))
  4667.     {
  4668.       internal_error (__FILE__, __LINE__,
  4669.                       "error extracting `gdb_trampoline_buffer_end'");
  4670.     }

  4671.   if (ipa_gdb_jump_pad_buffer <= stop_pc
  4672.       && stop_pc < ipa_gdb_jump_pad_buffer_end)
  4673.     {
  4674.       /* We can tell which tracepoint(s) the thread is collecting by
  4675.          matching the jump pad address back to the tracepoint.  */
  4676.       tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
  4677.       if (tpoint == NULL)
  4678.         {
  4679.           warning ("in jump pad, but no matching tpoint?");
  4680.           return 0;
  4681.         }
  4682.       else
  4683.         {
  4684.           trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
  4685.                        "adj_insn(%s, %s)",
  4686.                        tpoint->number, paddress (tpoint->address),
  4687.                        paddress (tpoint->jump_pad),
  4688.                        paddress (tpoint->jump_pad_end),
  4689.                        paddress (tpoint->adjusted_insn_addr),
  4690.                        paddress (tpoint->adjusted_insn_addr_end));
  4691.         }

  4692.       /* Definitely in the jump pad.  May or may not need
  4693.          fast-exit-jump-pad breakpoint.  */
  4694.       if (tpoint->jump_pad <= stop_pc
  4695.           && stop_pc < tpoint->adjusted_insn_addr)
  4696.         needs_breakpoint =  1;
  4697.     }
  4698.   else if (ipa_gdb_trampoline_buffer <= stop_pc
  4699.            && stop_pc < ipa_gdb_trampoline_buffer_end)
  4700.     {
  4701.       /* We can tell which tracepoint(s) the thread is collecting by
  4702.          matching the trampoline address back to the tracepoint.  */
  4703.       tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
  4704.       if (tpoint == NULL)
  4705.         {
  4706.           warning ("in trampoline, but no matching tpoint?");
  4707.           return 0;
  4708.         }
  4709.       else
  4710.         {
  4711.           trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
  4712.                        tpoint->number, paddress (tpoint->address),
  4713.                        paddress (tpoint->trampoline),
  4714.                        paddress (tpoint->trampoline_end));
  4715.         }

  4716.       /* Have not reached jump pad yet, but treat the trampoline as a
  4717.          part of the jump pad that is before the adjusted original
  4718.          instruction.  */
  4719.       needs_breakpoint = 1;
  4720.     }
  4721.   else
  4722.     {
  4723.       collecting_t ipa_collecting_obj;

  4724.       /* If `collecting' is set/locked, then the THREAD_AREA thread
  4725.          may or not be the one holding the lock.  We have to read the
  4726.          lock to find out.  */

  4727.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
  4728.                                       &ipa_collecting))
  4729.         {
  4730.           trace_debug ("fast_tracepoint_collecting:"
  4731.                        " failed reading 'collecting' in the inferior");
  4732.           return 0;
  4733.         }

  4734.       if (!ipa_collecting)
  4735.         {
  4736.           trace_debug ("fast_tracepoint_collecting: not collecting"
  4737.                        " (and nobody is).");
  4738.           return 0;
  4739.         }

  4740.       /* Some thread is collecting.  Check which.  */
  4741.       if (read_inferior_memory (ipa_collecting,
  4742.                                 (unsigned char *) &ipa_collecting_obj,
  4743.                                 sizeof (ipa_collecting_obj)) != 0)
  4744.         goto again;

  4745.       if (ipa_collecting_obj.thread_area != thread_area)
  4746.         {
  4747.           trace_debug ("fast_tracepoint_collecting: not collecting "
  4748.                        "(another thread is)");
  4749.           return 0;
  4750.         }

  4751.       tpoint
  4752.         = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
  4753.       if (tpoint == NULL)
  4754.         {
  4755.           warning ("fast_tracepoint_collecting: collecting, "
  4756.                    "but tpoint %s not found?",
  4757.                    paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
  4758.           return 0;
  4759.         }

  4760.       /* The thread is within `gdb_collect', skip over the rest of
  4761.          fast tracepoint collection quickly using a breakpoint.  */
  4762.       needs_breakpoint = 1;
  4763.     }

  4764.   /* The caller wants a bit of status detail.  */
  4765.   if (status != NULL)
  4766.     {
  4767.       status->tpoint_num = tpoint->number;
  4768.       status->tpoint_addr = tpoint->address;
  4769.       status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
  4770.       status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
  4771.     }

  4772.   if (needs_breakpoint)
  4773.     {
  4774.       /* Hasn't executed the original instruction yet.  Set breakpoint
  4775.          there, and wait till it's hit, then single-step until exiting
  4776.          the jump pad.  */

  4777.       trace_debug ("\
  4778. fast_tracepoint_collecting, returning continue-until-break at %s",
  4779.                    paddress (tpoint->adjusted_insn_addr));

  4780.       return 1; /* continue */
  4781.     }
  4782.   else
  4783.     {
  4784.       /* Just single-step until exiting the jump pad.  */

  4785.       trace_debug ("fast_tracepoint_collecting, returning "
  4786.                    "need-single-step (%s-%s)",
  4787.                    paddress (tpoint->adjusted_insn_addr),
  4788.                    paddress (tpoint->adjusted_insn_addr_end));

  4789.       return 2; /* single-step */
  4790.     }
  4791. }

  4792. #endif

  4793. #ifdef IN_PROCESS_AGENT

  4794. /* The global fast tracepoint collect lock.  Points to a collecting_t
  4795.    object built on the stack by the jump pad, if presently locked;
  4796.    NULL if it isn't locked.  Note that this lock *must* be set while
  4797.    executing any *function other than the jump pad.  See
  4798.    fast_tracepoint_collecting.  */
  4799. static collecting_t * ATTR_USED collecting;

  4800. /* This routine, called from the jump pad (in asm) is designed to be
  4801.    called from the jump pads of fast tracepoints, thus it is on the
  4802.    critical path.  */

  4803. IP_AGENT_EXPORT void ATTR_USED
  4804. gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
  4805. {
  4806.   struct fast_tracepoint_ctx ctx;

  4807.   /* Don't do anything until the trace run is completely set up.  */
  4808.   if (!tracing)
  4809.     return;

  4810.   ctx.base.type = fast_tracepoint;
  4811.   ctx.regs = regs;
  4812.   ctx.regcache_initted = 0;
  4813.   /* Wrap the regblock in a register cache (in the stack, we don't
  4814.      want to malloc here).  */
  4815.   ctx.regspace = alloca (ipa_tdesc->registers_size);
  4816.   if (ctx.regspace == NULL)
  4817.     {
  4818.       trace_debug ("Trace buffer block allocation failed, skipping");
  4819.       return;
  4820.     }

  4821.   for (ctx.tpoint = tpoint;
  4822.        ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
  4823.        ctx.tpoint = ctx.tpoint->next)
  4824.     {
  4825.       if (!ctx.tpoint->enabled)
  4826.         continue;

  4827.       /* Multiple tracepoints of different types, such as fast tracepoint and
  4828.          static tracepoint, can be set at the same address.  */
  4829.       if (ctx.tpoint->type != tpoint->type)
  4830.         continue;

  4831.       /* Test the condition if present, and collect if true.  */
  4832.       if (ctx.tpoint->cond == NULL
  4833.           || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
  4834.                                            ctx.tpoint))
  4835.         {
  4836.           collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
  4837.                                       ctx.tpoint->address, ctx.tpoint);

  4838.           /* Note that this will cause original insns to be written back
  4839.              to where we jumped from, but that's OK because we're jumping
  4840.              back to the next whole instruction.  This will go badly if
  4841.              instruction restoration is not atomic though.  */
  4842.           if (stopping_tracepoint
  4843.               || trace_buffer_is_full
  4844.               || expr_eval_result != expr_eval_no_error)
  4845.             {
  4846.               stop_tracing ();
  4847.               break;
  4848.             }
  4849.         }
  4850.       else
  4851.         {
  4852.           /* If there was a condition and it evaluated to false, the only
  4853.              way we would stop tracing is if there was an error during
  4854.              condition expression evaluation.  */
  4855.           if (expr_eval_result != expr_eval_no_error)
  4856.             {
  4857.               stop_tracing ();
  4858.               break;
  4859.             }
  4860.         }
  4861.     }
  4862. }

  4863. #endif

  4864. #ifndef IN_PROCESS_AGENT

  4865. CORE_ADDR
  4866. get_raw_reg_func_addr (void)
  4867. {
  4868.   return ipa_sym_addrs.addr_get_raw_reg;
  4869. }

  4870. CORE_ADDR
  4871. get_get_tsv_func_addr (void)
  4872. {
  4873.   return ipa_sym_addrs.addr_get_trace_state_variable_value;
  4874. }

  4875. CORE_ADDR
  4876. get_set_tsv_func_addr (void)
  4877. {
  4878.   return ipa_sym_addrs.addr_set_trace_state_variable_value;
  4879. }

  4880. static void
  4881. compile_tracepoint_condition (struct tracepoint *tpoint,
  4882.                               CORE_ADDR *jump_entry)
  4883. {
  4884.   CORE_ADDR entry_point = *jump_entry;
  4885.   enum eval_result_type err;

  4886.   trace_debug ("Starting condition compilation for tracepoint %d\n",
  4887.                tpoint->number);

  4888.   /* Initialize the global pointer to the code being built.  */
  4889.   current_insn_ptr = *jump_entry;

  4890.   emit_prologue ();

  4891.   err = compile_bytecodes (tpoint->cond);

  4892.   if (err == expr_eval_no_error)
  4893.     {
  4894.       emit_epilogue ();

  4895.       /* Record the beginning of the compiled code.  */
  4896.       tpoint->compiled_cond = entry_point;

  4897.       trace_debug ("Condition compilation for tracepoint %d complete\n",
  4898.                    tpoint->number);
  4899.     }
  4900.   else
  4901.     {
  4902.       /* Leave the unfinished code in situ, but don't point to it.  */

  4903.       tpoint->compiled_cond = 0;

  4904.       trace_debug ("Condition compilation for tracepoint %d failed, "
  4905.                    "error code %d",
  4906.                    tpoint->number, err);
  4907.     }

  4908.   /* Update the code pointer passed in.  Note that we do this even if
  4909.      the compile fails, so that we can look at the partial results
  4910.      instead of letting them be overwritten.  */
  4911.   *jump_entry = current_insn_ptr;

  4912.   /* Leave a gap, to aid dump decipherment.  */
  4913.   *jump_entry += 16;
  4914. }

  4915. /* We'll need to adjust these when we consider bi-arch setups, and big
  4916.    endian machines.  */

  4917. static int
  4918. write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr)
  4919. {
  4920.   return write_inferior_memory (where,
  4921.                                 (unsigned char *) &ptr, sizeof (void *));
  4922. }

  4923. /* The base pointer of the IPA's heap.  This is the only memory the
  4924.    IPA is allowed to use.  The IPA should _not_ call the inferior's
  4925.    `malloc' during operation.  That'd be slow, and, most importantly,
  4926.    it may not be safe.  We may be collecting a tracepoint in a signal
  4927.    handler, for example.  */
  4928. static CORE_ADDR target_tp_heap;

  4929. /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
  4930.    to 8 bytes.  */

  4931. static CORE_ADDR
  4932. target_malloc (ULONGEST size)
  4933. {
  4934.   CORE_ADDR ptr;

  4935.   if (target_tp_heap == 0)
  4936.     {
  4937.       /* We have the pointer *address*, need what it points to.  */
  4938.       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
  4939.                                       &target_tp_heap))
  4940.         {
  4941.           internal_error (__FILE__, __LINE__,
  4942.                           "couldn't get target heap head pointer");
  4943.         }
  4944.     }

  4945.   ptr = target_tp_heap;
  4946.   target_tp_heap += size;

  4947.   /* Pad to 8-byte alignment.  */
  4948.   target_tp_heap = ((target_tp_heap + 7) & ~0x7);

  4949.   return ptr;
  4950. }

  4951. static CORE_ADDR
  4952. download_agent_expr (struct agent_expr *expr)
  4953. {
  4954.   CORE_ADDR expr_addr;
  4955.   CORE_ADDR expr_bytes;

  4956.   expr_addr = target_malloc (sizeof (*expr));
  4957.   write_inferior_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));

  4958.   expr_bytes = target_malloc (expr->length);
  4959.   write_inferior_data_ptr (expr_addr + offsetof (struct agent_expr, bytes),
  4960.                            expr_bytes);
  4961.   write_inferior_memory (expr_bytes, expr->bytes, expr->length);

  4962.   return expr_addr;
  4963. }

  4964. /* Align V up to N bits.  */
  4965. #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))

  4966. /* Sync tracepoint with IPA, but leave maintenance of linked list to caller.  */

  4967. static void
  4968. download_tracepoint_1 (struct tracepoint *tpoint)
  4969. {
  4970.   struct tracepoint target_tracepoint;
  4971.   CORE_ADDR tpptr = 0;

  4972.   gdb_assert (tpoint->type == fast_tracepoint
  4973.               || tpoint->type == static_tracepoint);

  4974.   if (tpoint->cond != NULL && target_emit_ops () != NULL)
  4975.     {
  4976.       CORE_ADDR jentry, jump_entry;

  4977.       jentry = jump_entry = get_jump_space_head ();

  4978.       if (tpoint->cond != NULL)
  4979.         {
  4980.           /* Pad to 8-byte alignment. (needed?)  */
  4981.           /* Actually this should be left for the target to
  4982.              decide.  */
  4983.           jentry = UALIGN (jentry, 8);

  4984.           compile_tracepoint_condition (tpoint, &jentry);
  4985.         }

  4986.       /* Pad to 8-byte alignment.  */
  4987.       jentry = UALIGN (jentry, 8);
  4988.       claim_jump_space (jentry - jump_entry);
  4989.     }

  4990.   target_tracepoint = *tpoint;

  4991.   tpptr = target_malloc (sizeof (*tpoint));
  4992.   tpoint->obj_addr_on_target = tpptr;

  4993.   /* Write the whole object.  We'll fix up its pointers in a bit.
  4994.      Assume no next for now.  This is fixed up above on the next
  4995.      iteration, if there's any.  */
  4996.   target_tracepoint.next = NULL;
  4997.   /* Need to clear this here too, since we're downloading the
  4998.      tracepoints before clearing our own copy.  */
  4999.   target_tracepoint.hit_count = 0;

  5000.   write_inferior_memory (tpptr, (unsigned char *) &target_tracepoint,
  5001.                          sizeof (target_tracepoint));

  5002.   if (tpoint->cond)
  5003.     write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
  5004.                                                cond),
  5005.                              download_agent_expr (tpoint->cond));

  5006.   if (tpoint->numactions)
  5007.     {
  5008.       int i;
  5009.       CORE_ADDR actions_array;

  5010.       /* The pointers array.  */
  5011.       actions_array
  5012.         = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
  5013.       write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
  5014.                                                  actions),
  5015.                                actions_array);

  5016.       /* Now for each pointer, download the action.  */
  5017.       for (i = 0; i < tpoint->numactions; i++)
  5018.         {
  5019.           struct tracepoint_action *action = tpoint->actions[i];
  5020.           CORE_ADDR ipa_action = action->ops->download (action);

  5021.           if (ipa_action != 0)
  5022.             write_inferior_data_ptr
  5023.               (actions_array + i * sizeof (*tpoint->actions),
  5024.                ipa_action);
  5025.         }
  5026.     }
  5027. }

  5028. #define IPA_PROTO_FAST_TRACE_FLAG 0
  5029. #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
  5030. #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
  5031. #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
  5032. #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22

  5033. /* Send a command to agent to download and install tracepoint TPOINT.  */

  5034. static int
  5035. tracepoint_send_agent (struct tracepoint *tpoint)
  5036. {
  5037.   char buf[IPA_CMD_BUF_SIZE];
  5038.   char *p;
  5039.   int i, ret;

  5040.   p = buf;
  5041.   strcpy (p, "FastTrace:");
  5042.   p += 10;

  5043.   COPY_FIELD_TO_BUF (p, tpoint, number);
  5044.   COPY_FIELD_TO_BUF (p, tpoint, address);
  5045.   COPY_FIELD_TO_BUF (p, tpoint, type);
  5046.   COPY_FIELD_TO_BUF (p, tpoint, enabled);
  5047.   COPY_FIELD_TO_BUF (p, tpoint, step_count);
  5048.   COPY_FIELD_TO_BUF (p, tpoint, pass_count);
  5049.   COPY_FIELD_TO_BUF (p, tpoint, numactions);
  5050.   COPY_FIELD_TO_BUF (p, tpoint, hit_count);
  5051.   COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
  5052.   COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
  5053.   COPY_FIELD_TO_BUF (p, tpoint, orig_size);

  5054.   /* condition */
  5055.   p = agent_expr_send (p, tpoint->cond);

  5056.   /* tracepoint_action */
  5057.   for (i = 0; i < tpoint->numactions; i++)
  5058.     {
  5059.       struct tracepoint_action *action = tpoint->actions[i];

  5060.       p[0] = action->type;
  5061.       p = action->ops->send (&p[1], action);
  5062.     }

  5063.   get_jump_space_head ();
  5064.   /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
  5065.      agent can use jump pad from it.  */
  5066.   if (tpoint->type == fast_tracepoint)
  5067.     {
  5068.       memcpy (p, &gdb_jump_pad_head, 8);
  5069.       p += 8;
  5070.     }

  5071.   ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
  5072.   if (ret)
  5073.     return ret;

  5074.   if (strncmp (buf, "OK", 2) != 0)
  5075.     return 1;

  5076.   /* The value of tracepoint's target address is stored in BUF.  */
  5077.   memcpy (&tpoint->obj_addr_on_target,
  5078.           &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);

  5079.   if (tpoint->type == fast_tracepoint)
  5080.     {
  5081.       unsigned char *insn
  5082.         = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
  5083.       int fjump_size;

  5084.      trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
  5085.                   (unsigned int) tpoint->obj_addr_on_target,
  5086.                   (unsigned int) gdb_jump_pad_head);

  5087.       memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);

  5088.       /* This has been done in agent.  We should also set up record for it.  */
  5089.       memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
  5090.       /* Wire it in.  */
  5091.       tpoint->handle
  5092.         = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
  5093.     }

  5094.   return 0;
  5095. }

  5096. static void
  5097. download_tracepoint (struct tracepoint *tpoint)
  5098. {
  5099.   struct tracepoint *tp, *tp_prev;

  5100.   if (tpoint->type != fast_tracepoint
  5101.       && tpoint->type != static_tracepoint)
  5102.     return;

  5103.   download_tracepoint_1 (tpoint);

  5104.   /* Find the previous entry of TPOINT, which is fast tracepoint or
  5105.      static tracepoint.  */
  5106.   tp_prev = NULL;
  5107.   for (tp = tracepoints; tp != tpoint; tp = tp->next)
  5108.     {
  5109.       if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
  5110.         tp_prev = tp;
  5111.     }

  5112.   if (tp_prev)
  5113.     {
  5114.       CORE_ADDR tp_prev_target_next_addr;

  5115.       /* Insert TPOINT after TP_PREV in IPA.  */
  5116.       if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
  5117.                                       + offsetof (struct tracepoint, next),
  5118.                                       &tp_prev_target_next_addr))
  5119.         {
  5120.           internal_error (__FILE__, __LINE__,
  5121.                           "error reading `tp_prev->next'");
  5122.         }

  5123.       /* tpoint->next = tp_prev->next */
  5124.       write_inferior_data_ptr (tpoint->obj_addr_on_target
  5125.                                + offsetof (struct tracepoint, next),
  5126.                                tp_prev_target_next_addr);
  5127.       /* tp_prev->next = tpoint */
  5128.       write_inferior_data_ptr (tp_prev->obj_addr_on_target
  5129.                                + offsetof (struct tracepoint, next),
  5130.                                tpoint->obj_addr_on_target);
  5131.     }
  5132.   else
  5133.     /* First object in list, set the head pointer in the
  5134.        inferior.  */
  5135.     write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints,
  5136.                              tpoint->obj_addr_on_target);

  5137. }

  5138. static void
  5139. download_trace_state_variables (void)
  5140. {
  5141.   CORE_ADDR ptr = 0, prev_ptr = 0;
  5142.   struct trace_state_variable *tsv;

  5143.   /* Start out empty.  */
  5144.   write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables, 0);

  5145.   for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
  5146.     {
  5147.       struct trace_state_variable target_tsv;

  5148.       /* TSV's with a getter have been initialized equally in both the
  5149.          inferior and GDBserver.  Skip them.  */
  5150.       if (tsv->getter != NULL)
  5151.         continue;

  5152.       target_tsv = *tsv;

  5153.       prev_ptr = ptr;
  5154.       ptr = target_malloc (sizeof (*tsv));

  5155.       if (tsv == trace_state_variables)
  5156.         {
  5157.           /* First object in list, set the head pointer in the
  5158.              inferior.  */

  5159.           write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables,
  5160.                                    ptr);
  5161.         }
  5162.       else
  5163.         {
  5164.           write_inferior_data_ptr (prev_ptr
  5165.                                    + offsetof (struct trace_state_variable,
  5166.                                                next),
  5167.                                    ptr);
  5168.         }

  5169.       /* Write the whole object.  We'll fix up its pointers in a bit.
  5170.          Assume no next, fixup when needed.  */
  5171.       target_tsv.next = NULL;

  5172.       write_inferior_memory (ptr, (unsigned char *) &target_tsv,
  5173.                              sizeof (target_tsv));

  5174.       if (tsv->name != NULL)
  5175.         {
  5176.           size_t size = strlen (tsv->name) + 1;
  5177.           CORE_ADDR name_addr = target_malloc (size);
  5178.           write_inferior_memory (name_addr,
  5179.                                  (unsigned char *) tsv->name, size);
  5180.           write_inferior_data_ptr (ptr
  5181.                                    + offsetof (struct trace_state_variable,
  5182.                                                name),
  5183.                                    name_addr);
  5184.         }

  5185.       gdb_assert (tsv->getter == NULL);
  5186.     }

  5187.   if (prev_ptr != 0)
  5188.     {
  5189.       /* Fixup the next pointer in the last item in the list.  */
  5190.       write_inferior_data_ptr (prev_ptr
  5191.                                + offsetof (struct trace_state_variable,
  5192.                                            next), 0);
  5193.     }
  5194. }

  5195. /* Upload complete trace frames out of the IP Agent's trace buffer
  5196.    into GDBserver's trace buffer.  This always uploads either all or
  5197.    no trace frames.  This is the counter part of
  5198.    `trace_alloc_trace_buffer'.  See its description of the atomic
  5199.    synching mechanism.  */

  5200. static void
  5201. upload_fast_traceframes (void)
  5202. {
  5203.   unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
  5204.   unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
  5205.   CORE_ADDR tf;
  5206.   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
  5207.   unsigned int curr_tbctrl_idx;
  5208.   unsigned int ipa_trace_buffer_ctrl_curr;
  5209.   unsigned int ipa_trace_buffer_ctrl_curr_old;
  5210.   CORE_ADDR ipa_trace_buffer_ctrl_addr;
  5211.   struct breakpoint *about_to_request_buffer_space_bkpt;
  5212.   CORE_ADDR ipa_trace_buffer_lo;
  5213.   CORE_ADDR ipa_trace_buffer_hi;

  5214.   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
  5215.                               &ipa_traceframe_read_count_racy))
  5216.     {
  5217.       /* This will happen in most targets if the current thread is
  5218.          running.  */
  5219.       return;
  5220.     }

  5221.   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
  5222.                               &ipa_traceframe_write_count_racy))
  5223.     return;

  5224.   trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
  5225.                ipa_traceframe_write_count_racy
  5226.                - ipa_traceframe_read_count_racy,
  5227.                ipa_traceframe_write_count_racy,
  5228.                ipa_traceframe_read_count_racy);

  5229.   if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
  5230.     return;

  5231.   about_to_request_buffer_space_bkpt
  5232.     = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
  5233.                          NULL);

  5234.   if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
  5235.                               &ipa_trace_buffer_ctrl_curr))
  5236.     return;

  5237.   ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;

  5238.   curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;

  5239.   {
  5240.     unsigned int prev, counter;

  5241.     /* Update the token, with new counters, and the GDBserver stamp
  5242.        bit.  Alway reuse the current TBC index.  */
  5243.     prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
  5244.     counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;

  5245.     ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
  5246.                                   | (prev << 12)
  5247.                                   | counter
  5248.                                   | curr_tbctrl_idx);
  5249.   }

  5250.   if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
  5251.                                ipa_trace_buffer_ctrl_curr))
  5252.     return;

  5253.   trace_debug ("Lib: Committed %08x -> %08x",
  5254.                ipa_trace_buffer_ctrl_curr_old,
  5255.                ipa_trace_buffer_ctrl_curr);

  5256.   /* Re-read these, now that we've installed the
  5257.      `about_to_request_buffer_space' breakpoint/lock.  A thread could
  5258.      have finished a traceframe between the last read of these
  5259.      counters and setting the breakpoint above.  If we start
  5260.      uploading, we never want to leave this function with
  5261.      traceframe_read_count != 0, otherwise, GDBserver could end up
  5262.      incrementing the counter tokens more than once (due to event loop
  5263.      nesting), which would break the IP agent's "effective" detection
  5264.      (see trace_alloc_trace_buffer).  */
  5265.   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
  5266.                               &ipa_traceframe_read_count))
  5267.     return;
  5268.   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
  5269.                               &ipa_traceframe_write_count))
  5270.     return;

  5271.   if (debug_threads)
  5272.     {
  5273.       trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
  5274.                    ipa_traceframe_write_count - ipa_traceframe_read_count,
  5275.                    ipa_traceframe_write_count, ipa_traceframe_read_count);

  5276.       if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
  5277.           || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
  5278.         trace_debug ("note that ipa_traceframe_count's parts changed");
  5279.     }

  5280.   /* Get the address of the current TBC object (the IP agent has an
  5281.      array of 3 such objects).  The index is stored in the TBC
  5282.      token.  */
  5283.   ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
  5284.   ipa_trace_buffer_ctrl_addr
  5285.     += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;

  5286.   if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
  5287.                             (unsigned char *) &ipa_trace_buffer_ctrl,
  5288.                             sizeof (struct ipa_trace_buffer_control)))
  5289.     return;

  5290.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
  5291.                                   &ipa_trace_buffer_lo))
  5292.     return;
  5293.   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
  5294.                                   &ipa_trace_buffer_hi))
  5295.     return;

  5296.   /* Offsets are easier to grok for debugging than raw addresses,
  5297.      especially for the small trace buffer sizes that are useful for
  5298.      testing.  */
  5299.   trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
  5300.                "endfree=%d wrap=%d hi=%d",
  5301.                curr_tbctrl_idx,
  5302.                (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
  5303.                (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
  5304.                (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
  5305.                (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
  5306.                (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));

  5307.   /* Note that the IPA's buffer is always circular.  */

  5308. #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)

  5309. #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ)                \
  5310.   ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)

  5311. #define IPA_NEXT_TRACEFRAME(TF, TFOBJ)                                        \
  5312.   (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ)                                        \
  5313.    - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
  5314.       ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo)                \
  5315.       : 0))

  5316.   tf = IPA_FIRST_TRACEFRAME ();

  5317.   while (ipa_traceframe_write_count - ipa_traceframe_read_count)
  5318.     {
  5319.       struct tracepoint *tpoint;
  5320.       struct traceframe *tframe;
  5321.       unsigned char *block;
  5322.       struct traceframe ipa_tframe;

  5323.       if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
  5324.                                 offsetof (struct traceframe, data)))
  5325.         error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));

  5326.       if (ipa_tframe.tpnum == 0)
  5327.         {
  5328.           internal_error (__FILE__, __LINE__,
  5329.                           "Uploading: No (more) fast traceframes, but"
  5330.                           " ipa_traceframe_count == %u??\n",
  5331.                           ipa_traceframe_write_count
  5332.                           - ipa_traceframe_read_count);
  5333.         }

  5334.       /* Note that this will be incorrect for multi-location
  5335.          tracepoints...  */
  5336.       tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);

  5337.       tframe = add_traceframe (tpoint);
  5338.       if (tframe == NULL)
  5339.         {
  5340.           trace_buffer_is_full = 1;
  5341.           trace_debug ("Uploading: trace buffer is full");
  5342.         }
  5343.       else
  5344.         {
  5345.           /* Copy the whole set of blocks in one go for now.  FIXME:
  5346.              split this in smaller blocks.  */
  5347.           block = add_traceframe_block (tframe, tpoint,
  5348.                                         ipa_tframe.data_size);
  5349.           if (block != NULL)
  5350.             {
  5351.               if (read_inferior_memory (tf
  5352.                                         + offsetof (struct traceframe, data),
  5353.                                         block, ipa_tframe.data_size))
  5354.                 error ("Uploading: Couldn't read traceframe data at %s\n",
  5355.                        paddress (tf + offsetof (struct traceframe, data)));
  5356.             }

  5357.           trace_debug ("Uploading: traceframe didn't fit");
  5358.           finish_traceframe (tframe);
  5359.         }

  5360.       tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);

  5361.       /* If we freed the traceframe that wrapped around, go back
  5362.          to the non-wrap case.  */
  5363.       if (tf < ipa_trace_buffer_ctrl.start)
  5364.         {
  5365.           trace_debug ("Lib: Discarding past the wraparound");
  5366.           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
  5367.         }
  5368.       ipa_trace_buffer_ctrl.start = tf;
  5369.       ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
  5370.       ++ipa_traceframe_read_count;

  5371.       if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
  5372.           && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
  5373.         {
  5374.           trace_debug ("Lib: buffer is fully empty.  "
  5375.                        "Trace buffer [%d] start=%d free=%d endfree=%d",
  5376.                        curr_tbctrl_idx,
  5377.                        (int) (ipa_trace_buffer_ctrl.start
  5378.                               - ipa_trace_buffer_lo),
  5379.                        (int) (ipa_trace_buffer_ctrl.free
  5380.                               - ipa_trace_buffer_lo),
  5381.                        (int) (ipa_trace_buffer_ctrl.end_free
  5382.                               - ipa_trace_buffer_lo));

  5383.           ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
  5384.           ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
  5385.           ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
  5386.           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
  5387.         }

  5388.       trace_debug ("Uploaded a traceframe\n"
  5389.                    "Lib: Trace buffer [%d] start=%d free=%d "
  5390.                    "endfree=%d wrap=%d hi=%d",
  5391.                    curr_tbctrl_idx,
  5392.                    (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
  5393.                    (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
  5394.                    (int) (ipa_trace_buffer_ctrl.end_free
  5395.                           - ipa_trace_buffer_lo),
  5396.                    (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
  5397.                    (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
  5398.     }

  5399.   if (write_inferior_memory (ipa_trace_buffer_ctrl_addr,
  5400.                              (unsigned char *) &ipa_trace_buffer_ctrl,
  5401.                              sizeof (struct ipa_trace_buffer_control)))
  5402.     return;

  5403.   write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
  5404.                           ipa_traceframe_read_count);

  5405.   trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);

  5406.   pause_all (1);

  5407.   delete_breakpoint (about_to_request_buffer_space_bkpt);
  5408.   about_to_request_buffer_space_bkpt = NULL;

  5409.   unpause_all (1);

  5410.   if (trace_buffer_is_full)
  5411.     stop_tracing ();
  5412. }
  5413. #endif

  5414. #ifdef IN_PROCESS_AGENT

  5415. IP_AGENT_EXPORT int ust_loaded;
  5416. IP_AGENT_EXPORT char cmd_buf[IPA_CMD_BUF_SIZE];

  5417. #ifdef HAVE_UST

  5418. /* Static tracepoints.  */

  5419. /* UST puts a "struct tracepoint" in the global namespace, which
  5420.    conflicts with our tracepoint.  Arguably, being a library, it
  5421.    shouldn't take ownership of such a generic name.  We work around it
  5422.    here.  */
  5423. #define tracepoint ust_tracepoint
  5424. #include <ust/ust.h>
  5425. #undef tracepoint

  5426. extern int serialize_to_text (char *outbuf, int bufsize,
  5427.                               const char *fmt, va_list ap);

  5428. #define GDB_PROBE_NAME "gdb"

  5429. /* We dynamically search for the UST symbols instead of linking them
  5430.    in.  This lets the user decide if the application uses static
  5431.    tracepoints, instead of always pulling libust.so in.  This vector
  5432.    holds pointers to all functions we care about.  */

  5433. static struct
  5434. {
  5435.   int (*serialize_to_text) (char *outbuf, int bufsize,
  5436.                             const char *fmt, va_list ap);

  5437.   int (*ltt_probe_register) (struct ltt_available_probe *pdata);
  5438.   int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);

  5439.   int (*ltt_marker_connect) (const char *channel, const char *mname,
  5440.                              const char *pname);
  5441.   int (*ltt_marker_disconnect) (const char *channel, const char *mname,
  5442.                                 const char *pname);

  5443.   void (*marker_iter_start) (struct marker_iter *iter);
  5444.   void (*marker_iter_next) (struct marker_iter *iter);
  5445.   void (*marker_iter_stop) (struct marker_iter *iter);
  5446.   void (*marker_iter_reset) (struct marker_iter *iter);
  5447. } ust_ops;

  5448. #include <dlfcn.h>

  5449. /* Cast through typeof to catch incompatible API changes.  Since UST
  5450.    only builds with gcc, we can freely use gcc extensions here
  5451.    too.  */
  5452. #define GET_UST_SYM(SYM)                                        \
  5453.   do                                                                \
  5454.     {                                                                \
  5455.       if (ust_ops.SYM == NULL)                                        \
  5456.         ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM);        \
  5457.       if (ust_ops.SYM == NULL)                                        \
  5458.         return 0;                                                \
  5459.     } while (0)

  5460. #define USTF(SYM) ust_ops.SYM

  5461. /* Get pointers to all libust.so functions we care about.  */

  5462. static int
  5463. dlsym_ust (void)
  5464. {
  5465.   GET_UST_SYM (serialize_to_text);

  5466.   GET_UST_SYM (ltt_probe_register);
  5467.   GET_UST_SYM (ltt_probe_unregister);
  5468.   GET_UST_SYM (ltt_marker_connect);
  5469.   GET_UST_SYM (ltt_marker_disconnect);

  5470.   GET_UST_SYM (marker_iter_start);
  5471.   GET_UST_SYM (marker_iter_next);
  5472.   GET_UST_SYM (marker_iter_stop);
  5473.   GET_UST_SYM (marker_iter_reset);

  5474.   ust_loaded = 1;
  5475.   return 1;
  5476. }

  5477. /* Given an UST marker, return the matching gdb static tracepoint.
  5478.    The match is done by address.  */

  5479. static struct tracepoint *
  5480. ust_marker_to_static_tracepoint (const struct marker *mdata)
  5481. {
  5482.   struct tracepoint *tpoint;

  5483.   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
  5484.     {
  5485.       if (tpoint->type != static_tracepoint)
  5486.         continue;

  5487.       if (tpoint->address == (uintptr_t) mdata->location)
  5488.         return tpoint;
  5489.     }

  5490.   return NULL;
  5491. }

  5492. /* The probe function we install on lttng/ust markers.  Whenever a
  5493.    probed ust marker is hit, this function is called.  This is similar
  5494.    to gdb_collect, only for static tracepoints, instead of fast
  5495.    tracepoints.  */

  5496. static void
  5497. gdb_probe (const struct marker *mdata, void *probe_private,
  5498.            struct registers *regs, void *call_private,
  5499.            const char *fmt, va_list *args)
  5500. {
  5501.   struct tracepoint *tpoint;
  5502.   struct static_tracepoint_ctx ctx;

  5503.   /* Don't do anything until the trace run is completely set up.  */
  5504.   if (!tracing)
  5505.     {
  5506.       trace_debug ("gdb_probe: not tracing\n");
  5507.       return;
  5508.     }

  5509.   ctx.base.type = static_tracepoint;
  5510.   ctx.regcache_initted = 0;
  5511.   ctx.regs = regs;
  5512.   ctx.fmt = fmt;
  5513.   ctx.args = args;

  5514.   /* Wrap the regblock in a register cache (in the stack, we don't
  5515.      want to malloc here).  */
  5516.   ctx.regspace = alloca (ipa_tdesc->registers_size);
  5517.   if (ctx.regspace == NULL)
  5518.     {
  5519.       trace_debug ("Trace buffer block allocation failed, skipping");
  5520.       return;
  5521.     }

  5522.   tpoint = ust_marker_to_static_tracepoint (mdata);
  5523.   if (tpoint == NULL)
  5524.     {
  5525.       trace_debug ("gdb_probe: marker not known: "
  5526.                    "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
  5527.                    mdata->location, mdata->channel,
  5528.                    mdata->name, mdata->format);
  5529.       return;
  5530.     }

  5531.   if (!tpoint->enabled)
  5532.     {
  5533.       trace_debug ("gdb_probe: tracepoint disabled");
  5534.       return;
  5535.     }

  5536.   ctx.tpoint = tpoint;

  5537.   trace_debug ("gdb_probe: collecting marker: "
  5538.                "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
  5539.                mdata->location, mdata->channel,
  5540.                mdata->name, mdata->format);

  5541.   /* Test the condition if present, and collect if true.  */
  5542.   if (tpoint->cond == NULL
  5543.       || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
  5544.                                        tpoint))
  5545.     {
  5546.       collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
  5547.                                   tpoint->address, tpoint);

  5548.       if (stopping_tracepoint
  5549.           || trace_buffer_is_full
  5550.           || expr_eval_result != expr_eval_no_error)
  5551.         stop_tracing ();
  5552.     }
  5553.   else
  5554.     {
  5555.       /* If there was a condition and it evaluated to false, the only
  5556.          way we would stop tracing is if there was an error during
  5557.          condition expression evaluation.  */
  5558.       if (expr_eval_result != expr_eval_no_error)
  5559.         stop_tracing ();
  5560.     }
  5561. }

  5562. /* Called if the gdb static tracepoint requested collecting "$_sdata",
  5563.    static tracepoint string data.  This is a string passed to the
  5564.    tracing library by the user, at the time of the tracepoint marker
  5565.    call.  E.g., in the UST marker call:

  5566.      trace_mark (ust, bar33, "str %s", "FOOBAZ");

  5567.    the collected data is "str FOOBAZ".
  5568. */

  5569. static void
  5570. collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
  5571.                                 struct traceframe *tframe)
  5572. {
  5573.   struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
  5574.   unsigned char *bufspace;
  5575.   int size;
  5576.   va_list copy;
  5577.   unsigned short blocklen;

  5578.   if (umd == NULL)
  5579.     {
  5580.       trace_debug ("Wanted to collect static trace data, "
  5581.                    "but there's no static trace data");
  5582.       return;
  5583.     }

  5584.   va_copy (copy, *umd->args);
  5585.   size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
  5586.   va_end (copy);

  5587.   trace_debug ("Want to collect ust data");

  5588.   /* 'S' + size + string */
  5589.   bufspace = add_traceframe_block (tframe, umd->tpoint,
  5590.                                    1 + sizeof (blocklen) + size + 1);
  5591.   if (bufspace == NULL)
  5592.     {
  5593.       trace_debug ("Trace buffer block allocation failed, skipping");
  5594.       return;
  5595.     }

  5596.   /* Identify a static trace data block.  */
  5597.   *bufspace = 'S';

  5598.   blocklen = size + 1;
  5599.   memcpy (bufspace + 1, &blocklen, sizeof (blocklen));

  5600.   va_copy (copy, *umd->args);
  5601.   USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
  5602.                            size + 1, umd->fmt, copy);
  5603.   va_end (copy);

  5604.   trace_debug ("Storing static tracepoint data in regblock: %s",
  5605.                bufspace + 1 + sizeof (blocklen));
  5606. }

  5607. /* The probe to register with lttng/ust.  */
  5608. static struct ltt_available_probe gdb_ust_probe =
  5609.   {
  5610.     GDB_PROBE_NAME,
  5611.     NULL,
  5612.     gdb_probe,
  5613.   };

  5614. #endif /* HAVE_UST */
  5615. #endif /* IN_PROCESS_AGENT */

  5616. #ifndef IN_PROCESS_AGENT

  5617. /* Ask the in-process agent to run a command.  Since we don't want to
  5618.    have to handle the IPA hitting breakpoints while running the
  5619.    command, we pause all threads, remove all breakpoints, and then set
  5620.    the helper thread re-running.  We communicate with the helper
  5621.    thread by means of direct memory xfering, and a socket for
  5622.    synchronization.  */

  5623. static int
  5624. run_inferior_command (char *cmd, int len)
  5625. {
  5626.   int err = -1;
  5627.   int pid = ptid_get_pid (current_ptid);

  5628.   trace_debug ("run_inferior_command: running: %s", cmd);

  5629.   pause_all (0);
  5630.   uninsert_all_breakpoints ();

  5631.   err = agent_run_command (pid, (const char *) cmd, len);

  5632.   reinsert_all_breakpoints ();
  5633.   unpause_all (0);

  5634.   return err;
  5635. }

  5636. #else /* !IN_PROCESS_AGENT */

  5637. #include <sys/socket.h>
  5638. #include <sys/un.h>

  5639. #ifndef UNIX_PATH_MAX
  5640. #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
  5641. #endif

  5642. /* Where we put the socked used for synchronization.  */
  5643. #define SOCK_DIR P_tmpdir

  5644. /* Thread ID of the helper thread.  GDBserver reads this to know which
  5645.    is the help thread.  This is an LWP id on Linux.  */
  5646. int helper_thread_id;

  5647. static int
  5648. init_named_socket (const char *name)
  5649. {
  5650.   int result, fd;
  5651.   struct sockaddr_un addr;

  5652.   result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
  5653.   if (result == -1)
  5654.     {
  5655.       warning ("socket creation failed: %s", strerror (errno));
  5656.       return -1;
  5657.     }

  5658.   addr.sun_family = AF_UNIX;

  5659.   strncpy (addr.sun_path, name, UNIX_PATH_MAX);
  5660.   addr.sun_path[UNIX_PATH_MAX - 1] = '\0';

  5661.   result = access (name, F_OK);
  5662.   if (result == 0)
  5663.     {
  5664.       /* File exists.  */
  5665.       result = unlink (name);
  5666.       if (result == -1)
  5667.         {
  5668.           warning ("unlink failed: %s", strerror (errno));
  5669.           close (fd);
  5670.           return -1;
  5671.         }
  5672.       warning ("socket %s already exists; overwriting", name);
  5673.     }

  5674.   result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
  5675.   if (result == -1)
  5676.     {
  5677.       warning ("bind failed: %s", strerror (errno));
  5678.       close (fd);
  5679.       return -1;
  5680.     }

  5681.   result = listen (fd, 1);
  5682.   if (result == -1)
  5683.     {
  5684.       warning ("listen: %s", strerror (errno));
  5685.       close (fd);
  5686.       return -1;
  5687.     }

  5688.   return fd;
  5689. }

  5690. static char agent_socket_name[UNIX_PATH_MAX];

  5691. static int
  5692. gdb_agent_socket_init (void)
  5693. {
  5694.   int result, fd;

  5695.   result = xsnprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
  5696.                       SOCK_DIR, getpid ());
  5697.   if (result >= UNIX_PATH_MAX)
  5698.     {
  5699.       trace_debug ("string overflow allocating socket name");
  5700.       return -1;
  5701.     }

  5702.   fd = init_named_socket (agent_socket_name);
  5703.   if (fd < 0)
  5704.     warning ("Error initializing named socket (%s) for communication with the "
  5705.              "ust helper thread. Check that directory exists and that it "
  5706.              "is writable.", agent_socket_name);

  5707.   return fd;
  5708. }

  5709. #ifdef HAVE_UST

  5710. /* The next marker to be returned on a qTsSTM command.  */
  5711. static const struct marker *next_st;

  5712. /* Returns the first known marker.  */

  5713. struct marker *
  5714. first_marker (void)
  5715. {
  5716.   struct marker_iter iter;

  5717.   USTF(marker_iter_reset) (&iter);
  5718.   USTF(marker_iter_start) (&iter);

  5719.   return iter.marker;
  5720. }

  5721. /* Returns the marker following M.  */

  5722. const struct marker *
  5723. next_marker (const struct marker *m)
  5724. {
  5725.   struct marker_iter iter;

  5726.   USTF(marker_iter_reset) (&iter);
  5727.   USTF(marker_iter_start) (&iter);

  5728.   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
  5729.     {
  5730.       if (iter.marker == m)
  5731.         {
  5732.           USTF(marker_iter_next) (&iter);
  5733.           return iter.marker;
  5734.         }
  5735.     }

  5736.   return NULL;
  5737. }

  5738. /* Return an hexstr version of the STR C string, fit for sending to
  5739.    GDB.  */

  5740. static char *
  5741. cstr_to_hexstr (const char *str)
  5742. {
  5743.   int len = strlen (str);
  5744.   char *hexstr = xmalloc (len * 2 + 1);
  5745.   bin2hex ((gdb_byte *) str, hexstr, len);
  5746.   return hexstr;
  5747. }

  5748. /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
  5749.    packets.  */

  5750. static void
  5751. response_ust_marker (char *packet, const struct marker *st)
  5752. {
  5753.   char *strid, *format, *tmp;

  5754.   next_st = next_marker (st);

  5755.   tmp = xmalloc (strlen (st->channel) + 1 +
  5756.                  strlen (st->name) + 1);
  5757.   sprintf (tmp, "%s/%s", st->channel, st->name);

  5758.   strid = cstr_to_hexstr (tmp);
  5759.   free (tmp);

  5760.   format = cstr_to_hexstr (st->format);

  5761.   sprintf (packet, "m%s:%s:%s",
  5762.            paddress ((uintptr_t) st->location),
  5763.            strid,
  5764.            format);

  5765.   free (strid);
  5766.   free (format);
  5767. }

  5768. /* Return the first static tracepoint, and initialize the state
  5769.    machine that will iterate through all the static tracepoints.  */

  5770. static void
  5771. cmd_qtfstm (char *packet)
  5772. {
  5773.   trace_debug ("Returning first trace state variable definition");

  5774.   if (first_marker ())
  5775.     response_ust_marker (packet, first_marker ());
  5776.   else
  5777.     strcpy (packet, "l");
  5778. }

  5779. /* Return additional trace state variable definitions. */

  5780. static void
  5781. cmd_qtsstm (char *packet)
  5782. {
  5783.   trace_debug ("Returning static tracepoint");

  5784.   if (next_st)
  5785.     response_ust_marker (packet, next_st);
  5786.   else
  5787.     strcpy (packet, "l");
  5788. }

  5789. /* Disconnect the GDB probe from a marker at a given address.  */

  5790. static void
  5791. unprobe_marker_at (char *packet)
  5792. {
  5793.   char *p = packet;
  5794.   ULONGEST address;
  5795.   struct marker_iter iter;

  5796.   p += sizeof ("unprobe_marker_at:") - 1;

  5797.   p = unpack_varlen_hex (p, &address);

  5798.   USTF(marker_iter_reset) (&iter);
  5799.   USTF(marker_iter_start) (&iter);
  5800.   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
  5801.     if ((uintptr_t ) iter.marker->location == address)
  5802.       {
  5803.         int result;

  5804.         result = USTF(ltt_marker_disconnect) (iter.marker->channel,
  5805.                                               iter.marker->name,
  5806.                                               GDB_PROBE_NAME);
  5807.         if (result < 0)
  5808.           warning ("could not disable marker %s/%s",
  5809.                    iter.marker->channel, iter.marker->name);
  5810.         break;
  5811.       }
  5812. }

  5813. /* Connect the GDB probe to a marker at a given address.  */

  5814. static int
  5815. probe_marker_at (char *packet)
  5816. {
  5817.   char *p = packet;
  5818.   ULONGEST address;
  5819.   struct marker_iter iter;
  5820.   struct marker *m;

  5821.   p += sizeof ("probe_marker_at:") - 1;

  5822.   p = unpack_varlen_hex (p, &address);

  5823.   USTF(marker_iter_reset) (&iter);

  5824.   for (USTF(marker_iter_start) (&iter), m = iter.marker;
  5825.        m != NULL;
  5826.        USTF(marker_iter_next) (&iter), m = iter.marker)
  5827.     if ((uintptr_t ) m->location == address)
  5828.       {
  5829.         int result;

  5830.         trace_debug ("found marker for address.  "
  5831.                      "ltt_marker_connect (marker = %s/%s)",
  5832.                      m->channel, m->name);

  5833.         result = USTF(ltt_marker_connect) (m->channel, m->name,
  5834.                                            GDB_PROBE_NAME);
  5835.         if (result && result != -EEXIST)
  5836.           trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
  5837.                        m->channel, m->name, -result);

  5838.         if (result < 0)
  5839.           {
  5840.             sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
  5841.                      m->channel, m->name);
  5842.             return -1;
  5843.           }

  5844.         strcpy (packet, "OK");
  5845.         return 0;
  5846.       }

  5847.   sprintf (packet, "E.no marker found at 0x%s", paddress (address));
  5848.   return -1;
  5849. }

  5850. static int
  5851. cmd_qtstmat (char *packet)
  5852. {
  5853.   char *p = packet;
  5854.   ULONGEST address;
  5855.   struct marker_iter iter;
  5856.   struct marker *m;

  5857.   p += sizeof ("qTSTMat:") - 1;

  5858.   p = unpack_varlen_hex (p, &address);

  5859.   USTF(marker_iter_reset) (&iter);

  5860.   for (USTF(marker_iter_start) (&iter), m = iter.marker;
  5861.        m != NULL;
  5862.        USTF(marker_iter_next) (&iter), m = iter.marker)
  5863.     if ((uintptr_t ) m->location == address)
  5864.       {
  5865.         response_ust_marker (packet, m);
  5866.         return 0;
  5867.       }

  5868.   strcpy (packet, "l");
  5869.   return -1;
  5870. }

  5871. static void
  5872. gdb_ust_init (void)
  5873. {
  5874.   if (!dlsym_ust ())
  5875.     return;

  5876.   USTF(ltt_probe_register) (&gdb_ust_probe);
  5877. }

  5878. #endif /* HAVE_UST */

  5879. #include <sys/syscall.h>

  5880. static void
  5881. gdb_agent_remove_socket (void)
  5882. {
  5883.   unlink (agent_socket_name);
  5884. }

  5885. /* Helper thread of agent.  */

  5886. static void *
  5887. gdb_agent_helper_thread (void *arg)
  5888. {
  5889.   int listen_fd;

  5890.   atexit (gdb_agent_remove_socket);

  5891.   while (1)
  5892.     {
  5893.       listen_fd = gdb_agent_socket_init ();

  5894.       if (helper_thread_id == 0)
  5895.         helper_thread_id = syscall (SYS_gettid);

  5896.       if (listen_fd == -1)
  5897.         {
  5898.           warning ("could not create sync socket\n");
  5899.           break;
  5900.         }

  5901.       while (1)
  5902.         {
  5903.           socklen_t tmp;
  5904.           struct sockaddr_un sockaddr;
  5905.           int fd;
  5906.           char buf[1];
  5907.           int ret;
  5908.           int stop_loop = 0;

  5909.           tmp = sizeof (sockaddr);

  5910.           do
  5911.             {
  5912.               fd = accept (listen_fd, &sockaddr, &tmp);
  5913.             }
  5914.           /* It seems an ERESTARTSYS can escape out of accept.  */
  5915.           while (fd == -512 || (fd == -1 && errno == EINTR));

  5916.           if (fd < 0)
  5917.             {
  5918.               warning ("Accept returned %d, error: %s\n",
  5919.                        fd, strerror (errno));
  5920.               break;
  5921.             }

  5922.           do
  5923.             {
  5924.               ret = read (fd, buf, 1);
  5925.             } while (ret == -1 && errno == EINTR);

  5926.           if (ret == -1)
  5927.             {
  5928.               warning ("reading socket (fd=%d) failed with %s",
  5929.                        fd, strerror (errno));
  5930.               close (fd);
  5931.               break;
  5932.             }

  5933.           if (cmd_buf[0])
  5934.             {
  5935.               if (strncmp ("close", cmd_buf, 5) == 0)
  5936.                 {
  5937.                   stop_loop = 1;
  5938.                 }
  5939. #ifdef HAVE_UST
  5940.               else if (strcmp ("qTfSTM", cmd_buf) == 0)
  5941.                 {
  5942.                   cmd_qtfstm (cmd_buf);
  5943.                 }
  5944.               else if (strcmp ("qTsSTM", cmd_buf) == 0)
  5945.                 {
  5946.                   cmd_qtsstm (cmd_buf);
  5947.                 }
  5948.               else if (strncmp ("unprobe_marker_at:",
  5949.                                 cmd_buf,
  5950.                                 sizeof ("unprobe_marker_at:") - 1) == 0)
  5951.                 {
  5952.                   unprobe_marker_at (cmd_buf);
  5953.                 }
  5954.               else if (strncmp ("probe_marker_at:",
  5955.                                 cmd_buf,
  5956.                                 sizeof ("probe_marker_at:") - 1) == 0)
  5957.                 {
  5958.                   probe_marker_at (cmd_buf);
  5959.                 }
  5960.               else if (strncmp ("qTSTMat:",
  5961.                                 cmd_buf,
  5962.                                 sizeof ("qTSTMat:") - 1) == 0)
  5963.                 {
  5964.                   cmd_qtstmat (cmd_buf);
  5965.                 }
  5966. #endif /* HAVE_UST */
  5967.             }

  5968.           /* Fix compiler's warning: ignoring return value of 'write'.  */
  5969.           ret = write (fd, buf, 1);
  5970.           close (fd);

  5971.           if (stop_loop)
  5972.             {
  5973.               close (listen_fd);
  5974.               unlink (agent_socket_name);

  5975.               /* Sleep endlessly to wait the whole inferior stops.  This
  5976.                  thread can not exit because GDB or GDBserver may still need
  5977.                  'current_thread' (representing this thread) to access
  5978.                  inferior memory.  Otherwise, this thread exits earlier than
  5979.                  other threads, and 'current_thread' is set to NULL.  */
  5980.               while (1)
  5981.                 sleep (10);
  5982.             }
  5983.         }
  5984.     }

  5985.   return NULL;
  5986. }

  5987. #include <signal.h>
  5988. #include <pthread.h>

  5989. IP_AGENT_EXPORT int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;

  5990. static void
  5991. gdb_agent_init (void)
  5992. {
  5993.   int res;
  5994.   pthread_t thread;
  5995.   sigset_t new_mask;
  5996.   sigset_t orig_mask;

  5997.   /* We want the helper thread to be as transparent as possible, so
  5998.      have it inherit an all-signals-blocked mask.  */

  5999.   sigfillset (&new_mask);
  6000.   res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
  6001.   if (res)
  6002.     perror_with_name ("pthread_sigmask (1)");

  6003.   res = pthread_create (&thread,
  6004.                         NULL,
  6005.                         gdb_agent_helper_thread,
  6006.                         NULL);

  6007.   res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
  6008.   if (res)
  6009.     perror_with_name ("pthread_sigmask (2)");

  6010.   while (helper_thread_id == 0)
  6011.     usleep (1);

  6012. #ifdef HAVE_UST
  6013.   gdb_ust_init ();
  6014. #endif
  6015. }

  6016. #include <sys/mman.h>
  6017. #include <fcntl.h>

  6018. IP_AGENT_EXPORT char *gdb_tp_heap_buffer;
  6019. IP_AGENT_EXPORT char *gdb_jump_pad_buffer;
  6020. IP_AGENT_EXPORT char *gdb_jump_pad_buffer_end;
  6021. IP_AGENT_EXPORT char *gdb_trampoline_buffer;
  6022. IP_AGENT_EXPORT char *gdb_trampoline_buffer_end;
  6023. IP_AGENT_EXPORT char *gdb_trampoline_buffer_error;

  6024. /* Record the result of getting buffer space for fast tracepoint
  6025.    trampolines.  Any error message is copied, since caller may not be
  6026.    using persistent storage.  */

  6027. void
  6028. set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
  6029. {
  6030.   gdb_trampoline_buffer = (char *) (uintptr_t) begin;
  6031.   gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
  6032.   if (errmsg)
  6033.     strncpy (gdb_trampoline_buffer_error, errmsg, 99);
  6034.   else
  6035.     strcpy (gdb_trampoline_buffer_error, "no buffer passed");
  6036. }

  6037. static void __attribute__ ((constructor))
  6038. initialize_tracepoint_ftlib (void)
  6039. {
  6040.   initialize_tracepoint ();

  6041.   gdb_agent_init ();
  6042. }

  6043. #endif /* IN_PROCESS_AGENT */

  6044. /* Return a timestamp, expressed as microseconds of the usual Unix
  6045.    time.  (As the result is a 64-bit number, it will not overflow any
  6046.    time soon.)  */

  6047. static LONGEST
  6048. get_timestamp (void)
  6049. {
  6050.    struct timeval tv;

  6051.    if (gettimeofday (&tv, 0) != 0)
  6052.      return -1;
  6053.    else
  6054.      return (LONGEST) tv.tv_sec * 1000000 + tv.tv_usec;
  6055. }

  6056. void
  6057. initialize_tracepoint (void)
  6058. {
  6059.   /* Start with the default size.  */
  6060.   init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);

  6061.   /* Wire trace state variable 1 to be the timestamp.  This will be
  6062.      uploaded to GDB upon connection and become one of its trace state
  6063.      variables.  (In case you're wondering, if GDB already has a trace
  6064.      variable numbered 1, it will be renumbered.)  */
  6065.   create_trace_state_variable (1, 0);
  6066.   set_trace_state_variable_name (1, "trace_timestamp");
  6067.   set_trace_state_variable_getter (1, get_timestamp);

  6068. #ifdef IN_PROCESS_AGENT
  6069.   {
  6070.     uintptr_t addr;
  6071.     int pagesize;

  6072.     pagesize = sysconf (_SC_PAGE_SIZE);
  6073.     if (pagesize == -1)
  6074.       perror_with_name ("sysconf");

  6075.     gdb_tp_heap_buffer = xmalloc (5 * 1024 * 1024);

  6076. #define SCRATCH_BUFFER_NPAGES 20

  6077.     /* Allocate scratch buffer aligned on a page boundary, at a low
  6078.        address (close to the main executable's code).  */
  6079.     for (addr = pagesize; addr != 0; addr += pagesize)
  6080.       {
  6081.         gdb_jump_pad_buffer = mmap ((void *) addr, pagesize * SCRATCH_BUFFER_NPAGES,
  6082.                                     PROT_READ | PROT_WRITE | PROT_EXEC,
  6083.                                     MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
  6084.                                     -1, 0);
  6085.         if (gdb_jump_pad_buffer != MAP_FAILED)
  6086.           break;
  6087.       }

  6088.     if (addr == 0)
  6089.       perror_with_name ("mmap");

  6090.     gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + pagesize * SCRATCH_BUFFER_NPAGES;
  6091.   }

  6092.   gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;

  6093.   /* It's not a fatal error for something to go wrong with trampoline
  6094.      buffer setup, but it can be mysterious, so create a channel to
  6095.      report back on what went wrong, using a fixed size since we may
  6096.      not be able to allocate space later when the problem occurs.  */
  6097.   gdb_trampoline_buffer_error = xmalloc (IPA_BUFSIZ);

  6098.   strcpy (gdb_trampoline_buffer_error, "No errors reported");

  6099.   initialize_low_tracepoint ();
  6100. #endif
  6101. }