GDBserver
/home/stan/gdb/src/gdb/gdbserver/tracepoint.c
Go to the documentation of this file.
00001 /* Tracepoint code for remote server for GDB.
00002    Copyright (C) 2009-2013 Free Software Foundation, Inc.
00003 
00004    This file is part of GDB.
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 3 of the License, or
00009    (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00018 
00019 #include "server.h"
00020 #include "tracepoint.h"
00021 #include "gdbthread.h"
00022 #include "agent.h"
00023 
00024 #include <ctype.h>
00025 #include <fcntl.h>
00026 #include <unistd.h>
00027 #include <sys/time.h>
00028 #include <stddef.h>
00029 #include <inttypes.h>
00030 #include <stdint.h>
00031 
00032 #include "ax.h"
00033 #include "tdesc.h"
00034 
00035 #define DEFAULT_TRACE_BUFFER_SIZE 5242880 /* 5*1024*1024 */
00036 
00037 /* This file is built for both GDBserver, and the in-process
00038    agent (IPA), a shared library that includes a tracing agent that is
00039    loaded by the inferior to support fast tracepoints.  Fast
00040    tracepoints (or more accurately, jump based tracepoints) are
00041    implemented by patching the tracepoint location with a jump into a
00042    small trampoline function whose job is to save the register state,
00043    call the in-process tracing agent, and then execute the original
00044    instruction that was under the tracepoint jump (possibly adjusted,
00045    if PC-relative, or some such).
00046 
00047    The current synchronization design is pull based.  That means,
00048    GDBserver does most of the work, by peeking/poking at the inferior
00049    agent's memory directly for downloading tracepoint and associated
00050    objects, and for uploading trace frames.  Whenever the IPA needs
00051    something from GDBserver (trace buffer is full, tracing stopped for
00052    some reason, etc.) the IPA calls a corresponding hook function
00053    where GDBserver has placed a breakpoint.
00054 
00055    Each of the agents has its own trace buffer.  When browsing the
00056    trace frames built from slow and fast tracepoints from GDB (tfind
00057    mode), there's no guarantee the user is seeing the trace frames in
00058    strict chronological creation order, although, GDBserver tries to
00059    keep the order relatively reasonable, by syncing the trace buffers
00060    at appropriate times.
00061 
00062 */
00063 
00064 static void trace_vdebug (const char *, ...) ATTRIBUTE_PRINTF (1, 2);
00065 
00066 static void
00067 trace_vdebug (const char *fmt, ...)
00068 {
00069   char buf[1024];
00070   va_list ap;
00071 
00072   va_start (ap, fmt);
00073   vsprintf (buf, fmt, ap);
00074   fprintf (stderr, PROG "/tracepoint: %s\n", buf);
00075   va_end (ap);
00076 }
00077 
00078 #define trace_debug_1(level, fmt, args...)      \
00079   do {                                          \
00080     if (level <= debug_threads)         \
00081       trace_vdebug ((fmt), ##args);             \
00082   } while (0)
00083 
00084 #define trace_debug(FMT, args...)               \
00085   trace_debug_1 (1, FMT, ##args)
00086 
00087 #if defined(__GNUC__)
00088 #  define ATTR_USED __attribute__((used))
00089 #  define ATTR_NOINLINE __attribute__((noinline))
00090 #  define ATTR_CONSTRUCTOR __attribute__ ((constructor))
00091 #else
00092 #  define ATTR_USED
00093 #  define ATTR_NOINLINE
00094 #  define ATTR_CONSTRUCTOR
00095 #endif
00096 
00097 /* Make sure the functions the IPA needs to export (symbols GDBserver
00098    needs to query GDB about) are exported.  */
00099 
00100 #ifdef IN_PROCESS_AGENT
00101 # if defined _WIN32 || defined __CYGWIN__
00102 #   define IP_AGENT_EXPORT __declspec(dllexport) ATTR_USED
00103 # else
00104 #   if __GNUC__ >= 4
00105 #     define IP_AGENT_EXPORT \
00106   __attribute__ ((visibility("default"))) ATTR_USED
00107 #   else
00108 #     define IP_AGENT_EXPORT ATTR_USED
00109 #   endif
00110 # endif
00111 #else
00112 #  define IP_AGENT_EXPORT
00113 #endif
00114 
00115 /* Prefix exported symbols, for good citizenship.  All the symbols
00116    that need exporting are defined in this module.  */
00117 #ifdef IN_PROCESS_AGENT
00118 # define gdb_tp_heap_buffer gdb_agent_gdb_tp_heap_buffer
00119 # define gdb_jump_pad_buffer gdb_agent_gdb_jump_pad_buffer
00120 # define gdb_jump_pad_buffer_end gdb_agent_gdb_jump_pad_buffer_end
00121 # define gdb_trampoline_buffer gdb_agent_gdb_trampoline_buffer
00122 # define gdb_trampoline_buffer_end gdb_agent_gdb_trampoline_buffer_end
00123 # define gdb_trampoline_buffer_error gdb_agent_gdb_trampoline_buffer_error
00124 # define collecting gdb_agent_collecting
00125 # define gdb_collect gdb_agent_gdb_collect
00126 # define stop_tracing gdb_agent_stop_tracing
00127 # define flush_trace_buffer gdb_agent_flush_trace_buffer
00128 # define about_to_request_buffer_space gdb_agent_about_to_request_buffer_space
00129 # define trace_buffer_is_full gdb_agent_trace_buffer_is_full
00130 # define stopping_tracepoint gdb_agent_stopping_tracepoint
00131 # define expr_eval_result gdb_agent_expr_eval_result
00132 # define error_tracepoint gdb_agent_error_tracepoint
00133 # define tracepoints gdb_agent_tracepoints
00134 # define tracing gdb_agent_tracing
00135 # define trace_buffer_ctrl gdb_agent_trace_buffer_ctrl
00136 # define trace_buffer_ctrl_curr gdb_agent_trace_buffer_ctrl_curr
00137 # define trace_buffer_lo gdb_agent_trace_buffer_lo
00138 # define trace_buffer_hi gdb_agent_trace_buffer_hi
00139 # define traceframe_read_count gdb_agent_traceframe_read_count
00140 # define traceframe_write_count gdb_agent_traceframe_write_count
00141 # define traceframes_created gdb_agent_traceframes_created
00142 # define trace_state_variables gdb_agent_trace_state_variables
00143 # define get_raw_reg gdb_agent_get_raw_reg
00144 # define get_trace_state_variable_value \
00145   gdb_agent_get_trace_state_variable_value
00146 # define set_trace_state_variable_value \
00147   gdb_agent_set_trace_state_variable_value
00148 # define ust_loaded gdb_agent_ust_loaded
00149 # define helper_thread_id gdb_agent_helper_thread_id
00150 # define cmd_buf gdb_agent_cmd_buf
00151 #endif
00152 
00153 #ifndef IN_PROCESS_AGENT
00154 
00155 /* Addresses of in-process agent's symbols GDBserver cares about.  */
00156 
00157 struct ipa_sym_addresses
00158 {
00159   CORE_ADDR addr_gdb_tp_heap_buffer;
00160   CORE_ADDR addr_gdb_jump_pad_buffer;
00161   CORE_ADDR addr_gdb_jump_pad_buffer_end;
00162   CORE_ADDR addr_gdb_trampoline_buffer;
00163   CORE_ADDR addr_gdb_trampoline_buffer_end;
00164   CORE_ADDR addr_gdb_trampoline_buffer_error;
00165   CORE_ADDR addr_collecting;
00166   CORE_ADDR addr_gdb_collect;
00167   CORE_ADDR addr_stop_tracing;
00168   CORE_ADDR addr_flush_trace_buffer;
00169   CORE_ADDR addr_about_to_request_buffer_space;
00170   CORE_ADDR addr_trace_buffer_is_full;
00171   CORE_ADDR addr_stopping_tracepoint;
00172   CORE_ADDR addr_expr_eval_result;
00173   CORE_ADDR addr_error_tracepoint;
00174   CORE_ADDR addr_tracepoints;
00175   CORE_ADDR addr_tracing;
00176   CORE_ADDR addr_trace_buffer_ctrl;
00177   CORE_ADDR addr_trace_buffer_ctrl_curr;
00178   CORE_ADDR addr_trace_buffer_lo;
00179   CORE_ADDR addr_trace_buffer_hi;
00180   CORE_ADDR addr_traceframe_read_count;
00181   CORE_ADDR addr_traceframe_write_count;
00182   CORE_ADDR addr_traceframes_created;
00183   CORE_ADDR addr_trace_state_variables;
00184   CORE_ADDR addr_get_raw_reg;
00185   CORE_ADDR addr_get_trace_state_variable_value;
00186   CORE_ADDR addr_set_trace_state_variable_value;
00187   CORE_ADDR addr_ust_loaded;
00188 };
00189 
00190 static struct
00191 {
00192   const char *name;
00193   int offset;
00194   int required;
00195 } symbol_list[] = {
00196   IPA_SYM(gdb_tp_heap_buffer),
00197   IPA_SYM(gdb_jump_pad_buffer),
00198   IPA_SYM(gdb_jump_pad_buffer_end),
00199   IPA_SYM(gdb_trampoline_buffer),
00200   IPA_SYM(gdb_trampoline_buffer_end),
00201   IPA_SYM(gdb_trampoline_buffer_error),
00202   IPA_SYM(collecting),
00203   IPA_SYM(gdb_collect),
00204   IPA_SYM(stop_tracing),
00205   IPA_SYM(flush_trace_buffer),
00206   IPA_SYM(about_to_request_buffer_space),
00207   IPA_SYM(trace_buffer_is_full),
00208   IPA_SYM(stopping_tracepoint),
00209   IPA_SYM(expr_eval_result),
00210   IPA_SYM(error_tracepoint),
00211   IPA_SYM(tracepoints),
00212   IPA_SYM(tracing),
00213   IPA_SYM(trace_buffer_ctrl),
00214   IPA_SYM(trace_buffer_ctrl_curr),
00215   IPA_SYM(trace_buffer_lo),
00216   IPA_SYM(trace_buffer_hi),
00217   IPA_SYM(traceframe_read_count),
00218   IPA_SYM(traceframe_write_count),
00219   IPA_SYM(traceframes_created),
00220   IPA_SYM(trace_state_variables),
00221   IPA_SYM(get_raw_reg),
00222   IPA_SYM(get_trace_state_variable_value),
00223   IPA_SYM(set_trace_state_variable_value),
00224   IPA_SYM(ust_loaded),
00225 };
00226 
00227 static struct ipa_sym_addresses ipa_sym_addrs;
00228 
00229 static int read_inferior_integer (CORE_ADDR symaddr, int *val);
00230 
00231 /* Returns true if both the in-process agent library and the static
00232    tracepoints libraries are loaded in the inferior, and agent has
00233    capability on static tracepoints.  */
00234 
00235 static int
00236 in_process_agent_supports_ust (void)
00237 {
00238   int loaded = 0;
00239 
00240   if (!agent_loaded_p ())
00241     {
00242       warning ("In-process agent not loaded");
00243       return 0;
00244     }
00245 
00246   if (agent_capability_check (AGENT_CAPA_STATIC_TRACE))
00247     {
00248       /* Agent understands static tracepoint, then check whether UST is in
00249          fact loaded in the inferior.  */
00250       if (read_inferior_integer (ipa_sym_addrs.addr_ust_loaded, &loaded))
00251         {
00252           warning ("Error reading ust_loaded in lib");
00253           return 0;
00254         }
00255 
00256       return loaded;
00257     }
00258   else
00259     return 0;
00260 }
00261 
00262 static void
00263 write_e_ipa_not_loaded (char *buffer)
00264 {
00265   sprintf (buffer,
00266            "E.In-process agent library not loaded in process.  "
00267            "Fast and static tracepoints unavailable.");
00268 }
00269 
00270 /* Write an error to BUFFER indicating that UST isn't loaded in the
00271    inferior.  */
00272 
00273 static void
00274 write_e_ust_not_loaded (char *buffer)
00275 {
00276 #ifdef HAVE_UST
00277   sprintf (buffer,
00278            "E.UST library not loaded in process.  "
00279            "Static tracepoints unavailable.");
00280 #else
00281   sprintf (buffer, "E.GDBserver was built without static tracepoints support");
00282 #endif
00283 }
00284 
00285 /* If the in-process agent library isn't loaded in the inferior, write
00286    an error to BUFFER, and return 1.  Otherwise, return 0.  */
00287 
00288 static int
00289 maybe_write_ipa_not_loaded (char *buffer)
00290 {
00291   if (!agent_loaded_p ())
00292     {
00293       write_e_ipa_not_loaded (buffer);
00294       return 1;
00295     }
00296   return 0;
00297 }
00298 
00299 /* If the in-process agent library and the ust (static tracepoints)
00300    library aren't loaded in the inferior, write an error to BUFFER,
00301    and return 1.  Otherwise, return 0.  */
00302 
00303 static int
00304 maybe_write_ipa_ust_not_loaded (char *buffer)
00305 {
00306   if (!agent_loaded_p ())
00307     {
00308       write_e_ipa_not_loaded (buffer);
00309       return 1;
00310     }
00311   else if (!in_process_agent_supports_ust ())
00312     {
00313       write_e_ust_not_loaded (buffer);
00314       return 1;
00315     }
00316   return 0;
00317 }
00318 
00319 /* Cache all future symbols that the tracepoints module might request.
00320    We can not request symbols at arbitrary states in the remote
00321    protocol, only when the client tells us that new symbols are
00322    available.  So when we load the in-process library, make sure to
00323    check the entire list.  */
00324 
00325 void
00326 tracepoint_look_up_symbols (void)
00327 {
00328   int i;
00329 
00330   if (agent_loaded_p ())
00331     return;
00332 
00333   for (i = 0; i < sizeof (symbol_list) / sizeof (symbol_list[0]); i++)
00334     {
00335       CORE_ADDR *addrp =
00336         (CORE_ADDR *) ((char *) &ipa_sym_addrs + symbol_list[i].offset);
00337 
00338       if (look_up_one_symbol (symbol_list[i].name, addrp, 1) == 0)
00339         {
00340           if (debug_threads)
00341             fprintf (stderr, "symbol `%s' not found\n", symbol_list[i].name);
00342           return;
00343         }
00344     }
00345 
00346   agent_look_up_symbols (NULL);
00347 }
00348 
00349 #endif
00350 
00351 /* GDBserver places a breakpoint on the IPA's version (which is a nop)
00352    of the "stop_tracing" function.  When this breakpoint is hit,
00353    tracing stopped in the IPA for some reason.  E.g., due to
00354    tracepoint reaching the pass count, hitting conditional expression
00355    evaluation error, etc.
00356 
00357    The IPA's trace buffer is never in circular tracing mode: instead,
00358    GDBserver's is, and whenever the in-process buffer fills, it calls
00359    "flush_trace_buffer", which triggers an internal breakpoint.
00360    GDBserver reacts to this breakpoint by pulling the meanwhile
00361    collected data.  Old frames discarding is always handled on the
00362    GDBserver side.  */
00363 
00364 #ifdef IN_PROCESS_AGENT
00365 int
00366 read_inferior_memory (CORE_ADDR memaddr, unsigned char *myaddr, int len)
00367 {
00368   memcpy (myaddr, (void *) (uintptr_t) memaddr, len);
00369   return 0;
00370 }
00371 
00372 /* Call this in the functions where GDBserver places a breakpoint, so
00373    that the compiler doesn't try to be clever and skip calling the
00374    function at all.  This is necessary, even if we tell the compiler
00375    to not inline said functions.  */
00376 
00377 #if defined(__GNUC__)
00378 #  define UNKNOWN_SIDE_EFFECTS() asm ("")
00379 #else
00380 #  define UNKNOWN_SIDE_EFFECTS() do {} while (0)
00381 #endif
00382 
00383 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
00384 stop_tracing (void)
00385 {
00386   /* GDBserver places breakpoint here.  */
00387   UNKNOWN_SIDE_EFFECTS();
00388 }
00389 
00390 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
00391 flush_trace_buffer (void)
00392 {
00393   /* GDBserver places breakpoint here.  */
00394   UNKNOWN_SIDE_EFFECTS();
00395 }
00396 
00397 #endif
00398 
00399 #ifndef IN_PROCESS_AGENT
00400 static int
00401 tracepoint_handler (CORE_ADDR address)
00402 {
00403   trace_debug ("tracepoint_handler: tracepoint at 0x%s hit",
00404                paddress (address));
00405   return 0;
00406 }
00407 
00408 /* Breakpoint at "stop_tracing" in the inferior lib.  */
00409 struct breakpoint *stop_tracing_bkpt;
00410 static int stop_tracing_handler (CORE_ADDR);
00411 
00412 /* Breakpoint at "flush_trace_buffer" in the inferior lib.  */
00413 struct breakpoint *flush_trace_buffer_bkpt;
00414 static int flush_trace_buffer_handler (CORE_ADDR);
00415 
00416 static void download_trace_state_variables (void);
00417 static void upload_fast_traceframes (void);
00418 
00419 static int run_inferior_command (char *cmd, int len);
00420 
00421 static int
00422 read_inferior_integer (CORE_ADDR symaddr, int *val)
00423 {
00424   return read_inferior_memory (symaddr, (unsigned char *) val,
00425                                sizeof (*val));
00426 }
00427 
00428 struct tracepoint;
00429 static int tracepoint_send_agent (struct tracepoint *tpoint);
00430 
00431 static int
00432 read_inferior_uinteger (CORE_ADDR symaddr, unsigned int *val)
00433 {
00434   return read_inferior_memory (symaddr, (unsigned char *) val,
00435                                sizeof (*val));
00436 }
00437 
00438 static int
00439 read_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR *val)
00440 {
00441   void *pval = (void *) (uintptr_t) val;
00442   int ret;
00443 
00444   ret = read_inferior_memory (symaddr, (unsigned char *) &pval, sizeof (pval));
00445   *val = (uintptr_t) pval;
00446   return ret;
00447 }
00448 
00449 static int
00450 write_inferior_data_pointer (CORE_ADDR symaddr, CORE_ADDR val)
00451 {
00452   void *pval = (void *) (uintptr_t) val;
00453   return write_inferior_memory (symaddr,
00454                                 (unsigned char *) &pval, sizeof (pval));
00455 }
00456 
00457 static int
00458 write_inferior_integer (CORE_ADDR symaddr, int val)
00459 {
00460   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
00461 }
00462 
00463 static int
00464 write_inferior_uinteger (CORE_ADDR symaddr, unsigned int val)
00465 {
00466   return write_inferior_memory (symaddr, (unsigned char *) &val, sizeof (val));
00467 }
00468 
00469 static CORE_ADDR target_malloc (ULONGEST size);
00470 static int write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr);
00471 
00472 #define COPY_FIELD_TO_BUF(BUF, OBJ, FIELD)      \
00473   do {                                                  \
00474     memcpy (BUF, &(OBJ)->FIELD, sizeof ((OBJ)->FIELD)); \
00475     BUF += sizeof ((OBJ)->FIELD);                       \
00476   } while (0)
00477 
00478 #endif
00479 
00480 /* Operations on various types of tracepoint actions.  */
00481 
00482 struct tracepoint_action;
00483 
00484 struct tracepoint_action_ops
00485 {
00486   /* Download tracepoint action ACTION to IPA.  Return the address of action
00487      in IPA/inferior.  */
00488   CORE_ADDR (*download) (const struct tracepoint_action *action);
00489 
00490   /* Send ACTION to agent via command buffer started from BUFFER.  Return
00491      updated head of command buffer.  */
00492   char* (*send) (char *buffer, const struct tracepoint_action *action);
00493 };
00494 
00495 /* Base action.  Concrete actions inherit this.  */
00496 
00497 struct tracepoint_action
00498 {
00499 #ifndef IN_PROCESS_AGENT
00500   const struct tracepoint_action_ops *ops;
00501 #endif
00502   char type;
00503 };
00504 
00505 /* An 'M' (collect memory) action.  */
00506 struct collect_memory_action
00507 {
00508   struct tracepoint_action base;
00509 
00510   ULONGEST addr;
00511   ULONGEST len;
00512   int32_t basereg;
00513 };
00514 
00515 /* An 'R' (collect registers) action.  */
00516 
00517 struct collect_registers_action
00518 {
00519   struct tracepoint_action base;
00520 };
00521 
00522 /* An 'X' (evaluate expression) action.  */
00523 
00524 struct eval_expr_action
00525 {
00526   struct tracepoint_action base;
00527 
00528   struct agent_expr *expr;
00529 };
00530 
00531 /* An 'L' (collect static trace data) action.  */
00532 struct collect_static_trace_data_action
00533 {
00534   struct tracepoint_action base;
00535 };
00536 
00537 #ifndef IN_PROCESS_AGENT
00538 static CORE_ADDR
00539 m_tracepoint_action_download (const struct tracepoint_action *action)
00540 {
00541   int size_in_ipa = (sizeof (struct collect_memory_action)
00542                      - offsetof (struct tracepoint_action, type));
00543   CORE_ADDR ipa_action = target_malloc (size_in_ipa);
00544 
00545   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
00546                          size_in_ipa);
00547 
00548   return ipa_action;
00549 }
00550 static char *
00551 m_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
00552 {
00553   struct collect_memory_action *maction
00554     = (struct collect_memory_action *) action;
00555 
00556   COPY_FIELD_TO_BUF (buffer, maction, addr);
00557   COPY_FIELD_TO_BUF (buffer, maction, len);
00558   COPY_FIELD_TO_BUF (buffer, maction, basereg);
00559 
00560   return buffer;
00561 }
00562 
00563 static const struct tracepoint_action_ops m_tracepoint_action_ops =
00564 {
00565   m_tracepoint_action_download,
00566   m_tracepoint_action_send,
00567 };
00568 
00569 static CORE_ADDR
00570 r_tracepoint_action_download (const struct tracepoint_action *action)
00571 {
00572   int size_in_ipa = (sizeof (struct collect_registers_action)
00573                      - offsetof (struct tracepoint_action, type));
00574   CORE_ADDR ipa_action  = target_malloc (size_in_ipa);
00575 
00576   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
00577                         size_in_ipa);
00578 
00579   return ipa_action;
00580 }
00581 
00582 static char *
00583 r_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
00584 {
00585   return buffer;
00586 }
00587 
00588 static const struct tracepoint_action_ops r_tracepoint_action_ops =
00589 {
00590   r_tracepoint_action_download,
00591   r_tracepoint_action_send,
00592 };
00593 
00594 static CORE_ADDR download_agent_expr (struct agent_expr *expr);
00595 
00596 static CORE_ADDR
00597 x_tracepoint_action_download (const struct tracepoint_action *action)
00598 {
00599   int size_in_ipa = (sizeof (struct eval_expr_action)
00600                      - offsetof (struct tracepoint_action, type));
00601   CORE_ADDR ipa_action = target_malloc (size_in_ipa);
00602   CORE_ADDR expr;
00603 
00604   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
00605                          size_in_ipa);
00606   expr = download_agent_expr (((struct eval_expr_action *)action)->expr);
00607   write_inferior_data_ptr (ipa_action + offsetof (struct eval_expr_action, expr)
00608                            - offsetof (struct tracepoint_action, type),
00609                            expr);
00610 
00611   return ipa_action;
00612 }
00613 
00614 /* Copy agent expression AEXPR to buffer pointed by P.  If AEXPR is NULL,
00615    copy 0 to P.  Return updated header of buffer.  */
00616 
00617 static char *
00618 agent_expr_send (char *p, const struct agent_expr *aexpr)
00619 {
00620   /* Copy the length of condition first, and then copy its
00621      content.  */
00622   if (aexpr == NULL)
00623     {
00624       memset (p, 0, 4);
00625       p += 4;
00626     }
00627   else
00628     {
00629       memcpy (p, &aexpr->length, 4);
00630       p +=4;
00631 
00632       memcpy (p, aexpr->bytes, aexpr->length);
00633       p += aexpr->length;
00634     }
00635   return p;
00636 }
00637 
00638 static char *
00639 x_tracepoint_action_send ( char *buffer, const struct tracepoint_action *action)
00640 {
00641   struct eval_expr_action *eaction = (struct eval_expr_action *) action;
00642 
00643   return agent_expr_send (buffer, eaction->expr);
00644 }
00645 
00646 static const struct tracepoint_action_ops x_tracepoint_action_ops =
00647 {
00648   x_tracepoint_action_download,
00649   x_tracepoint_action_send,
00650 };
00651 
00652 static CORE_ADDR
00653 l_tracepoint_action_download (const struct tracepoint_action *action)
00654 {
00655   int size_in_ipa = (sizeof (struct collect_static_trace_data_action)
00656                      - offsetof (struct tracepoint_action, type));
00657   CORE_ADDR ipa_action = target_malloc (size_in_ipa);
00658 
00659   write_inferior_memory (ipa_action, (unsigned char *) &action->type,
00660                          size_in_ipa);
00661 
00662   return ipa_action;
00663 }
00664 
00665 static char *
00666 l_tracepoint_action_send (char *buffer, const struct tracepoint_action *action)
00667 {
00668   return buffer;
00669 }
00670 
00671 static const struct tracepoint_action_ops l_tracepoint_action_ops =
00672 {
00673   l_tracepoint_action_download,
00674   l_tracepoint_action_send,
00675 };
00676 #endif
00677 
00678 /* This structure describes a piece of the source-level definition of
00679    the tracepoint.  The contents are not interpreted by the target,
00680    but preserved verbatim for uploading upon reconnection.  */
00681 
00682 struct source_string
00683 {
00684   /* The type of string, such as "cond" for a conditional.  */
00685   char *type;
00686 
00687   /* The source-level string itself.  For the sake of target
00688      debugging, we store it in plaintext, even though it is always
00689      transmitted in hex.  */
00690   char *str;
00691 
00692   /* Link to the next one in the list.  We link them in the order
00693      received, in case some make up an ordered list of commands or
00694      some such.  */
00695   struct source_string *next;
00696 };
00697 
00698 enum tracepoint_type
00699 {
00700   /* Trap based tracepoint.  */
00701   trap_tracepoint,
00702 
00703   /* A fast tracepoint implemented with a jump instead of a trap.  */
00704   fast_tracepoint,
00705 
00706   /* A static tracepoint, implemented by a program call into a tracing
00707      library.  */
00708   static_tracepoint
00709 };
00710 
00711 struct tracepoint_hit_ctx;
00712 
00713 typedef enum eval_result_type (*condfn) (struct tracepoint_hit_ctx *,
00714                                          ULONGEST *);
00715 
00716 /* The definition of a tracepoint.  */
00717 
00718 /* Tracepoints may have multiple locations, each at a different
00719    address.  This can occur with optimizations, template
00720    instantiation, etc.  Since the locations may be in different
00721    scopes, the conditions and actions may be different for each
00722    location.  Our target version of tracepoints is more like GDB's
00723    notion of "breakpoint locations", but we have almost nothing that
00724    is not per-location, so we bother having two kinds of objects.  The
00725    key consequence is that numbers are not unique, and that it takes
00726    both number and address to identify a tracepoint uniquely.  */
00727 
00728 struct tracepoint
00729 {
00730   /* The number of the tracepoint, as specified by GDB.  Several
00731      tracepoint objects here may share a number.  */
00732   uint32_t number;
00733 
00734   /* Address at which the tracepoint is supposed to trigger.  Several
00735      tracepoints may share an address.  */
00736   CORE_ADDR address;
00737 
00738   /* Tracepoint type.  */
00739   enum tracepoint_type type;
00740 
00741   /* True if the tracepoint is currently enabled.  */
00742   int8_t enabled;
00743 
00744   /* The number of single steps that will be performed after each
00745      tracepoint hit.  */
00746   uint64_t step_count;
00747 
00748   /* The number of times the tracepoint may be hit before it will
00749      terminate the entire tracing run.  */
00750   uint64_t pass_count;
00751 
00752   /* Pointer to the agent expression that is the tracepoint's
00753      conditional, or NULL if the tracepoint is unconditional.  */
00754   struct agent_expr *cond;
00755 
00756   /* The list of actions to take when the tracepoint triggers.  */
00757   uint32_t numactions;
00758   struct tracepoint_action **actions;
00759 
00760   /* Count of the times we've hit this tracepoint during the run.
00761      Note that while-stepping steps are not counted as "hits".  */
00762   uint64_t hit_count;
00763 
00764   /* Cached sum of the sizes of traceframes created by this point.  */
00765   uint64_t traceframe_usage;
00766 
00767   CORE_ADDR compiled_cond;
00768 
00769   /* Link to the next tracepoint in the list.  */
00770   struct tracepoint *next;
00771 
00772 #ifndef IN_PROCESS_AGENT
00773   /* The list of actions to take when the tracepoint triggers, in
00774      string/packet form.  */
00775   char **actions_str;
00776 
00777   /* The collection of strings that describe the tracepoint as it was
00778      entered into GDB.  These are not used by the target, but are
00779      reported back to GDB upon reconnection.  */
00780   struct source_string *source_strings;
00781 
00782   /* The number of bytes displaced by fast tracepoints. It may subsume
00783      multiple instructions, for multi-byte fast tracepoints.  This
00784      field is only valid for fast tracepoints.  */
00785   uint32_t orig_size;
00786 
00787   /* Only for fast tracepoints.  */
00788   CORE_ADDR obj_addr_on_target;
00789 
00790   /* Address range where the original instruction under a fast
00791      tracepoint was relocated to.  (_end is actually one byte past
00792      the end).  */
00793   CORE_ADDR adjusted_insn_addr;
00794   CORE_ADDR adjusted_insn_addr_end;
00795 
00796   /* The address range of the piece of the jump pad buffer that was
00797      assigned to this fast tracepoint.  (_end is actually one byte
00798      past the end).*/
00799   CORE_ADDR jump_pad;
00800   CORE_ADDR jump_pad_end;
00801 
00802   /* The address range of the piece of the trampoline buffer that was
00803      assigned to this fast tracepoint.  (_end is actually one byte
00804      past the end).  */
00805   CORE_ADDR trampoline;
00806   CORE_ADDR trampoline_end;
00807 
00808   /* The list of actions to take while in a stepping loop.  These
00809      fields are only valid for patch-based tracepoints.  */
00810   int num_step_actions;
00811   struct tracepoint_action **step_actions;
00812   /* Same, but in string/packet form.  */
00813   char **step_actions_str;
00814 
00815   /* Handle returned by the breakpoint or tracepoint module when we
00816      inserted the trap or jump, or hooked into a static tracepoint.
00817      NULL if we haven't inserted it yet.  */
00818   void *handle;
00819 #endif
00820 
00821 };
00822 
00823 #ifndef IN_PROCESS_AGENT
00824 
00825 /* Given `while-stepping', a thread may be collecting data for more
00826    than one tracepoint simultaneously.  On the other hand, the same
00827    tracepoint with a while-stepping action may be hit by more than one
00828    thread simultaneously (but not quite, each thread could be handling
00829    a different step).  Each thread holds a list of these objects,
00830    representing the current step of each while-stepping action being
00831    collected.  */
00832 
00833 struct wstep_state
00834 {
00835   struct wstep_state *next;
00836 
00837   /* The tracepoint number.  */
00838   int tp_number;
00839   /* The tracepoint's address.  */
00840   CORE_ADDR tp_address;
00841 
00842   /* The number of the current step in this 'while-stepping'
00843      action.  */
00844   long current_step;
00845 };
00846 
00847 #endif
00848 
00849 /* The linked list of all tracepoints.  Marked explicitly as used as
00850    the in-process library doesn't use it for the fast tracepoints
00851    support.  */
00852 IP_AGENT_EXPORT struct tracepoint *tracepoints ATTR_USED;
00853 
00854 #ifndef IN_PROCESS_AGENT
00855 
00856 /* Pointer to the last tracepoint in the list, new tracepoints are
00857    linked in at the end.  */
00858 
00859 static struct tracepoint *last_tracepoint;
00860 #endif
00861 
00862 /* The first tracepoint to exceed its pass count.  */
00863 
00864 IP_AGENT_EXPORT struct tracepoint *stopping_tracepoint;
00865 
00866 /* True if the trace buffer is full or otherwise no longer usable.  */
00867 
00868 IP_AGENT_EXPORT int trace_buffer_is_full;
00869 
00870 static enum eval_result_type expr_eval_result = expr_eval_no_error;
00871 
00872 #ifndef IN_PROCESS_AGENT
00873 
00874 static const char *eval_result_names[] =
00875   {
00876     "terror:in the attic",  /* this should never be reported */
00877     "terror:empty expression",
00878     "terror:empty stack",
00879     "terror:stack overflow",
00880     "terror:stack underflow",
00881     "terror:unhandled opcode",
00882     "terror:unrecognized opcode",
00883     "terror:divide by zero"
00884   };
00885 
00886 #endif
00887 
00888 /* The tracepoint in which the error occurred.  */
00889 
00890 static struct tracepoint *error_tracepoint;
00891 
00892 struct trace_state_variable
00893 {
00894   /* This is the name of the variable as used in GDB.  The target
00895      doesn't use the name, but needs to have it for saving and
00896      reconnection purposes.  */
00897   char *name;
00898 
00899   /* This number identifies the variable uniquely.  Numbers may be
00900      assigned either by the target (in the case of builtin variables),
00901      or by GDB, and are presumed unique during the course of a trace
00902      experiment.  */
00903   int number;
00904 
00905   /* The variable's initial value, a 64-bit signed integer always.  */
00906   LONGEST initial_value;
00907 
00908   /* The variable's value, a 64-bit signed integer always.  */
00909   LONGEST value;
00910 
00911   /* Pointer to a getter function, used to supply computed values.  */
00912   LONGEST (*getter) (void);
00913 
00914   /* Link to the next variable.  */
00915   struct trace_state_variable *next;
00916 };
00917 
00918 /* Linked list of all trace state variables.  */
00919 
00920 #ifdef IN_PROCESS_AGENT
00921 struct trace_state_variable *alloced_trace_state_variables;
00922 #endif
00923 
00924 IP_AGENT_EXPORT struct trace_state_variable *trace_state_variables;
00925 
00926 /* The results of tracing go into a fixed-size space known as the
00927    "trace buffer".  Because usage follows a limited number of
00928    patterns, we manage it ourselves rather than with malloc.  Basic
00929    rules are that we create only one trace frame at a time, each is
00930    variable in size, they are never moved once created, and we only
00931    discard if we are doing a circular buffer, and then only the oldest
00932    ones.  Each trace frame includes its own size, so we don't need to
00933    link them together, and the trace frame number is relative to the
00934    first one, so we don't need to record numbers.  A trace frame also
00935    records the number of the tracepoint that created it.  The data
00936    itself is a series of blocks, each introduced by a single character
00937    and with a defined format.  Each type of block has enough
00938    type/length info to allow scanners to jump quickly from one block
00939    to the next without reading each byte in the block.  */
00940 
00941 /* Trace buffer management would be simple - advance a free pointer
00942    from beginning to end, then stop - were it not for the circular
00943    buffer option, which is a useful way to prevent a trace run from
00944    stopping prematurely because the buffer filled up.  In the circular
00945    case, the location of the first trace frame (trace_buffer_start)
00946    moves as old trace frames are discarded.  Also, since we grow trace
00947    frames incrementally as actions are performed, we wrap around to
00948    the beginning of the trace buffer.  This is per-block, so each
00949    block within a trace frame remains contiguous.  Things get messy
00950    when the wrapped-around trace frame is the one being discarded; the
00951    free space ends up in two parts at opposite ends of the buffer.  */
00952 
00953 #ifndef ATTR_PACKED
00954 #  if defined(__GNUC__)
00955 #    define ATTR_PACKED __attribute__ ((packed))
00956 #  else
00957 #    define ATTR_PACKED /* nothing */
00958 #  endif
00959 #endif
00960 
00961 /* The data collected at a tracepoint hit.  This object should be as
00962    small as possible, since there may be a great many of them.  We do
00963    not need to keep a frame number, because they are all sequential
00964    and there are no deletions; so the Nth frame in the buffer is
00965    always frame number N.  */
00966 
00967 struct traceframe
00968 {
00969   /* Number of the tracepoint that collected this traceframe.  A value
00970      of 0 indicates the current end of the trace buffer.  We make this
00971      a 16-bit field because it's never going to happen that GDB's
00972      numbering of tracepoints reaches 32,000.  */
00973   int tpnum : 16;
00974 
00975   /* The size of the data in this trace frame.  We limit this to 32
00976      bits, even on a 64-bit target, because it's just implausible that
00977      one is validly going to collect 4 gigabytes of data at a single
00978      tracepoint hit.  */
00979   unsigned int data_size : 32;
00980 
00981   /* The base of the trace data, which is contiguous from this point.  */
00982   unsigned char data[0];
00983 
00984 } ATTR_PACKED;
00985 
00986 /* The size of the EOB marker, in bytes.  A traceframe with zeroed
00987    fields (and no data) marks the end of trace data.  */
00988 #define TRACEFRAME_EOB_MARKER_SIZE offsetof (struct traceframe, data)
00989 
00990 /* The traceframe to be used as the source of data to send back to
00991    GDB.  A value of -1 means to get data from the live program.  */
00992 
00993 int current_traceframe = -1;
00994 
00995 /* This flag is true if the trace buffer is circular, meaning that
00996    when it fills, the oldest trace frames are discarded in order to
00997    make room.  */
00998 
00999 #ifndef IN_PROCESS_AGENT
01000 static int circular_trace_buffer;
01001 #endif
01002 
01003 /* Size of the trace buffer.  */
01004 
01005 static LONGEST trace_buffer_size;
01006 
01007 /* Pointer to the block of memory that traceframes all go into.  */
01008 
01009 static unsigned char *trace_buffer_lo;
01010 
01011 /* Pointer to the end of the trace buffer, more precisely to the byte
01012    after the end of the buffer.  */
01013 
01014 static unsigned char *trace_buffer_hi;
01015 
01016 /* Control structure holding the read/write/etc. pointers into the
01017    trace buffer.  We need more than one of these to implement a
01018    transaction-like mechanism to garantees that both GDBserver and the
01019    in-process agent can try to change the trace buffer
01020    simultaneously.  */
01021 
01022 struct trace_buffer_control
01023 {
01024   /* Pointer to the first trace frame in the buffer.  In the
01025      non-circular case, this is equal to trace_buffer_lo, otherwise it
01026      moves around in the buffer.  */
01027   unsigned char *start;
01028 
01029   /* Pointer to the free part of the trace buffer.  Note that we clear
01030      several bytes at and after this pointer, so that traceframe
01031      scans/searches terminate properly.  */
01032   unsigned char *free;
01033 
01034   /* Pointer to the byte after the end of the free part.  Note that
01035      this may be smaller than trace_buffer_free in the circular case,
01036      and means that the free part is in two pieces.  Initially it is
01037      equal to trace_buffer_hi, then is generally equivalent to
01038      trace_buffer_start.  */
01039   unsigned char *end_free;
01040 
01041   /* Pointer to the wraparound.  If not equal to trace_buffer_hi, then
01042      this is the point at which the trace data breaks, and resumes at
01043      trace_buffer_lo.  */
01044   unsigned char *wrap;
01045 };
01046 
01047 /* Same as above, to be used by GDBserver when updating the in-process
01048    agent.  */
01049 struct ipa_trace_buffer_control
01050 {
01051   uintptr_t start;
01052   uintptr_t free;
01053   uintptr_t end_free;
01054   uintptr_t wrap;
01055 };
01056 
01057 
01058 /* We have possibly both GDBserver and an inferior thread accessing
01059    the same IPA trace buffer memory.  The IPA is the producer (tries
01060    to put new frames in the buffer), while GDBserver occasionally
01061    consumes them, that is, flushes the IPA's buffer into its own
01062    buffer.  Both sides need to update the trace buffer control
01063    pointers (current head, tail, etc.).  We can't use a global lock to
01064    synchronize the accesses, as otherwise we could deadlock GDBserver
01065    (if the thread holding the lock stops for a signal, say).  So
01066    instead of that, we use a transaction scheme where GDBserver writes
01067    always prevail over the IPAs writes, and, we have the IPA detect
01068    the commit failure/overwrite, and retry the whole attempt.  This is
01069    mainly implemented by having a global token object that represents
01070    who wrote last to the buffer control structure.  We need to freeze
01071    any inferior writing to the buffer while GDBserver touches memory,
01072    so that the inferior can correctly detect that GDBserver had been
01073    there, otherwise, it could mistakingly think its commit was
01074    successful; that's implemented by simply having GDBserver set a
01075    breakpoint the inferior hits if it is the critical region.
01076 
01077    There are three cycling trace buffer control structure copies
01078    (buffer head, tail, etc.), with the token object including an index
01079    indicating which is current live copy.  The IPA tentatively builds
01080    an updated copy in a non-current control structure, while GDBserver
01081    always clobbers the current version directly.  The IPA then tries
01082    to atomically "commit" its version; if GDBserver clobbered the
01083    structure meanwhile, that will fail, and the IPA restarts the
01084    allocation process.
01085 
01086    Listing the step in further detail, we have:
01087 
01088   In-process agent (producer):
01089 
01090   - passes by `about_to_request_buffer_space' breakpoint/lock
01091 
01092   - reads current token, extracts current trace buffer control index,
01093     and starts tentatively updating the rightmost one (0->1, 1->2,
01094     2->0).  Note that only one inferior thread is executing this code
01095     at any given time, due to an outer lock in the jump pads.
01096 
01097   - updates counters, and tries to commit the token.
01098 
01099   - passes by second `about_to_request_buffer_space' breakpoint/lock,
01100     leaving the sync region.
01101 
01102   - checks if the update was effective.
01103 
01104   - if trace buffer was found full, hits flush_trace_buffer
01105     breakpoint, and restarts later afterwards.
01106 
01107   GDBserver (consumer):
01108 
01109   - sets `about_to_request_buffer_space' breakpoint/lock.
01110 
01111   - updates the token unconditionally, using the current buffer
01112     control index, since it knows that the IP agent always writes to
01113     the rightmost, and due to the breakpoint, at most one IP thread
01114     can try to update the trace buffer concurrently to GDBserver, so
01115     there will be no danger of trace buffer control index wrap making
01116     the IPA write to the same index as GDBserver.
01117 
01118   - flushes the IP agent's trace buffer completely, and updates the
01119     current trace buffer control structure.  GDBserver *always* wins.
01120 
01121   - removes the `about_to_request_buffer_space' breakpoint.
01122 
01123 The token is stored in the `trace_buffer_ctrl_curr' variable.
01124 Internally, it's bits are defined as:
01125 
01126  |-------------+-----+-------------+--------+-------------+--------------|
01127  | Bit offsets |  31 |   30 - 20   |   19   |    18-8     |     7-0      |
01128  |-------------+-----+-------------+--------+-------------+--------------|
01129  | What        | GSB | PC (11-bit) | unused | CC (11-bit) | TBCI (8-bit) |
01130  |-------------+-----+-------------+--------+-------------+--------------|
01131 
01132  GSB  - GDBserver Stamp Bit
01133  PC   - Previous Counter
01134  CC   - Current Counter
01135  TBCI - Trace Buffer Control Index
01136 
01137 
01138 An IPA update of `trace_buffer_ctrl_curr' does:
01139 
01140     - read CC from the current token, save as PC.
01141     - updates pointers
01142     - atomically tries to write PC+1,CC
01143 
01144 A GDBserver update of `trace_buffer_ctrl_curr' does:
01145 
01146     - reads PC and CC from the current token.
01147     - updates pointers
01148     - writes GSB,PC,CC
01149 */
01150 
01151 /* These are the bits of `trace_buffer_ctrl_curr' that are reserved
01152    for the counters described below.  The cleared bits are used to
01153    hold the index of the items of the `trace_buffer_ctrl' array that
01154    is "current".  */
01155 #define GDBSERVER_FLUSH_COUNT_MASK        0xfffffff0
01156 
01157 /* `trace_buffer_ctrl_curr' contains two counters.  The `previous'
01158    counter, and the `current' counter.  */
01159 
01160 #define GDBSERVER_FLUSH_COUNT_MASK_PREV   0x7ff00000
01161 #define GDBSERVER_FLUSH_COUNT_MASK_CURR   0x0007ff00
01162 
01163 /* When GDBserver update the IP agent's `trace_buffer_ctrl_curr', it
01164    always stamps this bit as set.  */
01165 #define GDBSERVER_UPDATED_FLUSH_COUNT_BIT 0x80000000
01166 
01167 #ifdef IN_PROCESS_AGENT
01168 IP_AGENT_EXPORT struct trace_buffer_control trace_buffer_ctrl[3];
01169 IP_AGENT_EXPORT unsigned int trace_buffer_ctrl_curr;
01170 
01171 # define TRACE_BUFFER_CTRL_CURR \
01172   (trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK)
01173 
01174 #else
01175 
01176 /* The GDBserver side agent only needs one instance of this object, as
01177    it doesn't need to sync with itself.  Define it as array anyway so
01178    that the rest of the code base doesn't need to care for the
01179    difference.  */
01180 struct trace_buffer_control trace_buffer_ctrl[1];
01181 # define TRACE_BUFFER_CTRL_CURR 0
01182 #endif
01183 
01184 /* These are convenience macros used to access the current trace
01185    buffer control in effect.  */
01186 #define trace_buffer_start (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].start)
01187 #define trace_buffer_free (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].free)
01188 #define trace_buffer_end_free \
01189   (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].end_free)
01190 #define trace_buffer_wrap (trace_buffer_ctrl[TRACE_BUFFER_CTRL_CURR].wrap)
01191 
01192 
01193 /* Macro that returns a pointer to the first traceframe in the buffer.  */
01194 
01195 #define FIRST_TRACEFRAME() ((struct traceframe *) trace_buffer_start)
01196 
01197 /* Macro that returns a pointer to the next traceframe in the buffer.
01198    If the computed location is beyond the wraparound point, subtract
01199    the offset of the wraparound.  */
01200 
01201 #define NEXT_TRACEFRAME_1(TF) \
01202   (((unsigned char *) (TF)) + sizeof (struct traceframe) + (TF)->data_size)
01203 
01204 #define NEXT_TRACEFRAME(TF) \
01205   ((struct traceframe *) (NEXT_TRACEFRAME_1 (TF)  \
01206                           - ((NEXT_TRACEFRAME_1 (TF) >= trace_buffer_wrap) \
01207                              ? (trace_buffer_wrap - trace_buffer_lo)    \
01208                              : 0)))
01209 
01210 /* The difference between these counters represents the total number
01211    of complete traceframes present in the trace buffer.  The IP agent
01212    writes to the write count, GDBserver writes to read count.  */
01213 
01214 IP_AGENT_EXPORT unsigned int traceframe_write_count;
01215 IP_AGENT_EXPORT unsigned int traceframe_read_count;
01216 
01217 /* Convenience macro.  */
01218 
01219 #define traceframe_count \
01220   ((unsigned int) (traceframe_write_count - traceframe_read_count))
01221 
01222 /* The count of all traceframes created in the current run, including
01223    ones that were discarded to make room.  */
01224 
01225 IP_AGENT_EXPORT int traceframes_created;
01226 
01227 #ifndef IN_PROCESS_AGENT
01228 
01229 /* Read-only regions are address ranges whose contents don't change,
01230    and so can be read from target memory even while looking at a trace
01231    frame.  Without these, disassembly for instance will likely fail,
01232    because the program code is not usually collected into a trace
01233    frame.  This data structure does not need to be very complicated or
01234    particularly efficient, it's only going to be used occasionally,
01235    and only by some commands.  */
01236 
01237 struct readonly_region
01238 {
01239   /* The bounds of the region.  */
01240   CORE_ADDR start, end;
01241 
01242   /* Link to the next one.  */
01243   struct readonly_region *next;
01244 };
01245 
01246 /* Linked list of readonly regions.  This list stays in effect from
01247    one tstart to the next.  */
01248 
01249 static struct readonly_region *readonly_regions;
01250 
01251 #endif
01252 
01253 /* The global that controls tracing overall.  */
01254 
01255 IP_AGENT_EXPORT int tracing;
01256 
01257 #ifndef IN_PROCESS_AGENT
01258 
01259 /* Controls whether tracing should continue after GDB disconnects.  */
01260 
01261 int disconnected_tracing;
01262 
01263 /* The reason for the last tracing run to have stopped.  We initialize
01264    to a distinct string so that GDB can distinguish between "stopped
01265    after running" and "stopped because never run" cases.  */
01266 
01267 static const char *tracing_stop_reason = "tnotrun";
01268 
01269 static int tracing_stop_tpnum;
01270 
01271 /* 64-bit timestamps for the trace run's start and finish, expressed
01272    in microseconds from the Unix epoch.  */
01273 
01274 LONGEST tracing_start_time;
01275 LONGEST tracing_stop_time;
01276 
01277 /* The (optional) user-supplied name of the user that started the run.
01278    This is an arbitrary string, and may be NULL.  */
01279 
01280 char *tracing_user_name;
01281 
01282 /* Optional user-supplied text describing the run.  This is
01283    an arbitrary string, and may be NULL.  */
01284 
01285 char *tracing_notes;
01286 
01287 /* Optional user-supplied text explaining a tstop command.  This is an
01288    arbitrary string, and may be NULL.  */
01289 
01290 char *tracing_stop_note;
01291 
01292 #endif
01293 
01294 /* Functions local to this file.  */
01295 
01296 /* Base "class" for tracepoint type specific data to be passed down to
01297    collect_data_at_tracepoint.  */
01298 struct tracepoint_hit_ctx
01299 {
01300   enum tracepoint_type type;
01301 };
01302 
01303 #ifdef IN_PROCESS_AGENT
01304 
01305 /* Fast/jump tracepoint specific data to be passed down to
01306    collect_data_at_tracepoint.  */
01307 struct fast_tracepoint_ctx
01308 {
01309   struct tracepoint_hit_ctx base;
01310 
01311   struct regcache regcache;
01312   int regcache_initted;
01313   unsigned char *regspace;
01314 
01315   unsigned char *regs;
01316   struct tracepoint *tpoint;
01317 };
01318 
01319 /* Static tracepoint specific data to be passed down to
01320    collect_data_at_tracepoint.  */
01321 struct static_tracepoint_ctx
01322 {
01323   struct tracepoint_hit_ctx base;
01324 
01325   /* The regcache corresponding to the registers state at the time of
01326      the tracepoint hit.  Initialized lazily, from REGS.  */
01327   struct regcache regcache;
01328   int regcache_initted;
01329 
01330   /* The buffer space REGCACHE above uses.  We use a separate buffer
01331      instead of letting the regcache malloc for both signal safety and
01332      performance reasons; this is allocated on the stack instead.  */
01333   unsigned char *regspace;
01334 
01335   /* The register buffer as passed on by lttng/ust.  */
01336   struct registers *regs;
01337 
01338   /* The "printf" formatter and the args the user passed to the marker
01339      call.  We use this to be able to collect "static trace data"
01340      ($_sdata).  */
01341   const char *fmt;
01342   va_list *args;
01343 
01344   /* The GDB tracepoint matching the probed marker that was "hit".  */
01345   struct tracepoint *tpoint;
01346 };
01347 
01348 #else
01349 
01350 /* Static tracepoint specific data to be passed down to
01351    collect_data_at_tracepoint.  */
01352 struct trap_tracepoint_ctx
01353 {
01354   struct tracepoint_hit_ctx base;
01355 
01356   struct regcache *regcache;
01357 };
01358 
01359 #endif
01360 
01361 #ifndef IN_PROCESS_AGENT
01362 static CORE_ADDR traceframe_get_pc (struct traceframe *tframe);
01363 static int traceframe_read_tsv (int num, LONGEST *val);
01364 #endif
01365 
01366 static int condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
01367                                          struct tracepoint *tpoint);
01368 
01369 #ifndef IN_PROCESS_AGENT
01370 static void clear_readonly_regions (void);
01371 static void clear_installed_tracepoints (void);
01372 #endif
01373 
01374 static void collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
01375                                         CORE_ADDR stop_pc,
01376                                         struct tracepoint *tpoint);
01377 #ifndef IN_PROCESS_AGENT
01378 static void collect_data_at_step (struct tracepoint_hit_ctx *ctx,
01379                                   CORE_ADDR stop_pc,
01380                                   struct tracepoint *tpoint, int current_step);
01381 static void compile_tracepoint_condition (struct tracepoint *tpoint,
01382                                           CORE_ADDR *jump_entry);
01383 #endif
01384 static void do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
01385                                      CORE_ADDR stop_pc,
01386                                      struct tracepoint *tpoint,
01387                                      struct traceframe *tframe,
01388                                      struct tracepoint_action *taction);
01389 
01390 #ifndef IN_PROCESS_AGENT
01391 static struct tracepoint *fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR);
01392 
01393 static void install_tracepoint (struct tracepoint *, char *own_buf);
01394 static void download_tracepoint (struct tracepoint *);
01395 static int install_fast_tracepoint (struct tracepoint *, char *errbuf);
01396 static void clone_fast_tracepoint (struct tracepoint *to,
01397                                    const struct tracepoint *from);
01398 #endif
01399 
01400 static LONGEST get_timestamp (void);
01401 
01402 #if defined(__GNUC__)
01403 #  define memory_barrier() asm volatile ("" : : : "memory")
01404 #else
01405 #  define memory_barrier() do {} while (0)
01406 #endif
01407 
01408 /* We only build the IPA if this builtin is supported, and there are
01409    no uses of this in GDBserver itself, so we're safe in defining this
01410    unconditionally.  */
01411 #define cmpxchg(mem, oldval, newval) \
01412   __sync_val_compare_and_swap (mem, oldval, newval)
01413 
01414 /* Record that an error occurred during expression evaluation.  */
01415 
01416 static void
01417 record_tracepoint_error (struct tracepoint *tpoint, const char *which,
01418                          enum eval_result_type rtype)
01419 {
01420   trace_debug ("Tracepoint %d at %s %s eval reports error %d",
01421                tpoint->number, paddress (tpoint->address), which, rtype);
01422 
01423 #ifdef IN_PROCESS_AGENT
01424   /* Only record the first error we get.  */
01425   if (cmpxchg (&expr_eval_result,
01426                expr_eval_no_error,
01427                rtype) != expr_eval_no_error)
01428     return;
01429 #else
01430   if (expr_eval_result != expr_eval_no_error)
01431     return;
01432 #endif
01433 
01434   error_tracepoint = tpoint;
01435 }
01436 
01437 /* Trace buffer management.  */
01438 
01439 static void
01440 clear_trace_buffer (void)
01441 {
01442   trace_buffer_start = trace_buffer_lo;
01443   trace_buffer_free = trace_buffer_lo;
01444   trace_buffer_end_free = trace_buffer_hi;
01445   trace_buffer_wrap = trace_buffer_hi;
01446   /* A traceframe with zeroed fields marks the end of trace data.  */
01447   ((struct traceframe *) trace_buffer_free)->tpnum = 0;
01448   ((struct traceframe *) trace_buffer_free)->data_size = 0;
01449   traceframe_read_count = traceframe_write_count = 0;
01450   traceframes_created = 0;
01451 }
01452 
01453 #ifndef IN_PROCESS_AGENT
01454 
01455 static void
01456 clear_inferior_trace_buffer (void)
01457 {
01458   CORE_ADDR ipa_trace_buffer_lo;
01459   CORE_ADDR ipa_trace_buffer_hi;
01460   struct traceframe ipa_traceframe = { 0 };
01461   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
01462 
01463   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
01464                               &ipa_trace_buffer_lo);
01465   read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
01466                               &ipa_trace_buffer_hi);
01467 
01468   ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
01469   ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
01470   ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
01471   ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
01472 
01473   /* A traceframe with zeroed fields marks the end of trace data.  */
01474   write_inferior_memory (ipa_sym_addrs.addr_trace_buffer_ctrl,
01475                          (unsigned char *) &ipa_trace_buffer_ctrl,
01476                          sizeof (ipa_trace_buffer_ctrl));
01477 
01478   write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr, 0);
01479 
01480   /* A traceframe with zeroed fields marks the end of trace data.  */
01481   write_inferior_memory (ipa_trace_buffer_lo,
01482                          (unsigned char *) &ipa_traceframe,
01483                          sizeof (ipa_traceframe));
01484 
01485   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count, 0);
01486   write_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count, 0);
01487   write_inferior_integer (ipa_sym_addrs.addr_traceframes_created, 0);
01488 }
01489 
01490 #endif
01491 
01492 static void
01493 init_trace_buffer (LONGEST bufsize)
01494 {
01495   size_t alloc_size;
01496 
01497   trace_buffer_size = bufsize;
01498 
01499   /* Make sure to internally allocate at least space for the EOB
01500      marker.  */
01501   alloc_size = (bufsize < TRACEFRAME_EOB_MARKER_SIZE
01502                 ? TRACEFRAME_EOB_MARKER_SIZE : bufsize);
01503   trace_buffer_lo = xrealloc (trace_buffer_lo, alloc_size);
01504 
01505   trace_buffer_hi = trace_buffer_lo + trace_buffer_size;
01506 
01507   clear_trace_buffer ();
01508 }
01509 
01510 #ifdef IN_PROCESS_AGENT
01511 
01512 IP_AGENT_EXPORT void ATTR_USED ATTR_NOINLINE
01513 about_to_request_buffer_space (void)
01514 {
01515   /* GDBserver places breakpoint here while it goes about to flush
01516      data at random times.  */
01517   UNKNOWN_SIDE_EFFECTS();
01518 }
01519 
01520 #endif
01521 
01522 /* Carve out a piece of the trace buffer, returning NULL in case of
01523    failure.  */
01524 
01525 static void *
01526 trace_buffer_alloc (size_t amt)
01527 {
01528   unsigned char *rslt;
01529   struct trace_buffer_control *tbctrl;
01530   unsigned int curr;
01531 #ifdef IN_PROCESS_AGENT
01532   unsigned int prev, prev_filtered;
01533   unsigned int commit_count;
01534   unsigned int commit;
01535   unsigned int readout;
01536 #else
01537   struct traceframe *oldest;
01538   unsigned char *new_start;
01539 #endif
01540 
01541   trace_debug ("Want to allocate %ld+%ld bytes in trace buffer",
01542                (long) amt, (long) sizeof (struct traceframe));
01543 
01544   /* Account for the EOB marker.  */
01545   amt += TRACEFRAME_EOB_MARKER_SIZE;
01546 
01547 #ifdef IN_PROCESS_AGENT
01548  again:
01549   memory_barrier ();
01550 
01551   /* Read the current token and extract the index to try to write to,
01552      storing it in CURR.  */
01553   prev = trace_buffer_ctrl_curr;
01554   prev_filtered = prev & ~GDBSERVER_FLUSH_COUNT_MASK;
01555   curr = prev_filtered + 1;
01556   if (curr > 2)
01557     curr = 0;
01558 
01559   about_to_request_buffer_space ();
01560 
01561   /* Start out with a copy of the current state.  GDBserver may be
01562      midway writing to the PREV_FILTERED TBC, but, that's OK, we won't
01563      be able to commit anyway if that happens.  */
01564   trace_buffer_ctrl[curr]
01565     = trace_buffer_ctrl[prev_filtered];
01566   trace_debug ("trying curr=%u", curr);
01567 #else
01568   /* The GDBserver's agent doesn't need all that syncing, and always
01569      updates TCB 0 (there's only one, mind you).  */
01570   curr = 0;
01571 #endif
01572   tbctrl = &trace_buffer_ctrl[curr];
01573 
01574   /* Offsets are easier to grok for debugging than raw addresses,
01575      especially for the small trace buffer sizes that are useful for
01576      testing.  */
01577   trace_debug ("Trace buffer [%d] start=%d free=%d endfree=%d wrap=%d hi=%d",
01578                curr,
01579                (int) (tbctrl->start - trace_buffer_lo),
01580                (int) (tbctrl->free - trace_buffer_lo),
01581                (int) (tbctrl->end_free - trace_buffer_lo),
01582                (int) (tbctrl->wrap - trace_buffer_lo),
01583                (int) (trace_buffer_hi - trace_buffer_lo));
01584 
01585   /* The algorithm here is to keep trying to get a contiguous block of
01586      the requested size, possibly discarding older traceframes to free
01587      up space.  Since free space might come in one or two pieces,
01588      depending on whether discarded traceframes wrapped around at the
01589      high end of the buffer, we test both pieces after each
01590      discard.  */
01591   while (1)
01592     {
01593       /* First, if we have two free parts, try the upper one first.  */
01594       if (tbctrl->end_free < tbctrl->free)
01595         {
01596           if (tbctrl->free + amt <= trace_buffer_hi)
01597             /* We have enough in the upper part.  */
01598             break;
01599           else
01600             {
01601               /* Our high part of free space wasn't enough.  Give up
01602                  on it for now, set wraparound.  We will recover the
01603                  space later, if/when the wrapped-around traceframe is
01604                  discarded.  */
01605               trace_debug ("Upper part too small, setting wraparound");
01606               tbctrl->wrap = tbctrl->free;
01607               tbctrl->free = trace_buffer_lo;
01608             }
01609         }
01610 
01611       /* The normal case.  */
01612       if (tbctrl->free + amt <= tbctrl->end_free)
01613         break;
01614 
01615 #ifdef IN_PROCESS_AGENT
01616       /* The IP Agent's buffer is always circular.  It isn't used
01617          currently, but `circular_trace_buffer' could represent
01618          GDBserver's mode.  If we didn't find space, ask GDBserver to
01619          flush.  */
01620 
01621       flush_trace_buffer ();
01622       memory_barrier ();
01623       if (tracing)
01624         {
01625           trace_debug ("gdbserver flushed buffer, retrying");
01626           goto again;
01627         }
01628 
01629       /* GDBserver cancelled the tracing.  Bail out as well.  */
01630       return NULL;
01631 #else
01632       /* If we're here, then neither part is big enough, and
01633          non-circular trace buffers are now full.  */
01634       if (!circular_trace_buffer)
01635         {
01636           trace_debug ("Not enough space in the trace buffer");
01637           return NULL;
01638         }
01639 
01640       trace_debug ("Need more space in the trace buffer");
01641 
01642       /* If we have a circular buffer, we can try discarding the
01643          oldest traceframe and see if that helps.  */
01644       oldest = FIRST_TRACEFRAME ();
01645       if (oldest->tpnum == 0)
01646         {
01647           /* Not good; we have no traceframes to free.  Perhaps we're
01648              asking for a block that is larger than the buffer?  In
01649              any case, give up.  */
01650           trace_debug ("No traceframes to discard");
01651           return NULL;
01652         }
01653 
01654       /* We don't run this code in the in-process agent currently.
01655          E.g., we could leave the in-process agent in autonomous
01656          circular mode if we only have fast tracepoints.  If we do
01657          that, then this bit becomes racy with GDBserver, which also
01658          writes to this counter.  */
01659       --traceframe_write_count;
01660 
01661       new_start = (unsigned char *) NEXT_TRACEFRAME (oldest);
01662       /* If we freed the traceframe that wrapped around, go back
01663          to the non-wrap case.  */
01664       if (new_start < tbctrl->start)
01665         {
01666           trace_debug ("Discarding past the wraparound");
01667           tbctrl->wrap = trace_buffer_hi;
01668         }
01669       tbctrl->start = new_start;
01670       tbctrl->end_free = tbctrl->start;
01671 
01672       trace_debug ("Discarded a traceframe\n"
01673                    "Trace buffer [%d], start=%d free=%d "
01674                    "endfree=%d wrap=%d hi=%d",
01675                    curr,
01676                    (int) (tbctrl->start - trace_buffer_lo),
01677                    (int) (tbctrl->free - trace_buffer_lo),
01678                    (int) (tbctrl->end_free - trace_buffer_lo),
01679                    (int) (tbctrl->wrap - trace_buffer_lo),
01680                    (int) (trace_buffer_hi - trace_buffer_lo));
01681 
01682       /* Now go back around the loop.  The discard might have resulted
01683          in either one or two pieces of free space, so we want to try
01684          both before freeing any more traceframes.  */
01685 #endif
01686     }
01687 
01688   /* If we get here, we know we can provide the asked-for space.  */
01689 
01690   rslt = tbctrl->free;
01691 
01692   /* Adjust the request back down, now that we know we have space for
01693      the marker, but don't commit to AMT yet, we may still need to
01694      restart the operation if GDBserver touches the trace buffer
01695      (obviously only important in the in-process agent's version).  */
01696   tbctrl->free += (amt - sizeof (struct traceframe));
01697 
01698   /* Or not.  If GDBserver changed the trace buffer behind our back,
01699      we get to restart a new allocation attempt.  */
01700 
01701 #ifdef IN_PROCESS_AGENT
01702   /* Build the tentative token.  */
01703   commit_count = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) + 0x100)
01704                   & GDBSERVER_FLUSH_COUNT_MASK_CURR);
01705   commit = (((prev & GDBSERVER_FLUSH_COUNT_MASK_CURR) << 12)
01706             | commit_count
01707             | curr);
01708 
01709   /* Try to commit it.  */
01710   readout = cmpxchg (&trace_buffer_ctrl_curr, prev, commit);
01711   if (readout != prev)
01712     {
01713       trace_debug ("GDBserver has touched the trace buffer, restarting."
01714                    " (prev=%08x, commit=%08x, readout=%08x)",
01715                    prev, commit, readout);
01716       goto again;
01717     }
01718 
01719   /* Hold your horses here.  Even if that change was committed,
01720      GDBserver could come in, and clobber it.  We need to hold to be
01721      able to tell if GDBserver clobbers before or after we committed
01722      the change.  Whenever GDBserver goes about touching the IPA
01723      buffer, it sets a breakpoint in this routine, so we have a sync
01724      point here.  */
01725   about_to_request_buffer_space ();
01726 
01727   /* Check if the change has been effective, even if GDBserver stopped
01728      us at the breakpoint.  */
01729 
01730   {
01731     unsigned int refetch;
01732 
01733     memory_barrier ();
01734 
01735     refetch = trace_buffer_ctrl_curr;
01736 
01737     if (refetch == commit
01738         || ((refetch & GDBSERVER_FLUSH_COUNT_MASK_PREV) >> 12) == commit_count)
01739       {
01740         /* effective */
01741         trace_debug ("change is effective: (prev=%08x, commit=%08x, "
01742                      "readout=%08x, refetch=%08x)",
01743                      prev, commit, readout, refetch);
01744       }
01745     else
01746       {
01747         trace_debug ("GDBserver has touched the trace buffer, not effective."
01748                      " (prev=%08x, commit=%08x, readout=%08x, refetch=%08x)",
01749                      prev, commit, readout, refetch);
01750         goto again;
01751       }
01752   }
01753 #endif
01754 
01755   /* We have a new piece of the trace buffer.  Hurray!  */
01756 
01757   /* Add an EOB marker just past this allocation.  */
01758   ((struct traceframe *) tbctrl->free)->tpnum = 0;
01759   ((struct traceframe *) tbctrl->free)->data_size = 0;
01760 
01761   /* Adjust the request back down, now that we know we have space for
01762      the marker.  */
01763   amt -= sizeof (struct traceframe);
01764 
01765   if (debug_threads)
01766     {
01767       trace_debug ("Allocated %d bytes", (int) amt);
01768       trace_debug ("Trace buffer [%d] start=%d free=%d "
01769                    "endfree=%d wrap=%d hi=%d",
01770                    curr,
01771                    (int) (tbctrl->start - trace_buffer_lo),
01772                    (int) (tbctrl->free - trace_buffer_lo),
01773                    (int) (tbctrl->end_free - trace_buffer_lo),
01774                    (int) (tbctrl->wrap - trace_buffer_lo),
01775                    (int) (trace_buffer_hi - trace_buffer_lo));
01776     }
01777 
01778   return rslt;
01779 }
01780 
01781 #ifndef IN_PROCESS_AGENT
01782 
01783 /* Return the total free space.  This is not necessarily the largest
01784    block we can allocate, because of the two-part case.  */
01785 
01786 static int
01787 free_space (void)
01788 {
01789   if (trace_buffer_free <= trace_buffer_end_free)
01790     return trace_buffer_end_free - trace_buffer_free;
01791   else
01792     return ((trace_buffer_end_free - trace_buffer_lo)
01793             + (trace_buffer_hi - trace_buffer_free));
01794 }
01795 
01796 /* An 'S' in continuation packets indicates remainder are for
01797    while-stepping.  */
01798 
01799 static int seen_step_action_flag;
01800 
01801 /* Create a tracepoint (location) with given number and address.  Add this
01802    new tracepoint to list and sort this list.  */
01803 
01804 static struct tracepoint *
01805 add_tracepoint (int num, CORE_ADDR addr)
01806 {
01807   struct tracepoint *tpoint, **tp_next;
01808 
01809   tpoint = xmalloc (sizeof (struct tracepoint));
01810   tpoint->number = num;
01811   tpoint->address = addr;
01812   tpoint->numactions = 0;
01813   tpoint->actions = NULL;
01814   tpoint->actions_str = NULL;
01815   tpoint->cond = NULL;
01816   tpoint->num_step_actions = 0;
01817   tpoint->step_actions = NULL;
01818   tpoint->step_actions_str = NULL;
01819   /* Start all off as regular (slow) tracepoints.  */
01820   tpoint->type = trap_tracepoint;
01821   tpoint->orig_size = -1;
01822   tpoint->source_strings = NULL;
01823   tpoint->compiled_cond = 0;
01824   tpoint->handle = NULL;
01825   tpoint->next = NULL;
01826 
01827   /* Find a place to insert this tracepoint into list in order to keep
01828      the tracepoint list still in the ascending order.  There may be
01829      multiple tracepoints at the same address as TPOINT's, and this
01830      guarantees TPOINT is inserted after all the tracepoints which are
01831      set at the same address.  For example, fast tracepoints A, B, C are
01832      set at the same address, and D is to be insert at the same place as
01833      well,
01834 
01835      -->| A |--> | B |-->| C |->...
01836 
01837      One jump pad was created for tracepoint A, B, and C, and the target
01838      address of A is referenced/used in jump pad.  So jump pad will let
01839      inferior jump to A.  If D is inserted in front of A, like this,
01840 
01841      -->| D |-->| A |--> | B |-->| C |->...
01842 
01843      without updating jump pad, D is not reachable during collect, which
01844      is wrong.  As we can see, the order of B, C and D doesn't matter, but
01845      A should always be the `first' one.  */
01846   for (tp_next = &tracepoints;
01847        (*tp_next) != NULL && (*tp_next)->address <= tpoint->address;
01848        tp_next = &(*tp_next)->next)
01849     ;
01850   tpoint->next = *tp_next;
01851   *tp_next = tpoint;
01852   last_tracepoint = tpoint;
01853 
01854   seen_step_action_flag = 0;
01855 
01856   return tpoint;
01857 }
01858 
01859 #ifndef IN_PROCESS_AGENT
01860 
01861 /* Return the tracepoint with the given number and address, or NULL.  */
01862 
01863 static struct tracepoint *
01864 find_tracepoint (int id, CORE_ADDR addr)
01865 {
01866   struct tracepoint *tpoint;
01867 
01868   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
01869     if (tpoint->number == id && tpoint->address == addr)
01870       return tpoint;
01871 
01872   return NULL;
01873 }
01874 
01875 /* Remove TPOINT from global list.  */
01876 
01877 static void
01878 remove_tracepoint (struct tracepoint *tpoint)
01879 {
01880   struct tracepoint *tp, *tp_prev;
01881 
01882   for (tp = tracepoints, tp_prev = NULL; tp && tp != tpoint;
01883        tp_prev = tp, tp = tp->next)
01884     ;
01885 
01886   if (tp)
01887     {
01888       if (tp_prev)
01889         tp_prev->next = tp->next;
01890       else
01891         tracepoints = tp->next;
01892 
01893       xfree (tp);
01894     }
01895 }
01896 
01897 /* There may be several tracepoints with the same number (because they
01898    are "locations", in GDB parlance); return the next one after the
01899    given tracepoint, or search from the beginning of the list if the
01900    first argument is NULL.  */
01901 
01902 static struct tracepoint *
01903 find_next_tracepoint_by_number (struct tracepoint *prev_tp, int num)
01904 {
01905   struct tracepoint *tpoint;
01906 
01907   if (prev_tp)
01908     tpoint = prev_tp->next;
01909   else
01910     tpoint = tracepoints;
01911   for (; tpoint; tpoint = tpoint->next)
01912     if (tpoint->number == num)
01913       return tpoint;
01914 
01915   return NULL;
01916 }
01917 
01918 #endif
01919 
01920 /* Append another action to perform when the tracepoint triggers.  */
01921 
01922 static void
01923 add_tracepoint_action (struct tracepoint *tpoint, char *packet)
01924 {
01925   char *act;
01926 
01927   if (*packet == 'S')
01928     {
01929       seen_step_action_flag = 1;
01930       ++packet;
01931     }
01932 
01933   act = packet;
01934 
01935   while (*act)
01936     {
01937       char *act_start = act;
01938       struct tracepoint_action *action = NULL;
01939 
01940       switch (*act)
01941         {
01942         case 'M':
01943           {
01944             struct collect_memory_action *maction;
01945             ULONGEST basereg;
01946             int is_neg;
01947 
01948             maction = xmalloc (sizeof *maction);
01949             maction->base.type = *act;
01950             maction->base.ops = &m_tracepoint_action_ops;
01951             action = &maction->base;
01952 
01953             ++act;
01954             is_neg = (*act == '-');
01955             if (*act == '-')
01956               ++act;
01957             act = unpack_varlen_hex (act, &basereg);
01958             ++act;
01959             act = unpack_varlen_hex (act, &maction->addr);
01960             ++act;
01961             act = unpack_varlen_hex (act, &maction->len);
01962             maction->basereg = (is_neg
01963                                 ? - (int) basereg
01964                                 : (int) basereg);
01965             trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
01966                          pulongest (maction->len),
01967                          paddress (maction->addr), maction->basereg);
01968             break;
01969           }
01970         case 'R':
01971           {
01972             struct collect_registers_action *raction;
01973 
01974             raction = xmalloc (sizeof *raction);
01975             raction->base.type = *act;
01976             raction->base.ops = &r_tracepoint_action_ops;
01977             action = &raction->base;
01978 
01979             trace_debug ("Want to collect registers");
01980             ++act;
01981             /* skip past hex digits of mask for now */
01982             while (isxdigit(*act))
01983               ++act;
01984             break;
01985           }
01986         case 'L':
01987           {
01988             struct collect_static_trace_data_action *raction;
01989 
01990             raction = xmalloc (sizeof *raction);
01991             raction->base.type = *act;
01992             raction->base.ops = &l_tracepoint_action_ops;
01993             action = &raction->base;
01994 
01995             trace_debug ("Want to collect static trace data");
01996             ++act;
01997             break;
01998           }
01999         case 'S':
02000           trace_debug ("Unexpected step action, ignoring");
02001           ++act;
02002           break;
02003         case 'X':
02004           {
02005             struct eval_expr_action *xaction;
02006 
02007             xaction = xmalloc (sizeof (*xaction));
02008             xaction->base.type = *act;
02009             xaction->base.ops = &x_tracepoint_action_ops;
02010             action = &xaction->base;
02011 
02012             trace_debug ("Want to evaluate expression");
02013             xaction->expr = gdb_parse_agent_expr (&act);
02014             break;
02015           }
02016         default:
02017           trace_debug ("unknown trace action '%c', ignoring...", *act);
02018           break;
02019         case '-':
02020           break;
02021         }
02022 
02023       if (action == NULL)
02024         break;
02025 
02026       if (seen_step_action_flag)
02027         {
02028           tpoint->num_step_actions++;
02029 
02030           tpoint->step_actions
02031             = xrealloc (tpoint->step_actions,
02032                         (sizeof (*tpoint->step_actions)
02033                          * tpoint->num_step_actions));
02034           tpoint->step_actions_str
02035             = xrealloc (tpoint->step_actions_str,
02036                         (sizeof (*tpoint->step_actions_str)
02037                          * tpoint->num_step_actions));
02038           tpoint->step_actions[tpoint->num_step_actions - 1] = action;
02039           tpoint->step_actions_str[tpoint->num_step_actions - 1]
02040             = savestring (act_start, act - act_start);
02041         }
02042       else
02043         {
02044           tpoint->numactions++;
02045           tpoint->actions
02046             = xrealloc (tpoint->actions,
02047                         sizeof (*tpoint->actions) * tpoint->numactions);
02048           tpoint->actions_str
02049             = xrealloc (tpoint->actions_str,
02050                         sizeof (*tpoint->actions_str) * tpoint->numactions);
02051           tpoint->actions[tpoint->numactions - 1] = action;
02052           tpoint->actions_str[tpoint->numactions - 1]
02053             = savestring (act_start, act - act_start);
02054         }
02055     }
02056 }
02057 
02058 #endif
02059 
02060 /* Find or create a trace state variable with the given number.  */
02061 
02062 static struct trace_state_variable *
02063 get_trace_state_variable (int num)
02064 {
02065   struct trace_state_variable *tsv;
02066 
02067 #ifdef IN_PROCESS_AGENT
02068   /* Search for an existing variable.  */
02069   for (tsv = alloced_trace_state_variables; tsv; tsv = tsv->next)
02070     if (tsv->number == num)
02071       return tsv;
02072 #endif
02073 
02074   /* Search for an existing variable.  */
02075   for (tsv = trace_state_variables; tsv; tsv = tsv->next)
02076     if (tsv->number == num)
02077       return tsv;
02078 
02079   return NULL;
02080 }
02081 
02082 /* Find or create a trace state variable with the given number.  */
02083 
02084 static struct trace_state_variable *
02085 create_trace_state_variable (int num, int gdb)
02086 {
02087   struct trace_state_variable *tsv;
02088 
02089   tsv = get_trace_state_variable (num);
02090   if (tsv != NULL)
02091     return tsv;
02092 
02093   /* Create a new variable.  */
02094   tsv = xmalloc (sizeof (struct trace_state_variable));
02095   tsv->number = num;
02096   tsv->initial_value = 0;
02097   tsv->value = 0;
02098   tsv->getter = NULL;
02099   tsv->name = NULL;
02100 #ifdef IN_PROCESS_AGENT
02101   if (!gdb)
02102     {
02103       tsv->next = alloced_trace_state_variables;
02104       alloced_trace_state_variables = tsv;
02105     }
02106   else
02107 #endif
02108     {
02109       tsv->next = trace_state_variables;
02110       trace_state_variables = tsv;
02111     }
02112   return tsv;
02113 }
02114 
02115 IP_AGENT_EXPORT LONGEST
02116 get_trace_state_variable_value (int num)
02117 {
02118   struct trace_state_variable *tsv;
02119 
02120   tsv = get_trace_state_variable (num);
02121 
02122   if (!tsv)
02123     {
02124       trace_debug ("No trace state variable %d, skipping value get", num);
02125       return 0;
02126     }
02127 
02128   /* Call a getter function if we have one.  While it's tempting to
02129      set up something to only call the getter once per tracepoint hit,
02130      it could run afoul of thread races. Better to let the getter
02131      handle it directly, if necessary to worry about it.  */
02132   if (tsv->getter)
02133     tsv->value = (tsv->getter) ();
02134 
02135   trace_debug ("get_trace_state_variable_value(%d) ==> %s",
02136                num, plongest (tsv->value));
02137 
02138   return tsv->value;
02139 }
02140 
02141 IP_AGENT_EXPORT void
02142 set_trace_state_variable_value (int num, LONGEST val)
02143 {
02144   struct trace_state_variable *tsv;
02145 
02146   tsv = get_trace_state_variable (num);
02147 
02148   if (!tsv)
02149     {
02150       trace_debug ("No trace state variable %d, skipping value set", num);
02151       return;
02152     }
02153 
02154   tsv->value = val;
02155 }
02156 
02157 LONGEST
02158 agent_get_trace_state_variable_value (int num)
02159 {
02160   return get_trace_state_variable_value (num);
02161 }
02162 
02163 void
02164 agent_set_trace_state_variable_value (int num, LONGEST val)
02165 {
02166   set_trace_state_variable_value (num, val);
02167 }
02168 
02169 static void
02170 set_trace_state_variable_name (int num, const char *name)
02171 {
02172   struct trace_state_variable *tsv;
02173 
02174   tsv = get_trace_state_variable (num);
02175 
02176   if (!tsv)
02177     {
02178       trace_debug ("No trace state variable %d, skipping name set", num);
02179       return;
02180     }
02181 
02182   tsv->name = (char *) name;
02183 }
02184 
02185 static void
02186 set_trace_state_variable_getter (int num, LONGEST (*getter) (void))
02187 {
02188   struct trace_state_variable *tsv;
02189 
02190   tsv = get_trace_state_variable (num);
02191 
02192   if (!tsv)
02193     {
02194       trace_debug ("No trace state variable %d, skipping getter set", num);
02195       return;
02196     }
02197 
02198   tsv->getter = getter;
02199 }
02200 
02201 /* Add a raw traceframe for the given tracepoint.  */
02202 
02203 static struct traceframe *
02204 add_traceframe (struct tracepoint *tpoint)
02205 {
02206   struct traceframe *tframe;
02207 
02208   tframe = trace_buffer_alloc (sizeof (struct traceframe));
02209 
02210   if (tframe == NULL)
02211     return NULL;
02212 
02213   tframe->tpnum = tpoint->number;
02214   tframe->data_size = 0;
02215 
02216   return tframe;
02217 }
02218 
02219 /* Add a block to the traceframe currently being worked on.  */
02220 
02221 static unsigned char *
02222 add_traceframe_block (struct traceframe *tframe,
02223                       struct tracepoint *tpoint, int amt)
02224 {
02225   unsigned char *block;
02226 
02227   if (!tframe)
02228     return NULL;
02229 
02230   block = trace_buffer_alloc (amt);
02231 
02232   if (!block)
02233     return NULL;
02234 
02235   gdb_assert (tframe->tpnum == tpoint->number);
02236 
02237   tframe->data_size += amt;
02238   tpoint->traceframe_usage += amt;
02239 
02240   return block;
02241 }
02242 
02243 /* Flag that the current traceframe is finished.  */
02244 
02245 static void
02246 finish_traceframe (struct traceframe *tframe)
02247 {
02248   ++traceframe_write_count;
02249   ++traceframes_created;
02250 }
02251 
02252 #ifndef IN_PROCESS_AGENT
02253 
02254 /* Given a traceframe number NUM, find the NUMth traceframe in the
02255    buffer.  */
02256 
02257 static struct traceframe *
02258 find_traceframe (int num)
02259 {
02260   struct traceframe *tframe;
02261   int tfnum = 0;
02262 
02263   for (tframe = FIRST_TRACEFRAME ();
02264        tframe->tpnum != 0;
02265        tframe = NEXT_TRACEFRAME (tframe))
02266     {
02267       if (tfnum == num)
02268         return tframe;
02269       ++tfnum;
02270     }
02271 
02272   return NULL;
02273 }
02274 
02275 static CORE_ADDR
02276 get_traceframe_address (struct traceframe *tframe)
02277 {
02278   CORE_ADDR addr;
02279   struct tracepoint *tpoint;
02280 
02281   addr = traceframe_get_pc (tframe);
02282 
02283   if (addr)
02284     return addr;
02285 
02286   /* Fallback strategy, will be incorrect for while-stepping frames
02287      and multi-location tracepoints.  */
02288   tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
02289   return tpoint->address;
02290 }
02291 
02292 /* Search for the next traceframe whose address is inside or outside
02293    the given range.  */
02294 
02295 static struct traceframe *
02296 find_next_traceframe_in_range (CORE_ADDR lo, CORE_ADDR hi, int inside_p,
02297                                int *tfnump)
02298 {
02299   struct traceframe *tframe;
02300   CORE_ADDR tfaddr;
02301 
02302   *tfnump = current_traceframe + 1;
02303   tframe = find_traceframe (*tfnump);
02304   /* The search is not supposed to wrap around.  */
02305   if (!tframe)
02306     {
02307       *tfnump = -1;
02308       return NULL;
02309     }
02310 
02311   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
02312     {
02313       tfaddr = get_traceframe_address (tframe);
02314       if (inside_p
02315           ? (lo <= tfaddr && tfaddr <= hi)
02316           : (lo > tfaddr || tfaddr > hi))
02317         return tframe;
02318       ++*tfnump;
02319     }
02320 
02321   *tfnump = -1;
02322   return NULL;
02323 }
02324 
02325 /* Search for the next traceframe recorded by the given tracepoint.
02326    Note that for multi-location tracepoints, this will find whatever
02327    location appears first.  */
02328 
02329 static struct traceframe *
02330 find_next_traceframe_by_tracepoint (int num, int *tfnump)
02331 {
02332   struct traceframe *tframe;
02333 
02334   *tfnump = current_traceframe + 1;
02335   tframe = find_traceframe (*tfnump);
02336   /* The search is not supposed to wrap around.  */
02337   if (!tframe)
02338     {
02339       *tfnump = -1;
02340       return NULL;
02341     }
02342 
02343   for (; tframe->tpnum != 0; tframe = NEXT_TRACEFRAME (tframe))
02344     {
02345       if (tframe->tpnum == num)
02346         return tframe;
02347       ++*tfnump;
02348     }
02349 
02350   *tfnump = -1;
02351   return NULL;
02352 }
02353 
02354 #endif
02355 
02356 #ifndef IN_PROCESS_AGENT
02357 
02358 /* Clear all past trace state.  */
02359 
02360 static void
02361 cmd_qtinit (char *packet)
02362 {
02363   struct trace_state_variable *tsv, *prev, *next;
02364 
02365   /* Make sure we don't try to read from a trace frame.  */
02366   current_traceframe = -1;
02367 
02368   stop_tracing ();
02369 
02370   trace_debug ("Initializing the trace");
02371 
02372   clear_installed_tracepoints ();
02373   clear_readonly_regions ();
02374 
02375   tracepoints = NULL;
02376   last_tracepoint = NULL;
02377 
02378   /* Clear out any leftover trace state variables.  Ones with target
02379      defined getters should be kept however.  */
02380   prev = NULL;
02381   tsv = trace_state_variables;
02382   while (tsv)
02383     {
02384       trace_debug ("Looking at var %d", tsv->number);
02385       if (tsv->getter == NULL)
02386         {
02387           next = tsv->next;
02388           if (prev)
02389             prev->next = next;
02390           else
02391             trace_state_variables = next;
02392           trace_debug ("Deleting var %d", tsv->number);
02393           free (tsv);
02394           tsv = next;
02395         }
02396       else
02397         {
02398           prev = tsv;
02399           tsv = tsv->next;
02400         }
02401     }
02402 
02403   clear_trace_buffer ();
02404   clear_inferior_trace_buffer ();
02405 
02406   write_ok (packet);
02407 }
02408 
02409 /* Unprobe the UST marker at ADDRESS.  */
02410 
02411 static void
02412 unprobe_marker_at (CORE_ADDR address)
02413 {
02414   char cmd[IPA_CMD_BUF_SIZE];
02415 
02416   sprintf (cmd, "unprobe_marker_at:%s", paddress (address));
02417   run_inferior_command (cmd, strlen (cmd) + 1);
02418 }
02419 
02420 /* Restore the program to its pre-tracing state.  This routine may be called
02421    in error situations, so it needs to be careful about only restoring
02422    from known-valid bits.  */
02423 
02424 static void
02425 clear_installed_tracepoints (void)
02426 {
02427   struct tracepoint *tpoint;
02428   struct tracepoint *prev_stpoint;
02429 
02430   pause_all (1);
02431   cancel_breakpoints ();
02432 
02433   prev_stpoint = NULL;
02434 
02435   /* Restore any bytes overwritten by tracepoints.  */
02436   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
02437     {
02438       /* Catch the case where we might try to remove a tracepoint that
02439          was never actually installed.  */
02440       if (tpoint->handle == NULL)
02441         {
02442           trace_debug ("Tracepoint %d at 0x%s was "
02443                        "never installed, nothing to clear",
02444                        tpoint->number, paddress (tpoint->address));
02445           continue;
02446         }
02447 
02448       switch (tpoint->type)
02449         {
02450         case trap_tracepoint:
02451           delete_breakpoint (tpoint->handle);
02452           break;
02453         case fast_tracepoint:
02454           delete_fast_tracepoint_jump (tpoint->handle);
02455           break;
02456         case static_tracepoint:
02457           if (prev_stpoint != NULL
02458               && prev_stpoint->address == tpoint->address)
02459             /* Nothing to do.  We already unprobed a tracepoint set at
02460                this marker address (and there can only be one probe
02461                per marker).  */
02462             ;
02463           else
02464             {
02465               unprobe_marker_at (tpoint->address);
02466               prev_stpoint = tpoint;
02467             }
02468           break;
02469         }
02470 
02471       tpoint->handle = NULL;
02472     }
02473 
02474   unpause_all (1);
02475 }
02476 
02477 /* Parse a packet that defines a tracepoint.  */
02478 
02479 static void
02480 cmd_qtdp (char *own_buf)
02481 {
02482   int tppacket;
02483   /* Whether there is a trailing hyphen at the end of the QTDP packet.  */
02484   int trail_hyphen = 0;
02485   ULONGEST num;
02486   ULONGEST addr;
02487   ULONGEST count;
02488   struct tracepoint *tpoint;
02489   char *actparm;
02490   char *packet = own_buf;
02491 
02492   packet += strlen ("QTDP:");
02493 
02494   /* A hyphen at the beginning marks a packet specifying actions for a
02495      tracepoint already supplied.  */
02496   tppacket = 1;
02497   if (*packet == '-')
02498     {
02499       tppacket = 0;
02500       ++packet;
02501     }
02502   packet = unpack_varlen_hex (packet, &num);
02503   ++packet; /* skip a colon */
02504   packet = unpack_varlen_hex (packet, &addr);
02505   ++packet; /* skip a colon */
02506 
02507   /* See if we already have this tracepoint.  */
02508   tpoint = find_tracepoint (num, addr);
02509 
02510   if (tppacket)
02511     {
02512       /* Duplicate tracepoints are never allowed.  */
02513       if (tpoint)
02514         {
02515           trace_debug ("Tracepoint error: tracepoint %d"
02516                        " at 0x%s already exists",
02517                        (int) num, paddress (addr));
02518           write_enn (own_buf);
02519           return;
02520         }
02521 
02522       tpoint = add_tracepoint (num, addr);
02523 
02524       tpoint->enabled = (*packet == 'E');
02525       ++packet; /* skip 'E' */
02526       ++packet; /* skip a colon */
02527       packet = unpack_varlen_hex (packet, &count);
02528       tpoint->step_count = count;
02529       ++packet; /* skip a colon */
02530       packet = unpack_varlen_hex (packet, &count);
02531       tpoint->pass_count = count;
02532       /* See if we have any of the additional optional fields.  */
02533       while (*packet == ':')
02534         {
02535           ++packet;
02536           if (*packet == 'F')
02537             {
02538               tpoint->type = fast_tracepoint;
02539               ++packet;
02540               packet = unpack_varlen_hex (packet, &count);
02541               tpoint->orig_size = count;
02542             }
02543           else if (*packet == 'S')
02544             {
02545               tpoint->type = static_tracepoint;
02546               ++packet;
02547             }
02548           else if (*packet == 'X')
02549             {
02550               actparm = (char *) packet;
02551               tpoint->cond = gdb_parse_agent_expr (&actparm);
02552               packet = actparm;
02553             }
02554           else if (*packet == '-')
02555             break;
02556           else if (*packet == '\0')
02557             break;
02558           else
02559             trace_debug ("Unknown optional tracepoint field");
02560         }
02561       if (*packet == '-')
02562         {
02563           trail_hyphen = 1;
02564           trace_debug ("Also has actions\n");
02565         }
02566 
02567       trace_debug ("Defined %stracepoint %d at 0x%s, "
02568                    "enabled %d step %" PRIu64 " pass %" PRIu64,
02569                    tpoint->type == fast_tracepoint ? "fast "
02570                    : tpoint->type == static_tracepoint ? "static " : "",
02571                    tpoint->number, paddress (tpoint->address), tpoint->enabled,
02572                    tpoint->step_count, tpoint->pass_count);
02573     }
02574   else if (tpoint)
02575     add_tracepoint_action (tpoint, packet);
02576   else
02577     {
02578       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
02579                    (int) num, paddress (addr));
02580       write_enn (own_buf);
02581       return;
02582     }
02583 
02584   /* Install tracepoint during tracing only once for each tracepoint location.
02585      For each tracepoint loc, GDB may send multiple QTDP packets, and we can
02586      determine the last QTDP packet for one tracepoint location by checking
02587      trailing hyphen in QTDP packet.  */
02588   if (tracing && !trail_hyphen)
02589     {
02590       struct tracepoint *tp = NULL;
02591 
02592       /* Pause all threads temporarily while we patch tracepoints.  */
02593       pause_all (0);
02594 
02595       /* download_tracepoint will update global `tracepoints'
02596          list, so it is unsafe to leave threads in jump pad.  */
02597       stabilize_threads ();
02598 
02599       /* Freeze threads.  */
02600       pause_all (1);
02601 
02602 
02603       if (tpoint->type != trap_tracepoint)
02604         {
02605           /* Find another fast or static tracepoint at the same address.  */
02606           for (tp = tracepoints; tp; tp = tp->next)
02607             {
02608               if (tp->address == tpoint->address && tp->type == tpoint->type
02609                   && tp->number != tpoint->number)
02610                 break;
02611             }
02612 
02613           /* TPOINT is installed at the same address as TP.  */
02614           if (tp)
02615             {
02616               if (tpoint->type == fast_tracepoint)
02617                 clone_fast_tracepoint (tpoint, tp);
02618               else if (tpoint->type == static_tracepoint)
02619                 tpoint->handle = (void *) -1;
02620             }
02621         }
02622 
02623       if (use_agent && tpoint->type == fast_tracepoint
02624           && agent_capability_check (AGENT_CAPA_FAST_TRACE))
02625         {
02626           /* Download and install fast tracepoint by agent.  */
02627           if (tracepoint_send_agent (tpoint) == 0)
02628             write_ok (own_buf);
02629           else
02630             {
02631               write_enn (own_buf);
02632               remove_tracepoint (tpoint);
02633             }
02634         }
02635       else
02636         {
02637           download_tracepoint (tpoint);
02638 
02639           if (tpoint->type == trap_tracepoint || tp == NULL)
02640             {
02641               install_tracepoint (tpoint, own_buf);
02642               if (strcmp (own_buf, "OK") != 0)
02643                 remove_tracepoint (tpoint);
02644             }
02645           else
02646             write_ok (own_buf);
02647         }
02648 
02649       unpause_all (1);
02650       return;
02651     }
02652 
02653   write_ok (own_buf);
02654 }
02655 
02656 static void
02657 cmd_qtdpsrc (char *own_buf)
02658 {
02659   ULONGEST num, addr, start, slen;
02660   struct tracepoint *tpoint;
02661   char *packet = own_buf;
02662   char *saved, *srctype, *src;
02663   size_t nbytes;
02664   struct source_string *last, *newlast;
02665 
02666   packet += strlen ("QTDPsrc:");
02667 
02668   packet = unpack_varlen_hex (packet, &num);
02669   ++packet; /* skip a colon */
02670   packet = unpack_varlen_hex (packet, &addr);
02671   ++packet; /* skip a colon */
02672 
02673   /* See if we already have this tracepoint.  */
02674   tpoint = find_tracepoint (num, addr);
02675 
02676   if (!tpoint)
02677     {
02678       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
02679                    (int) num, paddress (addr));
02680       write_enn (own_buf);
02681       return;
02682     }
02683 
02684   saved = packet;
02685   packet = strchr (packet, ':');
02686   srctype = xmalloc (packet - saved + 1);
02687   memcpy (srctype, saved, packet - saved);
02688   srctype[packet - saved] = '\0';
02689   ++packet;
02690   packet = unpack_varlen_hex (packet, &start);
02691   ++packet; /* skip a colon */
02692   packet = unpack_varlen_hex (packet, &slen);
02693   ++packet; /* skip a colon */
02694   src = xmalloc (slen + 1);
02695   nbytes = unhexify (src, packet, strlen (packet) / 2);
02696   src[nbytes] = '\0';
02697 
02698   newlast = xmalloc (sizeof (struct source_string));
02699   newlast->type = srctype;
02700   newlast->str = src;
02701   newlast->next = NULL;
02702   /* Always add a source string to the end of the list;
02703      this keeps sequences of actions/commands in the right
02704      order.  */
02705   if (tpoint->source_strings)
02706     {
02707       for (last = tpoint->source_strings; last->next; last = last->next)
02708         ;
02709       last->next = newlast;
02710     }
02711   else
02712     tpoint->source_strings = newlast;
02713 
02714   write_ok (own_buf);
02715 }
02716 
02717 static void
02718 cmd_qtdv (char *own_buf)
02719 {
02720   ULONGEST num, val, builtin;
02721   char *varname;
02722   size_t nbytes;
02723   struct trace_state_variable *tsv;
02724   char *packet = own_buf;
02725 
02726   packet += strlen ("QTDV:");
02727 
02728   packet = unpack_varlen_hex (packet, &num);
02729   ++packet; /* skip a colon */
02730   packet = unpack_varlen_hex (packet, &val);
02731   ++packet; /* skip a colon */
02732   packet = unpack_varlen_hex (packet, &builtin);
02733   ++packet; /* skip a colon */
02734 
02735   nbytes = strlen (packet) / 2;
02736   varname = xmalloc (nbytes + 1);
02737   nbytes = unhexify (varname, packet, nbytes);
02738   varname[nbytes] = '\0';
02739 
02740   tsv = create_trace_state_variable (num, 1);
02741   tsv->initial_value = (LONGEST) val;
02742   tsv->name = varname;
02743 
02744   set_trace_state_variable_value (num, (LONGEST) val);
02745 
02746   write_ok (own_buf);
02747 }
02748 
02749 static void
02750 cmd_qtenable_disable (char *own_buf, int enable)
02751 {
02752   char *packet = own_buf;
02753   ULONGEST num, addr;
02754   struct tracepoint *tp;
02755 
02756   packet += strlen (enable ? "QTEnable:" : "QTDisable:");
02757   packet = unpack_varlen_hex (packet, &num);
02758   ++packet; /* skip a colon */
02759   packet = unpack_varlen_hex (packet, &addr);
02760 
02761   tp = find_tracepoint (num, addr);
02762 
02763   if (tp)
02764     {
02765       if ((enable && tp->enabled) || (!enable && !tp->enabled))
02766         {
02767           trace_debug ("Tracepoint %d at 0x%s is already %s",
02768                        (int) num, paddress (addr),
02769                        enable ? "enabled" : "disabled");
02770           write_ok (own_buf);
02771           return;
02772         }
02773 
02774       trace_debug ("%s tracepoint %d at 0x%s",
02775                    enable ? "Enabling" : "Disabling",
02776                    (int) num, paddress (addr));
02777 
02778       tp->enabled = enable;
02779 
02780       if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
02781         {
02782           int ret;
02783           int offset = offsetof (struct tracepoint, enabled);
02784           CORE_ADDR obj_addr = tp->obj_addr_on_target + offset;
02785 
02786           ret = prepare_to_access_memory ();
02787           if (ret)
02788             {
02789               trace_debug ("Failed to temporarily stop inferior threads");
02790               write_enn (own_buf);
02791               return;
02792             }
02793           
02794           ret = write_inferior_integer (obj_addr, enable);
02795           done_accessing_memory ();
02796           
02797           if (ret)
02798             {
02799               trace_debug ("Cannot write enabled flag into "
02800                            "inferior process memory");
02801               write_enn (own_buf);
02802               return;
02803             }
02804         }
02805 
02806       write_ok (own_buf);
02807     }
02808   else
02809     {
02810       trace_debug ("Tracepoint %d at 0x%s not found",
02811                    (int) num, paddress (addr));
02812       write_enn (own_buf);
02813     }
02814 }
02815 
02816 static void
02817 cmd_qtv (char *own_buf)
02818 {
02819   ULONGEST num;
02820   LONGEST val = 0;
02821   int err;
02822   char *packet = own_buf;
02823 
02824   packet += strlen ("qTV:");
02825   unpack_varlen_hex (packet, &num);
02826 
02827   if (current_traceframe >= 0)
02828     {
02829       err = traceframe_read_tsv ((int) num, &val);
02830       if (err)
02831         {
02832           strcpy (own_buf, "U");
02833           return;
02834         }
02835     }
02836   /* Only make tsv's be undefined before the first trace run.  After a
02837      trace run is over, the user might want to see the last value of
02838      the tsv, and it might not be available in a traceframe.  */
02839   else if (!tracing && strcmp (tracing_stop_reason, "tnotrun") == 0)
02840     {
02841       strcpy (own_buf, "U");
02842       return;
02843     }
02844   else
02845     val = get_trace_state_variable_value (num);
02846 
02847   sprintf (own_buf, "V%s", phex_nz (val, 0));
02848 }
02849 
02850 /* Clear out the list of readonly regions.  */
02851 
02852 static void
02853 clear_readonly_regions (void)
02854 {
02855   struct readonly_region *roreg;
02856 
02857   while (readonly_regions)
02858     {
02859       roreg = readonly_regions;
02860       readonly_regions = readonly_regions->next;
02861       free (roreg);
02862     }
02863 }
02864 
02865 /* Parse the collection of address ranges whose contents GDB believes
02866    to be unchanging and so can be read directly from target memory
02867    even while looking at a traceframe.  */
02868 
02869 static void
02870 cmd_qtro (char *own_buf)
02871 {
02872   ULONGEST start, end;
02873   struct readonly_region *roreg;
02874   char *packet = own_buf;
02875 
02876   trace_debug ("Want to mark readonly regions");
02877 
02878   clear_readonly_regions ();
02879 
02880   packet += strlen ("QTro");
02881 
02882   while (*packet == ':')
02883     {
02884       ++packet;  /* skip a colon */
02885       packet = unpack_varlen_hex (packet, &start);
02886       ++packet;  /* skip a comma */
02887       packet = unpack_varlen_hex (packet, &end);
02888       roreg = xmalloc (sizeof (struct readonly_region));
02889       roreg->start = start;
02890       roreg->end = end;
02891       roreg->next = readonly_regions;
02892       readonly_regions = roreg;
02893       trace_debug ("Added readonly region from 0x%s to 0x%s",
02894                    paddress (roreg->start), paddress (roreg->end));
02895     }
02896 
02897   write_ok (own_buf);
02898 }
02899 
02900 /* Test to see if the given range is in our list of readonly ranges.
02901    We only test for being entirely within a range, GDB is not going to
02902    send a single memory packet that spans multiple regions.  */
02903 
02904 int
02905 in_readonly_region (CORE_ADDR addr, ULONGEST length)
02906 {
02907   struct readonly_region *roreg;
02908 
02909   for (roreg = readonly_regions; roreg; roreg = roreg->next)
02910     if (roreg->start <= addr && (addr + length - 1) <= roreg->end)
02911       return 1;
02912 
02913   return 0;
02914 }
02915 
02916 /* The maximum size of a jump pad entry.  */
02917 static const int max_jump_pad_size = 0x100;
02918 
02919 static CORE_ADDR gdb_jump_pad_head;
02920 
02921 /* Return the address of the next free jump space.  */
02922 
02923 static CORE_ADDR
02924 get_jump_space_head (void)
02925 {
02926   if (gdb_jump_pad_head == 0)
02927     {
02928       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
02929                                       &gdb_jump_pad_head))
02930         fatal ("error extracting jump_pad_buffer");
02931     }
02932 
02933   return gdb_jump_pad_head;
02934 }
02935 
02936 /* Reserve USED bytes from the jump space.  */
02937 
02938 static void
02939 claim_jump_space (ULONGEST used)
02940 {
02941   trace_debug ("claim_jump_space reserves %s bytes at %s",
02942                pulongest (used), paddress (gdb_jump_pad_head));
02943   gdb_jump_pad_head += used;
02944 }
02945 
02946 static CORE_ADDR trampoline_buffer_head = 0;
02947 static CORE_ADDR trampoline_buffer_tail;
02948 
02949 /* Reserve USED bytes from the trampoline buffer and return the
02950    address of the start of the reserved space in TRAMPOLINE.  Returns
02951    non-zero if the space is successfully claimed.  */
02952 
02953 int
02954 claim_trampoline_space (ULONGEST used, CORE_ADDR *trampoline)
02955 {
02956   if (!trampoline_buffer_head)
02957     {
02958       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
02959                                       &trampoline_buffer_tail))
02960         {
02961           fatal ("error extracting trampoline_buffer");
02962           return 0;
02963         }
02964 
02965       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
02966                                       &trampoline_buffer_head))
02967         {
02968           fatal ("error extracting trampoline_buffer_end");
02969           return 0;
02970         }
02971     }
02972 
02973   /* Start claiming space from the top of the trampoline space.  If
02974      the space is located at the bottom of the virtual address space,
02975      this reduces the possibility that corruption will occur if a null
02976      pointer is used to write to memory.  */
02977   if (trampoline_buffer_head - trampoline_buffer_tail < used)
02978     {
02979       trace_debug ("claim_trampoline_space failed to reserve %s bytes",
02980                    pulongest (used));
02981       return 0;
02982     }
02983 
02984   trampoline_buffer_head -= used;
02985 
02986   trace_debug ("claim_trampoline_space reserves %s bytes at %s",
02987                pulongest (used), paddress (trampoline_buffer_head));
02988 
02989   *trampoline = trampoline_buffer_head;
02990   return 1;
02991 }
02992 
02993 /* Returns non-zero if there is space allocated for use in trampolines
02994    for fast tracepoints.  */
02995 
02996 int
02997 have_fast_tracepoint_trampoline_buffer (char *buf)
02998 {
02999   CORE_ADDR trampoline_end, errbuf;
03000 
03001   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
03002                                   &trampoline_end))
03003     {
03004       fatal ("error extracting trampoline_buffer_end");
03005       return 0;
03006     }
03007   
03008   if (buf)
03009     {
03010       buf[0] = '\0';
03011       strcpy (buf, "was claiming");
03012       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_error,
03013                                   &errbuf))
03014         {
03015           fatal ("error extracting errbuf");
03016           return 0;
03017         }
03018 
03019       read_inferior_memory (errbuf, (unsigned char *) buf, 100);
03020     }
03021 
03022   return trampoline_end != 0;
03023 }
03024 
03025 /* Ask the IPA to probe the marker at ADDRESS.  Returns -1 if running
03026    the command fails, or 0 otherwise.  If the command ran
03027    successfully, but probing the marker failed, ERROUT will be filled
03028    with the error to reply to GDB, and -1 is also returned.  This
03029    allows directly passing IPA errors to GDB.  */
03030 
03031 static int
03032 probe_marker_at (CORE_ADDR address, char *errout)
03033 {
03034   char cmd[IPA_CMD_BUF_SIZE];
03035   int err;
03036 
03037   sprintf (cmd, "probe_marker_at:%s", paddress (address));
03038   err = run_inferior_command (cmd, strlen (cmd) + 1);
03039 
03040   if (err == 0)
03041     {
03042       if (*cmd == 'E')
03043         {
03044           strcpy (errout, cmd);
03045           return -1;
03046         }
03047     }
03048 
03049   return err;
03050 }
03051 
03052 static void
03053 clone_fast_tracepoint (struct tracepoint *to, const struct tracepoint *from)
03054 {
03055   to->jump_pad = from->jump_pad;
03056   to->jump_pad_end = from->jump_pad_end;
03057   to->trampoline = from->trampoline;
03058   to->trampoline_end = from->trampoline_end;
03059   to->adjusted_insn_addr = from->adjusted_insn_addr;
03060   to->adjusted_insn_addr_end = from->adjusted_insn_addr_end;
03061   to->handle = from->handle;
03062 
03063   gdb_assert (from->handle);
03064   inc_ref_fast_tracepoint_jump ((struct fast_tracepoint_jump *) from->handle);
03065 }
03066 
03067 #define MAX_JUMP_SIZE 20
03068 
03069 /* Install fast tracepoint.  Return 0 if successful, otherwise return
03070    non-zero.  */
03071 
03072 static int
03073 install_fast_tracepoint (struct tracepoint *tpoint, char *errbuf)
03074 {
03075   CORE_ADDR jentry, jump_entry;
03076   CORE_ADDR trampoline;
03077   ULONGEST trampoline_size;
03078   int err = 0;
03079   /* The jump to the jump pad of the last fast tracepoint
03080      installed.  */
03081   unsigned char fjump[MAX_JUMP_SIZE];
03082   ULONGEST fjump_size;
03083 
03084   if (tpoint->orig_size < target_get_min_fast_tracepoint_insn_len ())
03085     {
03086       trace_debug ("Requested a fast tracepoint on an instruction "
03087                    "that is of less than the minimum length.");
03088       return 0;
03089     }
03090 
03091   jentry = jump_entry = get_jump_space_head ();
03092 
03093   trampoline = 0;
03094   trampoline_size = 0;
03095 
03096   /* Install the jump pad.  */
03097   err = install_fast_tracepoint_jump_pad (tpoint->obj_addr_on_target,
03098                                           tpoint->address,
03099                                           ipa_sym_addrs.addr_gdb_collect,
03100                                           ipa_sym_addrs.addr_collecting,
03101                                           tpoint->orig_size,
03102                                           &jentry,
03103                                           &trampoline, &trampoline_size,
03104                                           fjump, &fjump_size,
03105                                           &tpoint->adjusted_insn_addr,
03106                                           &tpoint->adjusted_insn_addr_end,
03107                                           errbuf);
03108 
03109   if (err)
03110     return 1;
03111 
03112   /* Wire it in.  */
03113   tpoint->handle = set_fast_tracepoint_jump (tpoint->address, fjump,
03114                                              fjump_size);
03115 
03116   if (tpoint->handle != NULL)
03117     {
03118       tpoint->jump_pad = jump_entry;
03119       tpoint->jump_pad_end = jentry;
03120       tpoint->trampoline = trampoline;
03121       tpoint->trampoline_end = trampoline + trampoline_size;
03122 
03123       /* Pad to 8-byte alignment.  */
03124       jentry = ((jentry + 7) & ~0x7);
03125       claim_jump_space (jentry - jump_entry);
03126     }
03127 
03128   return 0;
03129 }
03130 
03131 
03132 /* Install tracepoint TPOINT, and write reply message in OWN_BUF.  */
03133 
03134 static void
03135 install_tracepoint (struct tracepoint *tpoint, char *own_buf)
03136 {
03137   tpoint->handle = NULL;
03138   *own_buf = '\0';
03139 
03140   if (tpoint->type == trap_tracepoint)
03141     {
03142       /* Tracepoints are installed as memory breakpoints.  Just go
03143          ahead and install the trap.  The breakpoints module
03144          handles duplicated breakpoints, and the memory read
03145          routine handles un-patching traps from memory reads.  */
03146       tpoint->handle = set_breakpoint_at (tpoint->address,
03147                                           tracepoint_handler);
03148     }
03149   else if (tpoint->type == fast_tracepoint || tpoint->type == static_tracepoint)
03150     {
03151       if (!agent_loaded_p ())
03152         {
03153           trace_debug ("Requested a %s tracepoint, but fast "
03154                        "tracepoints aren't supported.",
03155                        tpoint->type == static_tracepoint ? "static" : "fast");
03156           write_e_ipa_not_loaded (own_buf);
03157           return;
03158         }
03159       if (tpoint->type == static_tracepoint
03160           && !in_process_agent_supports_ust ())
03161         {
03162           trace_debug ("Requested a static tracepoint, but static "
03163                        "tracepoints are not supported.");
03164           write_e_ust_not_loaded (own_buf);
03165           return;
03166         }
03167 
03168       if (tpoint->type == fast_tracepoint)
03169         install_fast_tracepoint (tpoint, own_buf);
03170       else
03171         {
03172           if (probe_marker_at (tpoint->address, own_buf) == 0)
03173             tpoint->handle = (void *) -1;
03174         }
03175 
03176     }
03177   else
03178     internal_error (__FILE__, __LINE__, "Unknown tracepoint type");
03179 
03180   if (tpoint->handle == NULL)
03181     {
03182       if (*own_buf == '\0')
03183         write_enn (own_buf);
03184     }
03185   else
03186     write_ok (own_buf);
03187 }
03188 
03189 static void download_tracepoint_1 (struct tracepoint *tpoint);
03190 
03191 static void
03192 cmd_qtstart (char *packet)
03193 {
03194   struct tracepoint *tpoint, *prev_ftpoint, *prev_stpoint;
03195   CORE_ADDR tpptr = 0, prev_tpptr = 0;
03196 
03197   trace_debug ("Starting the trace");
03198 
03199   /* Pause all threads temporarily while we patch tracepoints.  */
03200   pause_all (0);
03201 
03202   /* Get threads out of jump pads.  Safe to do here, since this is a
03203      top level command.  And, required to do here, since we're
03204      deleting/rewriting jump pads.  */
03205 
03206   stabilize_threads ();
03207 
03208   /* Freeze threads.  */
03209   pause_all (1);
03210 
03211   /* Sync the fast tracepoints list in the inferior ftlib.  */
03212   if (agent_loaded_p ())
03213     download_trace_state_variables ();
03214 
03215   /* No previous fast tpoint yet.  */
03216   prev_ftpoint = NULL;
03217 
03218   /* No previous static tpoint yet.  */
03219   prev_stpoint = NULL;
03220 
03221   *packet = '\0';
03222 
03223   /* Start out empty.  */
03224   if (agent_loaded_p ())
03225     write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, 0);
03226 
03227   /* Download and install tracepoints.  */
03228   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
03229     {
03230       /* Ensure all the hit counts start at zero.  */
03231       tpoint->hit_count = 0;
03232       tpoint->traceframe_usage = 0;
03233 
03234       if (tpoint->type == trap_tracepoint)
03235         {
03236           /* Tracepoints are installed as memory breakpoints.  Just go
03237              ahead and install the trap.  The breakpoints module
03238              handles duplicated breakpoints, and the memory read
03239              routine handles un-patching traps from memory reads.  */
03240           tpoint->handle = set_breakpoint_at (tpoint->address,
03241                                               tracepoint_handler);
03242         }
03243       else if (tpoint->type == fast_tracepoint
03244                || tpoint->type == static_tracepoint)
03245         {
03246           if (maybe_write_ipa_not_loaded (packet))
03247             {
03248               trace_debug ("Requested a %s tracepoint, but fast "
03249                            "tracepoints aren't supported.",
03250                            tpoint->type == static_tracepoint
03251                            ? "static" : "fast");
03252               break;
03253             }
03254 
03255           if (tpoint->type == fast_tracepoint)
03256             {
03257               int use_agent_p
03258                 = use_agent && agent_capability_check (AGENT_CAPA_FAST_TRACE);
03259 
03260               if (prev_ftpoint != NULL
03261                   && prev_ftpoint->address == tpoint->address)
03262                 {
03263                   if (use_agent_p)
03264                     tracepoint_send_agent (tpoint);
03265                   else
03266                     download_tracepoint_1 (tpoint);
03267 
03268                   clone_fast_tracepoint (tpoint, prev_ftpoint);
03269                 }
03270               else
03271                 {
03272                   /* Tracepoint is installed successfully?  */
03273                   int installed = 0;
03274 
03275                   /* Download and install fast tracepoint by agent.  */
03276                   if (use_agent_p)
03277                     installed = !tracepoint_send_agent (tpoint);
03278                   else
03279                     {
03280                       download_tracepoint_1 (tpoint);
03281                       installed = !install_fast_tracepoint (tpoint, packet);
03282                     }
03283 
03284                   if (installed)
03285                     prev_ftpoint = tpoint;
03286                 }
03287             }
03288           else
03289             {
03290               if (!in_process_agent_supports_ust ())
03291                 {
03292                   trace_debug ("Requested a static tracepoint, but static "
03293                                "tracepoints are not supported.");
03294                   break;
03295                 }
03296 
03297               download_tracepoint_1 (tpoint);
03298               /* Can only probe a given marker once.  */
03299               if (prev_stpoint != NULL
03300                   && prev_stpoint->address == tpoint->address)
03301                 tpoint->handle = (void *) -1;
03302               else
03303                 {
03304                   if (probe_marker_at (tpoint->address, packet) == 0)
03305                     {
03306                       tpoint->handle = (void *) -1;
03307 
03308                       /* So that we can handle multiple static tracepoints
03309                          at the same address easily.  */
03310                       prev_stpoint = tpoint;
03311                     }
03312                 }
03313             }
03314 
03315           prev_tpptr = tpptr;
03316           tpptr = tpoint->obj_addr_on_target;
03317 
03318           if (tpoint == tracepoints)
03319             /* First object in list, set the head pointer in the
03320                inferior.  */
03321             write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints, tpptr);
03322           else
03323             write_inferior_data_ptr (prev_tpptr + offsetof (struct tracepoint,
03324                                                             next),
03325                                      tpptr);
03326         }
03327 
03328       /* Any failure in the inner loop is sufficient cause to give
03329          up.  */
03330       if (tpoint->handle == NULL)
03331         break;
03332     }
03333 
03334   /* Any error in tracepoint insertion is unacceptable; better to
03335      address the problem now, than end up with a useless or misleading
03336      trace run.  */
03337   if (tpoint != NULL)
03338     {
03339       clear_installed_tracepoints ();
03340       if (*packet == '\0')
03341         write_enn (packet);
03342       unpause_all (1);
03343       return;
03344     }
03345 
03346   stopping_tracepoint = NULL;
03347   trace_buffer_is_full = 0;
03348   expr_eval_result = expr_eval_no_error;
03349   error_tracepoint = NULL;
03350   tracing_start_time = get_timestamp ();
03351 
03352   /* Tracing is now active, hits will now start being logged.  */
03353   tracing = 1;
03354 
03355   if (agent_loaded_p ())
03356     {
03357       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 1))
03358         fatal ("Error setting tracing variable in lib");
03359 
03360       if (write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
03361                                        0))
03362         fatal ("Error clearing stopping_tracepoint variable in lib");
03363 
03364       if (write_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full, 0))
03365         fatal ("Error clearing trace_buffer_is_full variable in lib");
03366 
03367       stop_tracing_bkpt = set_breakpoint_at (ipa_sym_addrs.addr_stop_tracing,
03368                                              stop_tracing_handler);
03369       if (stop_tracing_bkpt == NULL)
03370         error ("Error setting stop_tracing breakpoint");
03371 
03372       flush_trace_buffer_bkpt
03373         = set_breakpoint_at (ipa_sym_addrs.addr_flush_trace_buffer,
03374                              flush_trace_buffer_handler);
03375       if (flush_trace_buffer_bkpt == NULL)
03376         error ("Error setting flush_trace_buffer breakpoint");
03377     }
03378 
03379   unpause_all (1);
03380 
03381   write_ok (packet);
03382 }
03383 
03384 /* End a tracing run, filling in a stop reason to report back to GDB,
03385    and removing the tracepoints from the code.  */
03386 
03387 void
03388 stop_tracing (void)
03389 {
03390   if (!tracing)
03391     {
03392       trace_debug ("Tracing is already off, ignoring");
03393       return;
03394     }
03395 
03396   trace_debug ("Stopping the trace");
03397 
03398   /* Pause all threads before removing fast jumps from memory,
03399      breakpoints, and touching IPA state variables (inferior memory).
03400      Some thread may hit the internal tracing breakpoints, or be
03401      collecting this moment, but that's ok, we don't release the
03402      tpoint object's memory or the jump pads here (we only do that
03403      when we're sure we can move all threads out of the jump pads).
03404      We can't now, since we may be getting here due to the inferior
03405      agent calling us.  */
03406   pause_all (1);
03407   /* Since we're removing breakpoints, cancel breakpoint hits,
03408      possibly related to the breakpoints we're about to delete.  */
03409   cancel_breakpoints ();
03410 
03411   /* Stop logging. Tracepoints can still be hit, but they will not be
03412      recorded.  */
03413   tracing = 0;
03414   if (agent_loaded_p ())
03415     {
03416       if (write_inferior_integer (ipa_sym_addrs.addr_tracing, 0))
03417         fatal ("Error clearing tracing variable in lib");
03418     }
03419 
03420   tracing_stop_time = get_timestamp ();
03421   tracing_stop_reason = "t???";
03422   tracing_stop_tpnum = 0;
03423   if (stopping_tracepoint)
03424     {
03425       trace_debug ("Stopping the trace because "
03426                    "tracepoint %d was hit %" PRIu64 " times",
03427                    stopping_tracepoint->number,
03428                    stopping_tracepoint->pass_count);
03429       tracing_stop_reason = "tpasscount";
03430       tracing_stop_tpnum = stopping_tracepoint->number;
03431     }
03432   else if (trace_buffer_is_full)
03433     {
03434       trace_debug ("Stopping the trace because the trace buffer is full");
03435       tracing_stop_reason = "tfull";
03436     }
03437   else if (expr_eval_result != expr_eval_no_error)
03438     {
03439       trace_debug ("Stopping the trace because of an expression eval error");
03440       tracing_stop_reason = eval_result_names[expr_eval_result];
03441       tracing_stop_tpnum = error_tracepoint->number;
03442     }
03443 #ifndef IN_PROCESS_AGENT
03444   else if (!gdb_connected ())
03445     {
03446       trace_debug ("Stopping the trace because GDB disconnected");
03447       tracing_stop_reason = "tdisconnected";
03448     }
03449 #endif
03450   else
03451     {
03452       trace_debug ("Stopping the trace because of a tstop command");
03453       tracing_stop_reason = "tstop";
03454     }
03455 
03456   stopping_tracepoint = NULL;
03457   error_tracepoint = NULL;
03458 
03459   /* Clear out the tracepoints.  */
03460   clear_installed_tracepoints ();
03461 
03462   if (agent_loaded_p ())
03463     {
03464       /* Pull in fast tracepoint trace frames from the inferior lib
03465          buffer into our buffer, even if our buffer is already full,
03466          because we want to present the full number of created frames
03467          in addition to what fit in the trace buffer.  */
03468       upload_fast_traceframes ();
03469     }
03470 
03471   if (stop_tracing_bkpt != NULL)
03472     {
03473       delete_breakpoint (stop_tracing_bkpt);
03474       stop_tracing_bkpt = NULL;
03475     }
03476 
03477   if (flush_trace_buffer_bkpt != NULL)
03478     {
03479       delete_breakpoint (flush_trace_buffer_bkpt);
03480       flush_trace_buffer_bkpt = NULL;
03481     }
03482 
03483   unpause_all (1);
03484 }
03485 
03486 static int
03487 stop_tracing_handler (CORE_ADDR addr)
03488 {
03489   trace_debug ("lib hit stop_tracing");
03490 
03491   /* Don't actually handle it here.  When we stop tracing we remove
03492      breakpoints from the inferior, and that is not allowed in a
03493      breakpoint handler (as the caller is walking the breakpoint
03494      list).  */
03495   return 0;
03496 }
03497 
03498 static int
03499 flush_trace_buffer_handler (CORE_ADDR addr)
03500 {
03501   trace_debug ("lib hit flush_trace_buffer");
03502   return 0;
03503 }
03504 
03505 static void
03506 cmd_qtstop (char *packet)
03507 {
03508   stop_tracing ();
03509   write_ok (packet);
03510 }
03511 
03512 static void
03513 cmd_qtdisconnected (char *own_buf)
03514 {
03515   ULONGEST setting;
03516   char *packet = own_buf;
03517 
03518   packet += strlen ("QTDisconnected:");
03519 
03520   unpack_varlen_hex (packet, &setting);
03521 
03522   write_ok (own_buf);
03523 
03524   disconnected_tracing = setting;
03525 }
03526 
03527 static void
03528 cmd_qtframe (char *own_buf)
03529 {
03530   ULONGEST frame, pc, lo, hi, num;
03531   int tfnum, tpnum;
03532   struct traceframe *tframe;
03533   char *packet = own_buf;
03534 
03535   packet += strlen ("QTFrame:");
03536 
03537   if (strncmp (packet, "pc:", strlen ("pc:")) == 0)
03538     {
03539       packet += strlen ("pc:");
03540       unpack_varlen_hex (packet, &pc);
03541       trace_debug ("Want to find next traceframe at pc=0x%s", paddress (pc));
03542       tframe = find_next_traceframe_in_range (pc, pc, 1, &tfnum);
03543     }
03544   else if (strncmp (packet, "range:", strlen ("range:")) == 0)
03545     {
03546       packet += strlen ("range:");
03547       packet = unpack_varlen_hex (packet, &lo);
03548       ++packet;
03549       unpack_varlen_hex (packet, &hi);
03550       trace_debug ("Want to find next traceframe in the range 0x%s to 0x%s",
03551                    paddress (lo), paddress (hi));
03552       tframe = find_next_traceframe_in_range (lo, hi, 1, &tfnum);
03553     }
03554   else if (strncmp (packet, "outside:", strlen ("outside:")) == 0)
03555     {
03556       packet += strlen ("outside:");
03557       packet = unpack_varlen_hex (packet, &lo);
03558       ++packet;
03559       unpack_varlen_hex (packet, &hi);
03560       trace_debug ("Want to find next traceframe "
03561                    "outside the range 0x%s to 0x%s",
03562                    paddress (lo), paddress (hi));
03563       tframe = find_next_traceframe_in_range (lo, hi, 0, &tfnum);
03564     }
03565   else if (strncmp (packet, "tdp:", strlen ("tdp:")) == 0)
03566     {
03567       packet += strlen ("tdp:");
03568       unpack_varlen_hex (packet, &num);
03569       tpnum = (int) num;
03570       trace_debug ("Want to find next traceframe for tracepoint %d", tpnum);
03571       tframe = find_next_traceframe_by_tracepoint (tpnum, &tfnum);
03572     }
03573   else
03574     {
03575       unpack_varlen_hex (packet, &frame);
03576       tfnum = (int) frame;
03577       if (tfnum == -1)
03578         {
03579           trace_debug ("Want to stop looking at traceframes");
03580           current_traceframe = -1;
03581           write_ok (own_buf);
03582           return;
03583         }
03584       trace_debug ("Want to look at traceframe %d", tfnum);
03585       tframe = find_traceframe (tfnum);
03586     }
03587 
03588   if (tframe)
03589     {
03590       current_traceframe = tfnum;
03591       sprintf (own_buf, "F%xT%x", tfnum, tframe->tpnum);
03592     }
03593   else
03594     sprintf (own_buf, "F-1");
03595 }
03596 
03597 static void
03598 cmd_qtstatus (char *packet)
03599 {
03600   char *stop_reason_rsp = NULL;
03601   char *buf1, *buf2, *buf3, *str;
03602   int slen;
03603 
03604   /* Translate the plain text of the notes back into hex for
03605      transmission.  */
03606 
03607   str = (tracing_user_name ? tracing_user_name : "");
03608   slen = strlen (str);
03609   buf1 = (char *) alloca (slen * 2 + 1);
03610   hexify (buf1, str, slen);
03611 
03612   str = (tracing_notes ? tracing_notes : "");
03613   slen = strlen (str);
03614   buf2 = (char *) alloca (slen * 2 + 1);
03615   hexify (buf2, str, slen);
03616 
03617   str = (tracing_stop_note ? tracing_stop_note : "");
03618   slen = strlen (str);
03619   buf3 = (char *) alloca (slen * 2 + 1);
03620   hexify (buf3, str, slen);
03621 
03622   trace_debug ("Returning trace status as %d, stop reason %s",
03623                tracing, tracing_stop_reason);
03624 
03625   if (agent_loaded_p ())
03626     {
03627       pause_all (1);
03628 
03629       upload_fast_traceframes ();
03630 
03631       unpause_all (1);
03632    }
03633 
03634   stop_reason_rsp = (char *) tracing_stop_reason;
03635 
03636   /* The user visible error string in terror needs to be hex encoded.
03637      We leave it as plain string in `tracing_stop_reason' to ease
03638      debugging.  */
03639   if (strncmp (stop_reason_rsp, "terror:", strlen ("terror:")) == 0)
03640     {
03641       const char *result_name;
03642       int hexstr_len;
03643       char *p;
03644 
03645       result_name = stop_reason_rsp + strlen ("terror:");
03646       hexstr_len = strlen (result_name) * 2;
03647       p = stop_reason_rsp = alloca (strlen ("terror:") + hexstr_len + 1);
03648       strcpy (p, "terror:");
03649       p += strlen (p);
03650       convert_int_to_ascii ((gdb_byte *) result_name, p, strlen (result_name));
03651     }
03652 
03653   /* If this was a forced stop, include any stop note that was supplied.  */
03654   if (strcmp (stop_reason_rsp, "tstop") == 0)
03655     {
03656       stop_reason_rsp = alloca (strlen ("tstop:") + strlen (buf3) + 1);
03657       strcpy (stop_reason_rsp, "tstop:");
03658       strcat (stop_reason_rsp, buf3);
03659     }
03660 
03661   sprintf (packet,
03662            "T%d;"
03663            "%s:%x;"
03664            "tframes:%x;tcreated:%x;"
03665            "tfree:%x;tsize:%s;"
03666            "circular:%d;"
03667            "disconn:%d;"
03668            "starttime:%s;stoptime:%s;"
03669            "username:%s;notes:%s:",
03670            tracing ? 1 : 0,
03671            stop_reason_rsp, tracing_stop_tpnum,
03672            traceframe_count, traceframes_created,
03673            free_space (), phex_nz (trace_buffer_hi - trace_buffer_lo, 0),
03674            circular_trace_buffer,
03675            disconnected_tracing,
03676            phex_nz (tracing_start_time, sizeof (tracing_start_time)),
03677            phex_nz (tracing_stop_time, sizeof (tracing_stop_time)),
03678            buf1, buf2);
03679 }
03680 
03681 static void
03682 cmd_qtp (char *own_buf)
03683 {
03684   ULONGEST num, addr;
03685   struct tracepoint *tpoint;
03686   char *packet = own_buf;
03687 
03688   packet += strlen ("qTP:");
03689 
03690   packet = unpack_varlen_hex (packet, &num);
03691   ++packet; /* skip a colon */
03692   packet = unpack_varlen_hex (packet, &addr);
03693 
03694   /* See if we already have this tracepoint.  */
03695   tpoint = find_tracepoint (num, addr);
03696 
03697   if (!tpoint)
03698     {
03699       trace_debug ("Tracepoint error: tracepoint %d at 0x%s not found",
03700                    (int) num, paddress (addr));
03701       write_enn (own_buf);
03702       return;
03703     }
03704 
03705   sprintf (own_buf, "V%" PRIu64 ":%" PRIu64 "", tpoint->hit_count,
03706            tpoint->traceframe_usage);
03707 }
03708 
03709 /* State variables to help return all the tracepoint bits.  */
03710 static struct tracepoint *cur_tpoint;
03711 static unsigned int cur_action;
03712 static unsigned int cur_step_action;
03713 static struct source_string *cur_source_string;
03714 static struct trace_state_variable *cur_tsv;
03715 
03716 /* Compose a response that is an imitation of the syntax by which the
03717    tracepoint was originally downloaded.  */
03718 
03719 static void
03720 response_tracepoint (char *packet, struct tracepoint *tpoint)
03721 {
03722   char *buf;
03723 
03724   sprintf (packet, "T%x:%s:%c:%" PRIx64 ":%" PRIx64, tpoint->number,
03725            paddress (tpoint->address),
03726            (tpoint->enabled ? 'E' : 'D'), tpoint->step_count,
03727            tpoint->pass_count);
03728   if (tpoint->type == fast_tracepoint)
03729     sprintf (packet + strlen (packet), ":F%x", tpoint->orig_size);
03730   else if (tpoint->type == static_tracepoint)
03731     sprintf (packet + strlen (packet), ":S");
03732 
03733   if (tpoint->cond)
03734     {
03735       buf = gdb_unparse_agent_expr (tpoint->cond);
03736       sprintf (packet + strlen (packet), ":X%x,%s",
03737                tpoint->cond->length, buf);
03738       free (buf);
03739     }
03740 }
03741 
03742 /* Compose a response that is an imitation of the syntax by which the
03743    tracepoint action was originally downloaded (with the difference
03744    that due to the way we store the actions, this will output a packet
03745    per action, while GDB could have combined more than one action
03746    per-packet.  */
03747 
03748 static void
03749 response_action (char *packet, struct tracepoint *tpoint,
03750                  char *taction, int step)
03751 {
03752   sprintf (packet, "%c%x:%s:%s",
03753            (step ? 'S' : 'A'), tpoint->number, paddress (tpoint->address),
03754            taction);
03755 }
03756 
03757 /* Compose a response that is an imitation of the syntax by which the
03758    tracepoint source piece was originally downloaded.  */
03759 
03760 static void
03761 response_source (char *packet,
03762                  struct tracepoint *tpoint, struct source_string *src)
03763 {
03764   char *buf;
03765   int len;
03766 
03767   len = strlen (src->str);
03768   buf = alloca (len * 2 + 1);
03769   convert_int_to_ascii ((gdb_byte *) src->str, buf, len);
03770 
03771   sprintf (packet, "Z%x:%s:%s:%x:%x:%s",
03772            tpoint->number, paddress (tpoint->address),
03773            src->type, 0, len, buf);
03774 }
03775 
03776 /* Return the first piece of tracepoint definition, and initialize the
03777    state machine that will iterate through all the tracepoint
03778    bits.  */
03779 
03780 static void
03781 cmd_qtfp (char *packet)
03782 {
03783   trace_debug ("Returning first tracepoint definition piece");
03784 
03785   cur_tpoint = tracepoints;
03786   cur_action = cur_step_action = 0;
03787   cur_source_string = NULL;
03788 
03789   if (cur_tpoint)
03790     response_tracepoint (packet, cur_tpoint);
03791   else
03792     strcpy (packet, "l");
03793 }
03794 
03795 /* Return additional pieces of tracepoint definition.  Each action and
03796    stepping action must go into its own packet, because of packet size
03797    limits, and so we use state variables to deliver one piece at a
03798    time.  */
03799 
03800 static void
03801 cmd_qtsp (char *packet)
03802 {
03803   trace_debug ("Returning subsequent tracepoint definition piece");
03804 
03805   if (!cur_tpoint)
03806     {
03807       /* This case would normally never occur, but be prepared for
03808          GDB misbehavior.  */
03809       strcpy (packet, "l");
03810     }
03811   else if (cur_action < cur_tpoint->numactions)
03812     {
03813       response_action (packet, cur_tpoint,
03814                        cur_tpoint->actions_str[cur_action], 0);
03815       ++cur_action;
03816     }
03817   else if (cur_step_action < cur_tpoint->num_step_actions)
03818     {
03819       response_action (packet, cur_tpoint,
03820                        cur_tpoint->step_actions_str[cur_step_action], 1);
03821       ++cur_step_action;
03822     }
03823   else if ((cur_source_string
03824             ? cur_source_string->next
03825             : cur_tpoint->source_strings))
03826     {
03827       if (cur_source_string)
03828         cur_source_string = cur_source_string->next;
03829       else
03830         cur_source_string = cur_tpoint->source_strings;
03831       response_source (packet, cur_tpoint, cur_source_string);
03832     }
03833   else
03834     {
03835       cur_tpoint = cur_tpoint->next;
03836       cur_action = cur_step_action = 0;
03837       cur_source_string = NULL;
03838       if (cur_tpoint)
03839         response_tracepoint (packet, cur_tpoint);
03840       else
03841         strcpy (packet, "l");
03842     }
03843 }
03844 
03845 /* Compose a response that is an imitation of the syntax by which the
03846    trace state variable was originally downloaded.  */
03847 
03848 static void
03849 response_tsv (char *packet, struct trace_state_variable *tsv)
03850 {
03851   char *buf = (char *) "";
03852   int namelen;
03853 
03854   if (tsv->name)
03855     {
03856       namelen = strlen (tsv->name);
03857       buf = alloca (namelen * 2 + 1);
03858       convert_int_to_ascii ((gdb_byte *) tsv->name, buf, namelen);
03859     }
03860 
03861   sprintf (packet, "%x:%s:%x:%s", tsv->number, phex_nz (tsv->initial_value, 0),
03862            tsv->getter ? 1 : 0, buf);
03863 }
03864 
03865 /* Return the first trace state variable definition, and initialize
03866    the state machine that will iterate through all the tsv bits.  */
03867 
03868 static void
03869 cmd_qtfv (char *packet)
03870 {
03871   trace_debug ("Returning first trace state variable definition");
03872 
03873   cur_tsv = trace_state_variables;
03874 
03875   if (cur_tsv)
03876     response_tsv (packet, cur_tsv);
03877   else
03878     strcpy (packet, "l");
03879 }
03880 
03881 /* Return additional trace state variable definitions. */
03882 
03883 static void
03884 cmd_qtsv (char *packet)
03885 {
03886   trace_debug ("Returning additional trace state variable definition");
03887 
03888   if (cur_tsv)
03889     {
03890       cur_tsv = cur_tsv->next;
03891       if (cur_tsv)
03892         response_tsv (packet, cur_tsv);
03893       else
03894         strcpy (packet, "l");
03895     }
03896   else
03897     strcpy (packet, "l");
03898 }
03899 
03900 /* Return the first static tracepoint marker, and initialize the state
03901    machine that will iterate through all the static tracepoints
03902    markers.  */
03903 
03904 static void
03905 cmd_qtfstm (char *packet)
03906 {
03907   if (!maybe_write_ipa_ust_not_loaded (packet))
03908     run_inferior_command (packet, strlen (packet) + 1);
03909 }
03910 
03911 /* Return additional static tracepoints markers.  */
03912 
03913 static void
03914 cmd_qtsstm (char *packet)
03915 {
03916   if (!maybe_write_ipa_ust_not_loaded (packet))
03917     run_inferior_command (packet, strlen (packet) + 1);
03918 }
03919 
03920 /* Return the definition of the static tracepoint at a given address.
03921    Result packet is the same as qTsST's.  */
03922 
03923 static void
03924 cmd_qtstmat (char *packet)
03925 {
03926   if (!maybe_write_ipa_ust_not_loaded (packet))
03927     run_inferior_command (packet, strlen (packet) + 1);
03928 }
03929 
03930 /* Sent the agent a command to close it.  */
03931 
03932 void
03933 gdb_agent_about_to_close (int pid)
03934 {
03935   char buf[IPA_CMD_BUF_SIZE];
03936 
03937   if (!maybe_write_ipa_not_loaded (buf))
03938     {
03939       struct thread_info *save_inferior;
03940       struct inferior_list_entry *inf = all_threads.head;
03941 
03942       save_inferior = current_inferior;
03943 
03944       /* Find a certain thread which belongs to process PID.  */
03945       while (inf != NULL)
03946         {
03947           if (ptid_get_pid (inf->id) == pid)
03948             break;
03949           inf = inf->next;
03950         }
03951 
03952       current_inferior = (struct thread_info *) inf;
03953 
03954       strcpy (buf, "close");
03955 
03956       run_inferior_command (buf, strlen (buf) + 1);
03957 
03958       current_inferior = save_inferior;
03959     }
03960 }
03961 
03962 /* Return the minimum instruction size needed for fast tracepoints as a
03963    hexadecimal number.  */
03964 
03965 static void
03966 cmd_qtminftpilen (char *packet)
03967 {
03968   if (current_inferior == NULL)
03969     {
03970       /* Indicate that the minimum length is currently unknown.  */
03971       strcpy (packet, "0");
03972       return;
03973     }
03974 
03975   sprintf (packet, "%x", target_get_min_fast_tracepoint_insn_len ());
03976 }
03977 
03978 /* Respond to qTBuffer packet with a block of raw data from the trace
03979    buffer.  GDB may ask for a lot, but we are allowed to reply with
03980    only as much as will fit within packet limits or whatever.  */
03981 
03982 static void
03983 cmd_qtbuffer (char *own_buf)
03984 {
03985   ULONGEST offset, num, tot;
03986   unsigned char *tbp;
03987   char *packet = own_buf;
03988 
03989   packet += strlen ("qTBuffer:");
03990 
03991   packet = unpack_varlen_hex (packet, &offset);
03992   ++packet; /* skip a comma */
03993   unpack_varlen_hex (packet, &num);
03994 
03995   trace_debug ("Want to get trace buffer, %d bytes at offset 0x%s",
03996                (int) num, phex_nz (offset, 0));
03997 
03998   tot = (trace_buffer_hi - trace_buffer_lo) - free_space ();
03999 
04000   /* If we're right at the end, reply specially that we're done.  */
04001   if (offset == tot)
04002     {
04003       strcpy (own_buf, "l");
04004       return;
04005     }
04006 
04007   /* Object to any other out-of-bounds request.  */
04008   if (offset > tot)
04009     {
04010       write_enn (own_buf);
04011       return;
04012     }
04013 
04014   /* Compute the pointer corresponding to the given offset, accounting
04015      for wraparound.  */
04016   tbp = trace_buffer_start + offset;
04017   if (tbp >= trace_buffer_wrap)
04018     tbp -= (trace_buffer_wrap - trace_buffer_lo);
04019 
04020   /* Trim to the remaining bytes if we're close to the end.  */
04021   if (num > tot - offset)
04022     num = tot - offset;
04023 
04024   /* Trim to available packet size.  */
04025   if (num >= (PBUFSIZ - 16) / 2 )
04026     num = (PBUFSIZ - 16) / 2;
04027 
04028   convert_int_to_ascii (tbp, own_buf, num);
04029 }
04030 
04031 static void
04032 cmd_bigqtbuffer_circular (char *own_buf)
04033 {
04034   ULONGEST val;
04035   char *packet = own_buf;
04036 
04037   packet += strlen ("QTBuffer:circular:");
04038 
04039   unpack_varlen_hex (packet, &val);
04040   circular_trace_buffer = val;
04041   trace_debug ("Trace buffer is now %s",
04042                circular_trace_buffer ? "circular" : "linear");
04043   write_ok (own_buf);
04044 }
04045 
04046 static void
04047 cmd_bigqtbuffer_size (char *own_buf)
04048 {
04049   ULONGEST val;
04050   LONGEST sval;
04051   char *packet = own_buf;
04052 
04053   /* Can't change the size during a tracing run.  */
04054   if (tracing)
04055     {
04056       write_enn (own_buf);
04057       return;
04058     }
04059 
04060   packet += strlen ("QTBuffer:size:");
04061 
04062   /* -1 is sent as literal "-1".  */
04063   if (strcmp (packet, "-1") == 0)
04064     sval = DEFAULT_TRACE_BUFFER_SIZE;
04065   else
04066     {
04067       unpack_varlen_hex (packet, &val);
04068       sval = (LONGEST) val;
04069     }
04070 
04071   init_trace_buffer (sval);
04072   trace_debug ("Trace buffer is now %s bytes",
04073                plongest (trace_buffer_size));
04074   write_ok (own_buf);
04075 }
04076 
04077 static void
04078 cmd_qtnotes (char *own_buf)
04079 {
04080   size_t nbytes;
04081   char *saved, *user, *notes, *stopnote;
04082   char *packet = own_buf;
04083 
04084   packet += strlen ("QTNotes:");
04085 
04086   while (*packet)
04087     {
04088       if (strncmp ("user:", packet, strlen ("user:")) == 0)
04089         {
04090           packet += strlen ("user:");
04091           saved = packet;
04092           packet = strchr (packet, ';');
04093           nbytes = (packet - saved) / 2;
04094           user = xmalloc (nbytes + 1);
04095           nbytes = unhexify (user, saved, nbytes);
04096           user[nbytes] = '\0';
04097           ++packet; /* skip the semicolon */
04098           trace_debug ("User is '%s'", user);
04099           xfree (tracing_user_name);
04100           tracing_user_name = user;
04101         }
04102       else if (strncmp ("notes:", packet, strlen ("notes:")) == 0)
04103         {
04104           packet += strlen ("notes:");
04105           saved = packet;
04106           packet = strchr (packet, ';');
04107           nbytes = (packet - saved) / 2;
04108           notes = xmalloc (nbytes + 1);
04109           nbytes = unhexify (notes, saved, nbytes);
04110           notes[nbytes] = '\0';
04111           ++packet; /* skip the semicolon */
04112           trace_debug ("Notes is '%s'", notes);
04113           xfree (tracing_notes);
04114           tracing_notes = notes;
04115         }
04116       else if (strncmp ("tstop:", packet, strlen ("tstop:")) == 0)
04117         {
04118           packet += strlen ("tstop:");
04119           saved = packet;
04120           packet = strchr (packet, ';');
04121           nbytes = (packet - saved) / 2;
04122           stopnote = xmalloc (nbytes + 1);
04123           nbytes = unhexify (stopnote, saved, nbytes);
04124           stopnote[nbytes] = '\0';
04125           ++packet; /* skip the semicolon */
04126           trace_debug ("tstop note is '%s'", stopnote);
04127           xfree (tracing_stop_note);
04128           tracing_stop_note = stopnote;
04129         }
04130       else
04131         break;
04132     }
04133 
04134   write_ok (own_buf);
04135 }
04136 
04137 int
04138 handle_tracepoint_general_set (char *packet)
04139 {
04140   if (strcmp ("QTinit", packet) == 0)
04141     {
04142       cmd_qtinit (packet);
04143       return 1;
04144     }
04145   else if (strncmp ("QTDP:", packet, strlen ("QTDP:")) == 0)
04146     {
04147       cmd_qtdp (packet);
04148       return 1;
04149     }
04150   else if (strncmp ("QTDPsrc:", packet, strlen ("QTDPsrc:")) == 0)
04151     {
04152       cmd_qtdpsrc (packet);
04153       return 1;
04154     }
04155   else if (strncmp ("QTEnable:", packet, strlen ("QTEnable:")) == 0)
04156     {
04157       cmd_qtenable_disable (packet, 1);
04158       return 1;
04159     }
04160   else if (strncmp ("QTDisable:", packet, strlen ("QTDisable:")) == 0)
04161     {
04162       cmd_qtenable_disable (packet, 0);
04163       return 1;
04164     }
04165   else if (strncmp ("QTDV:", packet, strlen ("QTDV:")) == 0)
04166     {
04167       cmd_qtdv (packet);
04168       return 1;
04169     }
04170   else if (strncmp ("QTro:", packet, strlen ("QTro:")) == 0)
04171     {
04172       cmd_qtro (packet);
04173       return 1;
04174     }
04175   else if (strcmp ("QTStart", packet) == 0)
04176     {
04177       cmd_qtstart (packet);
04178       return 1;
04179     }
04180   else if (strcmp ("QTStop", packet) == 0)
04181     {
04182       cmd_qtstop (packet);
04183       return 1;
04184     }
04185   else if (strncmp ("QTDisconnected:", packet,
04186                     strlen ("QTDisconnected:")) == 0)
04187     {
04188       cmd_qtdisconnected (packet);
04189       return 1;
04190     }
04191   else if (strncmp ("QTFrame:", packet, strlen ("QTFrame:")) == 0)
04192     {
04193       cmd_qtframe (packet);
04194       return 1;
04195     }
04196   else if (strncmp ("QTBuffer:circular:", packet, strlen ("QTBuffer:circular:")) == 0)
04197     {
04198       cmd_bigqtbuffer_circular (packet);
04199       return 1;
04200     }
04201   else if (strncmp ("QTBuffer:size:", packet, strlen ("QTBuffer:size:")) == 0)
04202     {
04203       cmd_bigqtbuffer_size (packet);
04204       return 1;
04205     }
04206   else if (strncmp ("QTNotes:", packet, strlen ("QTNotes:")) == 0)
04207     {
04208       cmd_qtnotes (packet);
04209       return 1;
04210     }
04211 
04212   return 0;
04213 }
04214 
04215 int
04216 handle_tracepoint_query (char *packet)
04217 {
04218   if (strcmp ("qTStatus", packet) == 0)
04219     {
04220       cmd_qtstatus (packet);
04221       return 1;
04222     }
04223   else if (strncmp ("qTP:", packet, strlen ("qTP:")) == 0)
04224     {
04225       cmd_qtp (packet);
04226       return 1;
04227     }
04228   else if (strcmp ("qTfP", packet) == 0)
04229     {
04230       cmd_qtfp (packet);
04231       return 1;
04232     }
04233   else if (strcmp ("qTsP", packet) == 0)
04234     {
04235       cmd_qtsp (packet);
04236       return 1;
04237     }
04238   else if (strcmp ("qTfV", packet) == 0)
04239     {
04240       cmd_qtfv (packet);
04241       return 1;
04242     }
04243   else if (strcmp ("qTsV", packet) == 0)
04244     {
04245       cmd_qtsv (packet);
04246       return 1;
04247     }
04248   else if (strncmp ("qTV:", packet, strlen ("qTV:")) == 0)
04249     {
04250       cmd_qtv (packet);
04251       return 1;
04252     }
04253   else if (strncmp ("qTBuffer:", packet, strlen ("qTBuffer:")) == 0)
04254     {
04255       cmd_qtbuffer (packet);
04256       return 1;
04257     }
04258   else if (strcmp ("qTfSTM", packet) == 0)
04259     {
04260       cmd_qtfstm (packet);
04261       return 1;
04262     }
04263   else if (strcmp ("qTsSTM", packet) == 0)
04264     {
04265       cmd_qtsstm (packet);
04266       return 1;
04267     }
04268   else if (strncmp ("qTSTMat:", packet, strlen ("qTSTMat:")) == 0)
04269     {
04270       cmd_qtstmat (packet);
04271       return 1;
04272     }
04273   else if (strcmp ("qTMinFTPILen", packet) == 0)
04274     {
04275       cmd_qtminftpilen (packet);
04276       return 1;
04277     }
04278 
04279   return 0;
04280 }
04281 
04282 #endif
04283 #ifndef IN_PROCESS_AGENT
04284 
04285 /* Call this when thread TINFO has hit the tracepoint defined by
04286    TP_NUMBER and TP_ADDRESS, and that tracepoint has a while-stepping
04287    action.  This adds a while-stepping collecting state item to the
04288    threads' collecting state list, so that we can keep track of
04289    multiple simultaneous while-stepping actions being collected by the
04290    same thread.  This can happen in cases like:
04291 
04292     ff0001  INSN1 <-- TP1, while-stepping 10 collect $regs
04293     ff0002  INSN2
04294     ff0003  INSN3 <-- TP2, collect $regs
04295     ff0004  INSN4 <-- TP3, while-stepping 10 collect $regs
04296     ff0005  INSN5
04297 
04298    Notice that when instruction INSN5 is reached, the while-stepping
04299    actions of both TP1 and TP3 are still being collected, and that TP2
04300    had been collected meanwhile.  The whole range of ff0001-ff0005
04301    should be single-stepped, due to at least TP1's while-stepping
04302    action covering the whole range.  */
04303 
04304 static void
04305 add_while_stepping_state (struct thread_info *tinfo,
04306                           int tp_number, CORE_ADDR tp_address)
04307 {
04308   struct wstep_state *wstep;
04309 
04310   wstep = xmalloc (sizeof (*wstep));
04311   wstep->next = tinfo->while_stepping;
04312 
04313   wstep->tp_number = tp_number;
04314   wstep->tp_address = tp_address;
04315   wstep->current_step = 0;
04316 
04317   tinfo->while_stepping = wstep;
04318 }
04319 
04320 /* Release the while-stepping collecting state WSTEP.  */
04321 
04322 static void
04323 release_while_stepping_state (struct wstep_state *wstep)
04324 {
04325   free (wstep);
04326 }
04327 
04328 /* Release all while-stepping collecting states currently associated
04329    with thread TINFO.  */
04330 
04331 void
04332 release_while_stepping_state_list (struct thread_info *tinfo)
04333 {
04334   struct wstep_state *head;
04335 
04336   while (tinfo->while_stepping)
04337     {
04338       head = tinfo->while_stepping;
04339       tinfo->while_stepping = head->next;
04340       release_while_stepping_state (head);
04341     }
04342 }
04343 
04344 /* If TINFO was handling a 'while-stepping' action, the step has
04345    finished, so collect any step data needed, and check if any more
04346    steps are required.  Return true if the thread was indeed
04347    collecting tracepoint data, false otherwise.  */
04348 
04349 int
04350 tracepoint_finished_step (struct thread_info *tinfo, CORE_ADDR stop_pc)
04351 {
04352   struct tracepoint *tpoint;
04353   struct wstep_state *wstep;
04354   struct wstep_state **wstep_link;
04355   struct trap_tracepoint_ctx ctx;
04356 
04357   /* Pull in fast tracepoint trace frames from the inferior lib buffer into
04358      our buffer.  */
04359   if (agent_loaded_p ())
04360     upload_fast_traceframes ();
04361 
04362   /* Check if we were indeed collecting data for one of more
04363      tracepoints with a 'while-stepping' count.  */
04364   if (tinfo->while_stepping == NULL)
04365     return 0;
04366 
04367   if (!tracing)
04368     {
04369       /* We're not even tracing anymore.  Stop this thread from
04370          collecting.  */
04371       release_while_stepping_state_list (tinfo);
04372 
04373       /* The thread had stopped due to a single-step request indeed
04374          explained by a tracepoint.  */
04375       return 1;
04376     }
04377 
04378   wstep = tinfo->while_stepping;
04379   wstep_link = &tinfo->while_stepping;
04380 
04381   trace_debug ("Thread %s finished a single-step for tracepoint %d at 0x%s",
04382                target_pid_to_str (tinfo->entry.id),
04383                wstep->tp_number, paddress (wstep->tp_address));
04384 
04385   ctx.base.type = trap_tracepoint;
04386   ctx.regcache = get_thread_regcache (tinfo, 1);
04387 
04388   while (wstep != NULL)
04389     {
04390       tpoint = find_tracepoint (wstep->tp_number, wstep->tp_address);
04391       if (tpoint == NULL)
04392         {
04393           trace_debug ("NO TRACEPOINT %d at 0x%s FOR THREAD %s!",
04394                        wstep->tp_number, paddress (wstep->tp_address),
04395                        target_pid_to_str (tinfo->entry.id));
04396 
04397           /* Unlink.  */
04398           *wstep_link = wstep->next;
04399           release_while_stepping_state (wstep);
04400           wstep = *wstep_link;
04401           continue;
04402         }
04403 
04404       /* We've just finished one step.  */
04405       ++wstep->current_step;
04406 
04407       /* Collect data.  */
04408       collect_data_at_step ((struct tracepoint_hit_ctx *) &ctx,
04409                             stop_pc, tpoint, wstep->current_step);
04410 
04411       if (wstep->current_step >= tpoint->step_count)
04412         {
04413           /* The requested numbers of steps have occurred.  */
04414           trace_debug ("Thread %s done stepping for tracepoint %d at 0x%s",
04415                        target_pid_to_str (tinfo->entry.id),
04416                        wstep->tp_number, paddress (wstep->tp_address));
04417 
04418           /* Unlink the wstep.  */
04419           *wstep_link = wstep->next;
04420           release_while_stepping_state (wstep);
04421           wstep = *wstep_link;
04422 
04423           /* Only check the hit count now, which ensure that we do all
04424              our stepping before stopping the run.  */
04425           if (tpoint->pass_count > 0
04426               && tpoint->hit_count >= tpoint->pass_count
04427               && stopping_tracepoint == NULL)
04428             stopping_tracepoint = tpoint;
04429         }
04430       else
04431         {
04432           /* Keep single-stepping until the requested numbers of steps
04433              have occurred.  */
04434           wstep_link = &wstep->next;
04435           wstep = *wstep_link;
04436         }
04437 
04438       if (stopping_tracepoint
04439           || trace_buffer_is_full
04440           || expr_eval_result != expr_eval_no_error)
04441         {
04442           stop_tracing ();
04443           break;
04444         }
04445     }
04446 
04447   return 1;
04448 }
04449 
04450 /* Handle any internal tracing control breakpoint hits.  That means,
04451    pull traceframes from the IPA to our buffer, and syncing both
04452    tracing agents when the IPA's tracing stops for some reason.  */
04453 
04454 int
04455 handle_tracepoint_bkpts (struct thread_info *tinfo, CORE_ADDR stop_pc)
04456 {
04457   /* Pull in fast tracepoint trace frames from the inferior in-process
04458      agent's buffer into our buffer.  */
04459 
04460   if (!agent_loaded_p ())
04461     return 0;
04462 
04463   upload_fast_traceframes ();
04464 
04465   /* Check if the in-process agent had decided we should stop
04466      tracing.  */
04467   if (stop_pc == ipa_sym_addrs.addr_stop_tracing)
04468     {
04469       int ipa_trace_buffer_is_full;
04470       CORE_ADDR ipa_stopping_tracepoint;
04471       int ipa_expr_eval_result;
04472       CORE_ADDR ipa_error_tracepoint;
04473 
04474       trace_debug ("lib stopped at stop_tracing");
04475 
04476       read_inferior_integer (ipa_sym_addrs.addr_trace_buffer_is_full,
04477                              &ipa_trace_buffer_is_full);
04478 
04479       read_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint,
04480                                   &ipa_stopping_tracepoint);
04481       write_inferior_data_pointer (ipa_sym_addrs.addr_stopping_tracepoint, 0);
04482 
04483       read_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint,
04484                                   &ipa_error_tracepoint);
04485       write_inferior_data_pointer (ipa_sym_addrs.addr_error_tracepoint, 0);
04486 
04487       read_inferior_integer (ipa_sym_addrs.addr_expr_eval_result,
04488                              &ipa_expr_eval_result);
04489       write_inferior_integer (ipa_sym_addrs.addr_expr_eval_result, 0);
04490 
04491       trace_debug ("lib: trace_buffer_is_full: %d, "
04492                    "stopping_tracepoint: %s, "
04493                    "ipa_expr_eval_result: %d, "
04494                    "error_tracepoint: %s, ",
04495                    ipa_trace_buffer_is_full,
04496                    paddress (ipa_stopping_tracepoint),
04497                    ipa_expr_eval_result,
04498                    paddress (ipa_error_tracepoint));
04499 
04500       if (debug_threads)
04501         {
04502           if (ipa_trace_buffer_is_full)
04503             trace_debug ("lib stopped due to full buffer.");
04504           if (ipa_stopping_tracepoint)
04505             trace_debug ("lib stopped due to tpoint");
04506           if (ipa_stopping_tracepoint)
04507             trace_debug ("lib stopped due to error");
04508         }
04509 
04510       if (ipa_stopping_tracepoint != 0)
04511         {
04512           stopping_tracepoint
04513             = fast_tracepoint_from_ipa_tpoint_address (ipa_stopping_tracepoint);
04514         }
04515       else if (ipa_expr_eval_result != expr_eval_no_error)
04516         {
04517           expr_eval_result = ipa_expr_eval_result;
04518           error_tracepoint
04519             = fast_tracepoint_from_ipa_tpoint_address (ipa_error_tracepoint);
04520         }
04521       stop_tracing ();
04522       return 1;
04523     }
04524   else if (stop_pc == ipa_sym_addrs.addr_flush_trace_buffer)
04525     {
04526       trace_debug ("lib stopped at flush_trace_buffer");
04527       return 1;
04528     }
04529 
04530   return 0;
04531 }
04532 
04533 /* Return true if TINFO just hit a tracepoint.  Collect data if
04534    so.  */
04535 
04536 int
04537 tracepoint_was_hit (struct thread_info *tinfo, CORE_ADDR stop_pc)
04538 {
04539   struct tracepoint *tpoint;
04540   int ret = 0;
04541   struct trap_tracepoint_ctx ctx;
04542 
04543   /* Not tracing, don't handle.  */
04544   if (!tracing)
04545     return 0;
04546 
04547   ctx.base.type = trap_tracepoint;
04548   ctx.regcache = get_thread_regcache (tinfo, 1);
04549 
04550   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
04551     {
04552       /* Note that we collect fast tracepoints here as well.  We'll
04553          step over the fast tracepoint jump later, which avoids the
04554          double collect.  However, we don't collect for static
04555          tracepoints here, because UST markers are compiled in program,
04556          and probes will be executed in program.  So static tracepoints
04557          are collected there.   */
04558       if (tpoint->enabled && stop_pc == tpoint->address
04559           && tpoint->type != static_tracepoint)
04560         {
04561           trace_debug ("Thread %s at address of tracepoint %d at 0x%s",
04562                        target_pid_to_str (tinfo->entry.id),
04563                        tpoint->number, paddress (tpoint->address));
04564 
04565           /* Test the condition if present, and collect if true.  */
04566           if (!tpoint->cond
04567               || (condition_true_at_tracepoint
04568                   ((struct tracepoint_hit_ctx *) &ctx, tpoint)))
04569             collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
04570                                         stop_pc, tpoint);
04571 
04572           if (stopping_tracepoint
04573               || trace_buffer_is_full
04574               || expr_eval_result != expr_eval_no_error)
04575             {
04576               stop_tracing ();
04577             }
04578           /* If the tracepoint had a 'while-stepping' action, then set
04579              the thread to collect this tracepoint on the following
04580              single-steps.  */
04581           else if (tpoint->step_count > 0)
04582             {
04583               add_while_stepping_state (tinfo,
04584                                         tpoint->number, tpoint->address);
04585             }
04586 
04587           ret = 1;
04588         }
04589     }
04590 
04591   return ret;
04592 }
04593 
04594 #endif
04595 
04596 #if defined IN_PROCESS_AGENT && defined HAVE_UST
04597 struct ust_marker_data;
04598 static void collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
04599                                             struct traceframe *tframe);
04600 #endif
04601 
04602 /* Create a trace frame for the hit of the given tracepoint in the
04603    given thread.  */
04604 
04605 static void
04606 collect_data_at_tracepoint (struct tracepoint_hit_ctx *ctx, CORE_ADDR stop_pc,
04607                             struct tracepoint *tpoint)
04608 {
04609   struct traceframe *tframe;
04610   int acti;
04611 
04612   /* Only count it as a hit when we actually collect data.  */
04613   tpoint->hit_count++;
04614 
04615   /* If we've exceeded a defined pass count, record the event for
04616      later, and finish the collection for this hit.  This test is only
04617      for nonstepping tracepoints, stepping tracepoints test at the end
04618      of their while-stepping loop.  */
04619   if (tpoint->pass_count > 0
04620       && tpoint->hit_count >= tpoint->pass_count
04621       && tpoint->step_count == 0
04622       && stopping_tracepoint == NULL)
04623     stopping_tracepoint = tpoint;
04624 
04625   trace_debug ("Making new traceframe for tracepoint %d at 0x%s, hit %" PRIu64,
04626                tpoint->number, paddress (tpoint->address), tpoint->hit_count);
04627 
04628   tframe = add_traceframe (tpoint);
04629 
04630   if (tframe)
04631     {
04632       for (acti = 0; acti < tpoint->numactions; ++acti)
04633         {
04634 #ifndef IN_PROCESS_AGENT
04635           trace_debug ("Tracepoint %d at 0x%s about to do action '%s'",
04636                        tpoint->number, paddress (tpoint->address),
04637                        tpoint->actions_str[acti]);
04638 #endif
04639 
04640           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
04641                                    tpoint->actions[acti]);
04642         }
04643 
04644       finish_traceframe (tframe);
04645     }
04646 
04647   if (tframe == NULL && tracing)
04648     trace_buffer_is_full = 1;
04649 }
04650 
04651 #ifndef IN_PROCESS_AGENT
04652 
04653 static void
04654 collect_data_at_step (struct tracepoint_hit_ctx *ctx,
04655                       CORE_ADDR stop_pc,
04656                       struct tracepoint *tpoint, int current_step)
04657 {
04658   struct traceframe *tframe;
04659   int acti;
04660 
04661   trace_debug ("Making new step traceframe for "
04662                "tracepoint %d at 0x%s, step %d of %" PRIu64 ", hit %" PRIu64,
04663                tpoint->number, paddress (tpoint->address),
04664                current_step, tpoint->step_count,
04665                tpoint->hit_count);
04666 
04667   tframe = add_traceframe (tpoint);
04668 
04669   if (tframe)
04670     {
04671       for (acti = 0; acti < tpoint->num_step_actions; ++acti)
04672         {
04673           trace_debug ("Tracepoint %d at 0x%s about to do step action '%s'",
04674                        tpoint->number, paddress (tpoint->address),
04675                        tpoint->step_actions_str[acti]);
04676 
04677           do_action_at_tracepoint (ctx, stop_pc, tpoint, tframe,
04678                                    tpoint->step_actions[acti]);
04679         }
04680 
04681       finish_traceframe (tframe);
04682     }
04683 
04684   if (tframe == NULL && tracing)
04685     trace_buffer_is_full = 1;
04686 }
04687 
04688 #endif
04689 
04690 #ifdef IN_PROCESS_AGENT
04691 /* The target description used by the IPA.  Given that the IPA library
04692    is built for a specific architecture that is loaded into the
04693    inferior, there only needs to be one such description per
04694    build.  */
04695 const struct target_desc *ipa_tdesc;
04696 #endif
04697 
04698 static struct regcache *
04699 get_context_regcache (struct tracepoint_hit_ctx *ctx)
04700 {
04701   struct regcache *regcache = NULL;
04702 
04703 #ifdef IN_PROCESS_AGENT
04704   if (ctx->type == fast_tracepoint)
04705     {
04706       struct fast_tracepoint_ctx *fctx = (struct fast_tracepoint_ctx *) ctx;
04707       if (!fctx->regcache_initted)
04708         {
04709           fctx->regcache_initted = 1;
04710           init_register_cache (&fctx->regcache, ipa_tdesc, fctx->regspace);
04711           supply_regblock (&fctx->regcache, NULL);
04712           supply_fast_tracepoint_registers (&fctx->regcache, fctx->regs);
04713         }
04714       regcache = &fctx->regcache;
04715     }
04716 #ifdef HAVE_UST
04717   if (ctx->type == static_tracepoint)
04718     {
04719       struct static_tracepoint_ctx *sctx
04720         = (struct static_tracepoint_ctx *) ctx;
04721 
04722       if (!sctx->regcache_initted)
04723         {
04724           sctx->regcache_initted = 1;
04725           init_register_cache (&sctx->regcache, ipa_tdesc, sctx->regspace);
04726           supply_regblock (&sctx->regcache, NULL);
04727           /* Pass down the tracepoint address, because REGS doesn't
04728              include the PC, but we know what it must have been.  */
04729           supply_static_tracepoint_registers (&sctx->regcache,
04730                                               (const unsigned char *)
04731                                               sctx->regs,
04732                                               sctx->tpoint->address);
04733         }
04734       regcache = &sctx->regcache;
04735     }
04736 #endif
04737 #else
04738   if (ctx->type == trap_tracepoint)
04739     {
04740       struct trap_tracepoint_ctx *tctx = (struct trap_tracepoint_ctx *) ctx;
04741       regcache = tctx->regcache;
04742     }
04743 #endif
04744 
04745   gdb_assert (regcache != NULL);
04746 
04747   return regcache;
04748 }
04749 
04750 static void
04751 do_action_at_tracepoint (struct tracepoint_hit_ctx *ctx,
04752                          CORE_ADDR stop_pc,
04753                          struct tracepoint *tpoint,
04754                          struct traceframe *tframe,
04755                          struct tracepoint_action *taction)
04756 {
04757   enum eval_result_type err;
04758 
04759   switch (taction->type)
04760     {
04761     case 'M':
04762       {
04763         struct collect_memory_action *maction;
04764         struct eval_agent_expr_context ax_ctx;
04765 
04766         maction = (struct collect_memory_action *) taction;
04767         ax_ctx.regcache = NULL;
04768         ax_ctx.tframe = tframe;
04769         ax_ctx.tpoint = tpoint;
04770 
04771         trace_debug ("Want to collect %s bytes at 0x%s (basereg %d)",
04772                      pulongest (maction->len),
04773                      paddress (maction->addr), maction->basereg);
04774         /* (should use basereg) */
04775         agent_mem_read (&ax_ctx, NULL, (CORE_ADDR) maction->addr,
04776                         maction->len);
04777         break;
04778       }
04779     case 'R':
04780       {
04781         unsigned char *regspace;
04782         struct regcache tregcache;
04783         struct regcache *context_regcache;
04784         int regcache_size;
04785 
04786         trace_debug ("Want to collect registers");
04787 
04788         context_regcache = get_context_regcache (ctx);
04789         regcache_size = register_cache_size (context_regcache->tdesc);
04790 
04791         /* Collect all registers for now.  */
04792         regspace = add_traceframe_block (tframe, tpoint, 1 + regcache_size);
04793         if (regspace == NULL)
04794           {
04795             trace_debug ("Trace buffer block allocation failed, skipping");
04796             break;
04797           }
04798         /* Identify a register block.  */
04799         *regspace = 'R';
04800 
04801         /* Wrap the regblock in a register cache (in the stack, we
04802            don't want to malloc here).  */
04803         init_register_cache (&tregcache, context_regcache->tdesc,
04804                              regspace + 1);
04805 
04806         /* Copy the register data to the regblock.  */
04807         regcache_cpy (&tregcache, context_regcache);
04808 
04809 #ifndef IN_PROCESS_AGENT
04810         /* On some platforms, trap-based tracepoints will have the PC
04811            pointing to the next instruction after the trap, but we
04812            don't want the user or GDB trying to guess whether the
04813            saved PC needs adjusting; so always record the adjusted
04814            stop_pc.  Note that we can't use tpoint->address instead,
04815            since it will be wrong for while-stepping actions.  This
04816            adjustment is a nop for fast tracepoints collected from the
04817            in-process lib (but not if GDBserver is collecting one
04818            preemptively), since the PC had already been adjusted to
04819            contain the tracepoint's address by the jump pad.  */
04820         trace_debug ("Storing stop pc (0x%s) in regblock",
04821                      paddress (stop_pc));
04822 
04823         /* This changes the regblock, not the thread's
04824            regcache.  */
04825         regcache_write_pc (&tregcache, stop_pc);
04826 #endif
04827       }
04828       break;
04829     case 'X':
04830       {
04831         struct eval_expr_action *eaction;
04832         struct eval_agent_expr_context ax_ctx;
04833 
04834         eaction = (struct eval_expr_action *) taction;
04835         ax_ctx.regcache = get_context_regcache (ctx);
04836         ax_ctx.tframe = tframe;
04837         ax_ctx.tpoint = tpoint;
04838 
04839         trace_debug ("Want to evaluate expression");
04840 
04841         err = gdb_eval_agent_expr (&ax_ctx, eaction->expr, NULL);
04842 
04843         if (err != expr_eval_no_error)
04844           {
04845             record_tracepoint_error (tpoint, "action expression", err);
04846             return;
04847           }
04848       }
04849       break;
04850     case 'L':
04851       {
04852 #if defined IN_PROCESS_AGENT && defined HAVE_UST
04853         trace_debug ("Want to collect static trace data");
04854         collect_ust_data_at_tracepoint (ctx, tframe);
04855 #else
04856         trace_debug ("warning: collecting static trace data, "
04857                      "but static tracepoints are not supported");
04858 #endif
04859       }
04860       break;
04861     default:
04862       trace_debug ("unknown trace action '%c', ignoring", taction->type);
04863       break;
04864     }
04865 }
04866 
04867 static int
04868 condition_true_at_tracepoint (struct tracepoint_hit_ctx *ctx,
04869                               struct tracepoint *tpoint)
04870 {
04871   ULONGEST value = 0;
04872   enum eval_result_type err;
04873 
04874   /* Presently, gdbserver doesn't run compiled conditions, only the
04875      IPA does.  If the program stops at a fast tracepoint's address
04876      (e.g., due to a breakpoint, trap tracepoint, or stepping),
04877      gdbserver preemptively collect the fast tracepoint.  Later, on
04878      resume, gdbserver steps over the fast tracepoint like it steps
04879      over breakpoints, so that the IPA doesn't see that fast
04880      tracepoint.  This avoids double collects of fast tracepoints in
04881      that stopping scenario.  Having gdbserver itself handle the fast
04882      tracepoint gives the user a consistent view of when fast or trap
04883      tracepoints are collected, compared to an alternative where only
04884      trap tracepoints are collected on stop, and fast tracepoints on
04885      resume.  When a fast tracepoint is being processed by gdbserver,
04886      it is always the non-compiled condition expression that is
04887      used.  */
04888 #ifdef IN_PROCESS_AGENT
04889   if (tpoint->compiled_cond)
04890     err = ((condfn) (uintptr_t) (tpoint->compiled_cond)) (ctx, &value);
04891   else
04892 #endif
04893     {
04894       struct eval_agent_expr_context ax_ctx;
04895 
04896       ax_ctx.regcache = get_context_regcache (ctx);
04897       ax_ctx.tframe = NULL;
04898       ax_ctx.tpoint = tpoint;
04899 
04900       err = gdb_eval_agent_expr (&ax_ctx, tpoint->cond, &value);
04901     }
04902   if (err != expr_eval_no_error)
04903     {
04904       record_tracepoint_error (tpoint, "condition", err);
04905       /* The error case must return false.  */
04906       return 0;
04907     }
04908 
04909   trace_debug ("Tracepoint %d at 0x%s condition evals to %s",
04910                tpoint->number, paddress (tpoint->address),
04911                pulongest (value));
04912   return (value ? 1 : 0);
04913 }
04914 
04915 /* Do memory copies for bytecodes.  */
04916 /* Do the recording of memory blocks for actions and bytecodes.  */
04917 
04918 int
04919 agent_mem_read (struct eval_agent_expr_context *ctx,
04920                 unsigned char *to, CORE_ADDR from, ULONGEST len)
04921 {
04922   unsigned char *mspace;
04923   ULONGEST remaining = len;
04924   unsigned short blocklen;
04925 
04926   /* If a 'to' buffer is specified, use it.  */
04927   if (to != NULL)
04928     {
04929       read_inferior_memory (from, to, len);
04930       return 0;
04931     }
04932 
04933   /* Otherwise, create a new memory block in the trace buffer.  */
04934   while (remaining > 0)
04935     {
04936       size_t sp;
04937 
04938       blocklen = (remaining > 65535 ? 65535 : remaining);
04939       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
04940       mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
04941       if (mspace == NULL)
04942         return 1;
04943       /* Identify block as a memory block.  */
04944       *mspace = 'M';
04945       ++mspace;
04946       /* Record address and size.  */
04947       memcpy (mspace, &from, sizeof (from));
04948       mspace += sizeof (from);
04949       memcpy (mspace, &blocklen, sizeof (blocklen));
04950       mspace += sizeof (blocklen);
04951       /* Record the memory block proper.  */
04952       read_inferior_memory (from, mspace, blocklen);
04953       trace_debug ("%d bytes recorded", blocklen);
04954       remaining -= blocklen;
04955       from += blocklen;
04956     }
04957   return 0;
04958 }
04959 
04960 int
04961 agent_mem_read_string (struct eval_agent_expr_context *ctx,
04962                        unsigned char *to, CORE_ADDR from, ULONGEST len)
04963 {
04964   unsigned char *buf, *mspace;
04965   ULONGEST remaining = len;
04966   unsigned short blocklen, i;
04967 
04968   /* To save a bit of space, block lengths are 16-bit, so break large
04969      requests into multiple blocks.  Bordering on overkill for strings,
04970      but it could happen that someone specifies a large max length.  */
04971   while (remaining > 0)
04972     {
04973       size_t sp;
04974 
04975       blocklen = (remaining > 65535 ? 65535 : remaining);
04976       /* We want working space to accumulate nonzero bytes, since
04977          traceframes must have a predecided size (otherwise it gets
04978          harder to wrap correctly for the circular case, etc).  */
04979       buf = (unsigned char *) xmalloc (blocklen + 1);
04980       for (i = 0; i < blocklen; ++i)
04981         {
04982           /* Read the string one byte at a time, in case the string is
04983              at the end of a valid memory area - we don't want a
04984              correctly-terminated string to engender segvio
04985              complaints.  */
04986           read_inferior_memory (from + i, buf + i, 1);
04987 
04988           if (buf[i] == '\0')
04989             {
04990               blocklen = i + 1;
04991               /* Make sure outer loop stops now too.  */
04992               remaining = blocklen;
04993               break;
04994             }
04995         }
04996       sp = 1 + sizeof (from) + sizeof (blocklen) + blocklen;
04997       mspace = add_traceframe_block (ctx->tframe, ctx->tpoint, sp);
04998       if (mspace == NULL)
04999         {
05000           xfree (buf);
05001           return 1;
05002         }
05003       /* Identify block as a memory block.  */
05004       *mspace = 'M';
05005       ++mspace;
05006       /* Record address and size.  */
05007       memcpy ((void *) mspace, (void *) &from, sizeof (from));
05008       mspace += sizeof (from);
05009       memcpy ((void *) mspace, (void *) &blocklen, sizeof (blocklen));
05010       mspace += sizeof (blocklen);
05011       /* Copy the string contents.  */
05012       memcpy ((void *) mspace, (void *) buf, blocklen);
05013       remaining -= blocklen;
05014       from += blocklen;
05015       xfree (buf);
05016     }
05017   return 0;
05018 }
05019 
05020 /* Record the value of a trace state variable.  */
05021 
05022 int
05023 agent_tsv_read (struct eval_agent_expr_context *ctx, int n)
05024 {
05025   unsigned char *vspace;
05026   LONGEST val;
05027 
05028   vspace = add_traceframe_block (ctx->tframe, ctx->tpoint,
05029                                  1 + sizeof (n) + sizeof (LONGEST));
05030   if (vspace == NULL)
05031     return 1;
05032   /* Identify block as a variable.  */
05033   *vspace = 'V';
05034   /* Record variable's number and value.  */
05035   memcpy (vspace + 1, &n, sizeof (n));
05036   val = get_trace_state_variable_value (n);
05037   memcpy (vspace + 1 + sizeof (n), &val, sizeof (val));
05038   trace_debug ("Variable %d recorded", n);
05039   return 0;
05040 }
05041 
05042 #ifndef IN_PROCESS_AGENT
05043 
05044 /* Callback for traceframe_walk_blocks, used to find a given block
05045    type in a traceframe.  */
05046 
05047 static int
05048 match_blocktype (char blocktype, unsigned char *dataptr, void *data)
05049 {
05050   char *wantedp = data;
05051 
05052   if (*wantedp == blocktype)
05053     return 1;
05054 
05055   return 0;
05056 }
05057 
05058 /* Walk over all traceframe blocks of the traceframe buffer starting
05059    at DATABASE, of DATASIZE bytes long, and call CALLBACK for each
05060    block found, passing in DATA unmodified.  If CALLBACK returns true,
05061    this returns a pointer to where the block is found.  Returns NULL
05062    if no callback call returned true, indicating that all blocks have
05063    been walked.  */
05064 
05065 static unsigned char *
05066 traceframe_walk_blocks (unsigned char *database, unsigned int datasize,
05067                         int tfnum,
05068                         int (*callback) (char blocktype,
05069                                          unsigned char *dataptr,
05070                                          void *data),
05071                         void *data)
05072 {
05073   unsigned char *dataptr;
05074 
05075   if (datasize == 0)
05076     {
05077       trace_debug ("traceframe %d has no data", tfnum);
05078       return NULL;
05079     }
05080 
05081   /* Iterate through a traceframe's blocks, looking for a block of the
05082      requested type.  */
05083   for (dataptr = database;
05084        dataptr < database + datasize;
05085        /* nothing */)
05086     {
05087       char blocktype;
05088       unsigned short mlen;
05089 
05090       if (dataptr == trace_buffer_wrap)
05091         {
05092           /* Adjust to reflect wrapping part of the frame around to
05093              the beginning.  */
05094           datasize = dataptr - database;
05095           dataptr = database = trace_buffer_lo;
05096         }
05097 
05098       blocktype = *dataptr++;
05099 
05100       if ((*callback) (blocktype, dataptr, data))
05101         return dataptr;
05102 
05103       switch (blocktype)
05104         {
05105         case 'R':
05106           /* Skip over the registers block.  */
05107           dataptr += current_target_desc ()->registers_size;
05108           break;
05109         case 'M':
05110           /* Skip over the memory block.  */
05111           dataptr += sizeof (CORE_ADDR);
05112           memcpy (&mlen, dataptr, sizeof (mlen));
05113           dataptr += (sizeof (mlen) + mlen);
05114           break;
05115         case 'V':
05116           /* Skip over the TSV block.  */
05117           dataptr += (sizeof (int) + sizeof (LONGEST));
05118           break;
05119         case 'S':
05120           /* Skip over the static trace data block.  */
05121           memcpy (&mlen, dataptr, sizeof (mlen));
05122           dataptr += (sizeof (mlen) + mlen);
05123           break;
05124         default:
05125           trace_debug ("traceframe %d has unknown block type 0x%x",
05126                        tfnum, blocktype);
05127           return NULL;
05128         }
05129     }
05130 
05131   return NULL;
05132 }
05133 
05134 /* Look for the block of type TYPE_WANTED in the trameframe starting
05135    at DATABASE of DATASIZE bytes long.  TFNUM is the traceframe
05136    number.  */
05137 
05138 static unsigned char *
05139 traceframe_find_block_type (unsigned char *database, unsigned int datasize,
05140                             int tfnum, char type_wanted)
05141 {
05142   return traceframe_walk_blocks (database, datasize, tfnum,
05143                                  match_blocktype, &type_wanted);
05144 }
05145 
05146 static unsigned char *
05147 traceframe_find_regblock (struct traceframe *tframe, int tfnum)
05148 {
05149   unsigned char *regblock;
05150 
05151   regblock = traceframe_find_block_type (tframe->data,
05152                                          tframe->data_size,
05153                                          tfnum, 'R');
05154 
05155   if (regblock == NULL)
05156     trace_debug ("traceframe %d has no register data", tfnum);
05157 
05158   return regblock;
05159 }
05160 
05161 /* Get registers from a traceframe.  */
05162 
05163 int
05164 fetch_traceframe_registers (int tfnum, struct regcache *regcache, int regnum)
05165 {
05166   unsigned char *dataptr;
05167   struct tracepoint *tpoint;
05168   struct traceframe *tframe;
05169 
05170   tframe = find_traceframe (tfnum);
05171 
05172   if (tframe == NULL)
05173     {
05174       trace_debug ("traceframe %d not found", tfnum);
05175       return 1;
05176     }
05177 
05178   dataptr = traceframe_find_regblock (tframe, tfnum);
05179   if (dataptr == NULL)
05180     {
05181       /* Mark registers unavailable.  */
05182       supply_regblock (regcache, NULL);
05183 
05184       /* We can generally guess at a PC, although this will be
05185          misleading for while-stepping frames and multi-location
05186          tracepoints.  */
05187       tpoint = find_next_tracepoint_by_number (NULL, tframe->tpnum);
05188       if (tpoint != NULL)
05189         regcache_write_pc (regcache, tpoint->address);
05190     }
05191   else
05192     supply_regblock (regcache, dataptr);
05193 
05194   return 0;
05195 }
05196 
05197 static CORE_ADDR
05198 traceframe_get_pc (struct traceframe *tframe)
05199 {
05200   struct regcache regcache;
05201   unsigned char *dataptr;
05202   const struct target_desc *tdesc = current_target_desc ();
05203 
05204   dataptr = traceframe_find_regblock (tframe, -1);
05205   if (dataptr == NULL)
05206     return 0;
05207 
05208   init_register_cache (&regcache, tdesc, dataptr);
05209   return regcache_read_pc (&regcache);
05210 }
05211 
05212 /* Read a requested block of memory from a trace frame.  */
05213 
05214 int
05215 traceframe_read_mem (int tfnum, CORE_ADDR addr,
05216                      unsigned char *buf, ULONGEST length,
05217                      ULONGEST *nbytes)
05218 {
05219   struct traceframe *tframe;
05220   unsigned char *database, *dataptr;
05221   unsigned int datasize;
05222   CORE_ADDR maddr;
05223   unsigned short mlen;
05224 
05225   trace_debug ("traceframe_read_mem");
05226 
05227   tframe = find_traceframe (tfnum);
05228 
05229   if (!tframe)
05230     {
05231       trace_debug ("traceframe %d not found", tfnum);
05232       return 1;
05233     }
05234 
05235   datasize = tframe->data_size;
05236   database = dataptr = &tframe->data[0];
05237 
05238   /* Iterate through a traceframe's blocks, looking for memory.  */
05239   while ((dataptr = traceframe_find_block_type (dataptr,
05240                                                 datasize
05241                                                 - (dataptr - database),
05242                                                 tfnum, 'M')) != NULL)
05243     {
05244       memcpy (&maddr, dataptr, sizeof (maddr));
05245       dataptr += sizeof (maddr);
05246       memcpy (&mlen, dataptr, sizeof (mlen));
05247       dataptr += sizeof (mlen);
05248       trace_debug ("traceframe %d has %d bytes at %s",
05249                    tfnum, mlen, paddress (maddr));
05250 
05251       /* If the block includes the first part of the desired range,
05252          return as much it has; GDB will re-request the remainder,
05253          which might be in a different block of this trace frame.  */
05254       if (maddr <= addr && addr < (maddr + mlen))
05255         {
05256           ULONGEST amt = (maddr + mlen) - addr;
05257           if (amt > length)
05258             amt = length;
05259 
05260           memcpy (buf, dataptr + (addr - maddr), amt);
05261           *nbytes = amt;
05262           return 0;
05263         }
05264 
05265       /* Skip over this block.  */
05266       dataptr += mlen;
05267     }
05268 
05269   trace_debug ("traceframe %d has no memory data for the desired region",
05270                tfnum);
05271 
05272   *nbytes = 0;
05273   return 0;
05274 }
05275 
05276 static int
05277 traceframe_read_tsv (int tsvnum, LONGEST *val)
05278 {
05279   int tfnum;
05280   struct traceframe *tframe;
05281   unsigned char *database, *dataptr;
05282   unsigned int datasize;
05283   int vnum;
05284   int found = 0;
05285 
05286   trace_debug ("traceframe_read_tsv");
05287 
05288   tfnum = current_traceframe;
05289 
05290   if (tfnum < 0)
05291     {
05292       trace_debug ("no current traceframe");
05293       return 1;
05294     }
05295 
05296   tframe = find_traceframe (tfnum);
05297 
05298   if (tframe == NULL)
05299     {
05300       trace_debug ("traceframe %d not found", tfnum);
05301       return 1;
05302     }
05303 
05304   datasize = tframe->data_size;
05305   database = dataptr = &tframe->data[0];
05306 
05307   /* Iterate through a traceframe's blocks, looking for the last
05308      matched tsv.  */
05309   while ((dataptr = traceframe_find_block_type (dataptr,
05310                                                 datasize
05311                                                 - (dataptr - database),
05312                                                 tfnum, 'V')) != NULL)
05313     {
05314       memcpy (&vnum, dataptr, sizeof (vnum));
05315       dataptr += sizeof (vnum);
05316 
05317       trace_debug ("traceframe %d has variable %d", tfnum, vnum);
05318 
05319       /* Check that this is the variable we want.  */
05320       if (tsvnum == vnum)
05321         {
05322           memcpy (val, dataptr, sizeof (*val));
05323           found = 1;
05324         }
05325 
05326       /* Skip over this block.  */
05327       dataptr += sizeof (LONGEST);
05328     }
05329 
05330   if (!found)
05331     trace_debug ("traceframe %d has no data for variable %d",
05332                  tfnum, tsvnum);
05333   return !found;
05334 }
05335 
05336 /* Read a requested block of static tracepoint data from a trace
05337    frame.  */
05338 
05339 int
05340 traceframe_read_sdata (int tfnum, ULONGEST offset,
05341                        unsigned char *buf, ULONGEST length,
05342                        ULONGEST *nbytes)
05343 {
05344   struct traceframe *tframe;
05345   unsigned char *database, *dataptr;
05346   unsigned int datasize;
05347   unsigned short mlen;
05348 
05349   trace_debug ("traceframe_read_sdata");
05350 
05351   tframe = find_traceframe (tfnum);
05352 
05353   if (!tframe)
05354     {
05355       trace_debug ("traceframe %d not found", tfnum);
05356       return 1;
05357     }
05358 
05359   datasize = tframe->data_size;
05360   database = &tframe->data[0];
05361 
05362   /* Iterate through a traceframe's blocks, looking for static
05363      tracepoint data.  */
05364   dataptr = traceframe_find_block_type (database, datasize,
05365                                         tfnum, 'S');
05366   if (dataptr != NULL)
05367     {
05368       memcpy (&mlen, dataptr, sizeof (mlen));
05369       dataptr += sizeof (mlen);
05370       if (offset < mlen)
05371         {
05372           if (offset + length > mlen)
05373             length = mlen - offset;
05374 
05375           memcpy (buf, dataptr, length);
05376           *nbytes = length;
05377         }
05378       else
05379         *nbytes = 0;
05380       return 0;
05381     }
05382 
05383   trace_debug ("traceframe %d has no static trace data", tfnum);
05384 
05385   *nbytes = 0;
05386   return 0;
05387 }
05388 
05389 /* Callback for traceframe_walk_blocks.  Builds a traceframe-info
05390    object.  DATA is pointer to a struct buffer holding the
05391    traceframe-info object being built.  */
05392 
05393 static int
05394 build_traceframe_info_xml (char blocktype, unsigned char *dataptr, void *data)
05395 {
05396   struct buffer *buffer = data;
05397 
05398   switch (blocktype)
05399     {
05400     case 'M':
05401       {
05402         unsigned short mlen;
05403         CORE_ADDR maddr;
05404 
05405         memcpy (&maddr, dataptr, sizeof (maddr));
05406         dataptr += sizeof (maddr);
05407         memcpy (&mlen, dataptr, sizeof (mlen));
05408         dataptr += sizeof (mlen);
05409         buffer_xml_printf (buffer,
05410                            "<memory start=\"0x%s\" length=\"0x%s\"/>\n",
05411                            paddress (maddr), phex_nz (mlen, sizeof (mlen)));
05412         break;
05413       }
05414     case 'V':
05415       {
05416         int vnum;
05417 
05418         memcpy (&vnum, dataptr, sizeof (vnum));
05419         buffer_xml_printf (buffer, "<tvar id=\"%d\"/>\n", vnum);
05420         break;
05421       }
05422     case 'R':
05423     case 'S':
05424       {
05425         break;
05426       }
05427     default:
05428       warning ("Unhandled trace block type (%d) '%c ' "
05429                "while building trace frame info.",
05430                blocktype, blocktype);
05431       break;
05432     }
05433 
05434   return 0;
05435 }
05436 
05437 /* Build a traceframe-info object for traceframe number TFNUM into
05438    BUFFER.  */
05439 
05440 int
05441 traceframe_read_info (int tfnum, struct buffer *buffer)
05442 {
05443   struct traceframe *tframe;
05444 
05445   trace_debug ("traceframe_read_info");
05446 
05447   tframe = find_traceframe (tfnum);
05448 
05449   if (!tframe)
05450     {
05451       trace_debug ("traceframe %d not found", tfnum);
05452       return 1;
05453     }
05454 
05455   buffer_grow_str (buffer, "<traceframe-info>\n");
05456   traceframe_walk_blocks (tframe->data, tframe->data_size,
05457                           tfnum, build_traceframe_info_xml, buffer);
05458   buffer_grow_str0 (buffer, "</traceframe-info>\n");
05459   return 0;
05460 }
05461 
05462 /* Return the first fast tracepoint whose jump pad contains PC.  */
05463 
05464 static struct tracepoint *
05465 fast_tracepoint_from_jump_pad_address (CORE_ADDR pc)
05466 {
05467   struct tracepoint *tpoint;
05468 
05469   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
05470     if (tpoint->type == fast_tracepoint)
05471       if (tpoint->jump_pad <= pc && pc < tpoint->jump_pad_end)
05472         return tpoint;
05473 
05474   return NULL;
05475 }
05476 
05477 /* Return the first fast tracepoint whose trampoline contains PC.  */
05478 
05479 static struct tracepoint *
05480 fast_tracepoint_from_trampoline_address (CORE_ADDR pc)
05481 {
05482   struct tracepoint *tpoint;
05483 
05484   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
05485     {
05486       if (tpoint->type == fast_tracepoint
05487           && tpoint->trampoline <= pc && pc < tpoint->trampoline_end)
05488         return tpoint;
05489     }
05490 
05491   return NULL;
05492 }
05493 
05494 /* Return GDBserver's tracepoint that matches the IP Agent's
05495    tracepoint object that lives at IPA_TPOINT_OBJ in the IP Agent's
05496    address space.  */
05497 
05498 static struct tracepoint *
05499 fast_tracepoint_from_ipa_tpoint_address (CORE_ADDR ipa_tpoint_obj)
05500 {
05501   struct tracepoint *tpoint;
05502 
05503   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
05504     if (tpoint->type == fast_tracepoint)
05505       if (tpoint->obj_addr_on_target == ipa_tpoint_obj)
05506         return tpoint;
05507 
05508   return NULL;
05509 }
05510 
05511 #endif
05512 
05513 /* The type of the object that is used to synchronize fast tracepoint
05514    collection.  */
05515 
05516 typedef struct collecting_t
05517 {
05518   /* The fast tracepoint number currently collecting.  */
05519   uintptr_t tpoint;
05520 
05521   /* A number that GDBserver can use to identify the thread that is
05522      presently holding the collect lock.  This need not (and usually
05523      is not) the thread id, as getting the current thread ID usually
05524      requires a system call, which we want to avoid like the plague.
05525      Usually this is thread's TCB, found in the TLS (pseudo-)
05526      register, which is readable with a single insn on several
05527      architectures.  */
05528   uintptr_t thread_area;
05529 } collecting_t;
05530 
05531 #ifndef IN_PROCESS_AGENT
05532 
05533 void
05534 force_unlock_trace_buffer (void)
05535 {
05536   write_inferior_data_pointer (ipa_sym_addrs.addr_collecting, 0);
05537 }
05538 
05539 /* Check if the thread identified by THREAD_AREA which is stopped at
05540    STOP_PC, is presently locking the fast tracepoint collection, and
05541    if so, gather some status of said collection.  Returns 0 if the
05542    thread isn't collecting or in the jump pad at all.  1, if in the
05543    jump pad (or within gdb_collect) and hasn't executed the adjusted
05544    original insn yet (can set a breakpoint there and run to it).  2,
05545    if presently executing the adjusted original insn --- in which
05546    case, if we want to move the thread out of the jump pad, we need to
05547    single-step it until this function returns 0.  */
05548 
05549 int
05550 fast_tracepoint_collecting (CORE_ADDR thread_area,
05551                             CORE_ADDR stop_pc,
05552                             struct fast_tpoint_collect_status *status)
05553 {
05554   CORE_ADDR ipa_collecting;
05555   CORE_ADDR ipa_gdb_jump_pad_buffer, ipa_gdb_jump_pad_buffer_end;
05556   CORE_ADDR ipa_gdb_trampoline_buffer;
05557   CORE_ADDR ipa_gdb_trampoline_buffer_end;
05558   struct tracepoint *tpoint;
05559   int needs_breakpoint;
05560 
05561   /* The thread THREAD_AREA is either:
05562 
05563       0. not collecting at all, not within the jump pad, or within
05564          gdb_collect or one of its callees.
05565 
05566       1. in the jump pad and haven't reached gdb_collect
05567 
05568       2. within gdb_collect (out of the jump pad) (collect is set)
05569 
05570       3. we're in the jump pad, after gdb_collect having returned,
05571          possibly executing the adjusted insns.
05572 
05573       For cases 1 and 3, `collecting' may or not be set.  The jump pad
05574       doesn't have any complicated jump logic, so we can tell if the
05575       thread is executing the adjust original insn or not by just
05576       matching STOP_PC with known jump pad addresses.  If we it isn't
05577       yet executing the original insn, set a breakpoint there, and let
05578       the thread run to it, so to quickly step over a possible (many
05579       insns) gdb_collect call.  Otherwise, or when the breakpoint is
05580       hit, only a few (small number of) insns are left to be executed
05581       in the jump pad.  Single-step the thread until it leaves the
05582       jump pad.  */
05583 
05584  again:
05585   tpoint = NULL;
05586   needs_breakpoint = 0;
05587   trace_debug ("fast_tracepoint_collecting");
05588 
05589   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer,
05590                                   &ipa_gdb_jump_pad_buffer))
05591     fatal ("error extracting `gdb_jump_pad_buffer'");
05592   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_jump_pad_buffer_end,
05593                                   &ipa_gdb_jump_pad_buffer_end))
05594     fatal ("error extracting `gdb_jump_pad_buffer_end'");
05595 
05596   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer,
05597                                   &ipa_gdb_trampoline_buffer))
05598     fatal ("error extracting `gdb_trampoline_buffer'");
05599   if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_trampoline_buffer_end,
05600                                   &ipa_gdb_trampoline_buffer_end))
05601     fatal ("error extracting `gdb_trampoline_buffer_end'");
05602 
05603   if (ipa_gdb_jump_pad_buffer <= stop_pc
05604       && stop_pc < ipa_gdb_jump_pad_buffer_end)
05605     {
05606       /* We can tell which tracepoint(s) the thread is collecting by
05607          matching the jump pad address back to the tracepoint.  */
05608       tpoint = fast_tracepoint_from_jump_pad_address (stop_pc);
05609       if (tpoint == NULL)
05610         {
05611           warning ("in jump pad, but no matching tpoint?");
05612           return 0;
05613         }
05614       else
05615         {
05616           trace_debug ("in jump pad of tpoint (%d, %s); jump_pad(%s, %s); "
05617                        "adj_insn(%s, %s)",
05618                        tpoint->number, paddress (tpoint->address),
05619                        paddress (tpoint->jump_pad),
05620                        paddress (tpoint->jump_pad_end),
05621                        paddress (tpoint->adjusted_insn_addr),
05622                        paddress (tpoint->adjusted_insn_addr_end));
05623         }
05624 
05625       /* Definitely in the jump pad.  May or may not need
05626          fast-exit-jump-pad breakpoint.  */
05627       if (tpoint->jump_pad <= stop_pc
05628           && stop_pc < tpoint->adjusted_insn_addr)
05629         needs_breakpoint =  1;
05630     }
05631   else if (ipa_gdb_trampoline_buffer <= stop_pc
05632            && stop_pc < ipa_gdb_trampoline_buffer_end)
05633     {
05634       /* We can tell which tracepoint(s) the thread is collecting by
05635          matching the trampoline address back to the tracepoint.  */
05636       tpoint = fast_tracepoint_from_trampoline_address (stop_pc);
05637       if (tpoint == NULL)
05638         {
05639           warning ("in trampoline, but no matching tpoint?");
05640           return 0;
05641         }
05642       else
05643         {
05644           trace_debug ("in trampoline of tpoint (%d, %s); trampoline(%s, %s)",
05645                        tpoint->number, paddress (tpoint->address),
05646                        paddress (tpoint->trampoline),
05647                        paddress (tpoint->trampoline_end));
05648         }
05649 
05650       /* Have not reached jump pad yet, but treat the trampoline as a
05651          part of the jump pad that is before the adjusted original
05652          instruction.  */
05653       needs_breakpoint = 1;
05654     }
05655   else
05656     {
05657       collecting_t ipa_collecting_obj;
05658 
05659       /* If `collecting' is set/locked, then the THREAD_AREA thread
05660          may or not be the one holding the lock.  We have to read the
05661          lock to find out.  */
05662 
05663       if (read_inferior_data_pointer (ipa_sym_addrs.addr_collecting,
05664                                       &ipa_collecting))
05665         {
05666           trace_debug ("fast_tracepoint_collecting:"
05667                        " failed reading 'collecting' in the inferior");
05668           return 0;
05669         }
05670 
05671       if (!ipa_collecting)
05672         {
05673           trace_debug ("fast_tracepoint_collecting: not collecting"
05674                        " (and nobody is).");
05675           return 0;
05676         }
05677 
05678       /* Some thread is collecting.  Check which.  */
05679       if (read_inferior_memory (ipa_collecting,
05680                                 (unsigned char *) &ipa_collecting_obj,
05681                                 sizeof (ipa_collecting_obj)) != 0)
05682         goto again;
05683 
05684       if (ipa_collecting_obj.thread_area != thread_area)
05685         {
05686           trace_debug ("fast_tracepoint_collecting: not collecting "
05687                        "(another thread is)");
05688           return 0;
05689         }
05690 
05691       tpoint
05692         = fast_tracepoint_from_ipa_tpoint_address (ipa_collecting_obj.tpoint);
05693       if (tpoint == NULL)
05694         {
05695           warning ("fast_tracepoint_collecting: collecting, "
05696                    "but tpoint %s not found?",
05697                    paddress ((CORE_ADDR) ipa_collecting_obj.tpoint));
05698           return 0;
05699         }
05700 
05701       /* The thread is within `gdb_collect', skip over the rest of
05702          fast tracepoint collection quickly using a breakpoint.  */
05703       needs_breakpoint = 1;
05704     }
05705 
05706   /* The caller wants a bit of status detail.  */
05707   if (status != NULL)
05708     {
05709       status->tpoint_num = tpoint->number;
05710       status->tpoint_addr = tpoint->address;
05711       status->adjusted_insn_addr = tpoint->adjusted_insn_addr;
05712       status->adjusted_insn_addr_end = tpoint->adjusted_insn_addr_end;
05713     }
05714 
05715   if (needs_breakpoint)
05716     {
05717       /* Hasn't executed the original instruction yet.  Set breakpoint
05718          there, and wait till it's hit, then single-step until exiting
05719          the jump pad.  */
05720 
05721       trace_debug ("\
05722 fast_tracepoint_collecting, returning continue-until-break at %s",
05723                    paddress (tpoint->adjusted_insn_addr));
05724 
05725       return 1; /* continue */
05726     }
05727   else
05728     {
05729       /* Just single-step until exiting the jump pad.  */
05730 
05731       trace_debug ("fast_tracepoint_collecting, returning "
05732                    "need-single-step (%s-%s)",
05733                    paddress (tpoint->adjusted_insn_addr),
05734                    paddress (tpoint->adjusted_insn_addr_end));
05735 
05736       return 2; /* single-step */
05737     }
05738 }
05739 
05740 #endif
05741 
05742 #ifdef IN_PROCESS_AGENT
05743 
05744 /* The global fast tracepoint collect lock.  Points to a collecting_t
05745    object built on the stack by the jump pad, if presently locked;
05746    NULL if it isn't locked.  Note that this lock *must* be set while
05747    executing any *function other than the jump pad.  See
05748    fast_tracepoint_collecting.  */
05749 static collecting_t * ATTR_USED collecting;
05750 
05751 /* This routine, called from the jump pad (in asm) is designed to be
05752    called from the jump pads of fast tracepoints, thus it is on the
05753    critical path.  */
05754 
05755 IP_AGENT_EXPORT void ATTR_USED
05756 gdb_collect (struct tracepoint *tpoint, unsigned char *regs)
05757 {
05758   struct fast_tracepoint_ctx ctx;
05759 
05760   /* Don't do anything until the trace run is completely set up.  */
05761   if (!tracing)
05762     return;
05763 
05764   ctx.base.type = fast_tracepoint;
05765   ctx.regs = regs;
05766   ctx.regcache_initted = 0;
05767   /* Wrap the regblock in a register cache (in the stack, we don't
05768      want to malloc here).  */
05769   ctx.regspace = alloca (ipa_tdesc->registers_size);
05770   if (ctx.regspace == NULL)
05771     {
05772       trace_debug ("Trace buffer block allocation failed, skipping");
05773       return;
05774     }
05775 
05776   for (ctx.tpoint = tpoint;
05777        ctx.tpoint != NULL && ctx.tpoint->address == tpoint->address;
05778        ctx.tpoint = ctx.tpoint->next)
05779     {
05780       if (!ctx.tpoint->enabled)
05781         continue;
05782 
05783       /* Multiple tracepoints of different types, such as fast tracepoint and
05784          static tracepoint, can be set at the same address.  */
05785       if (ctx.tpoint->type != tpoint->type)
05786         continue;
05787 
05788       /* Test the condition if present, and collect if true.  */
05789       if (ctx.tpoint->cond == NULL
05790           || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
05791                                            ctx.tpoint))
05792         {
05793           collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
05794                                       ctx.tpoint->address, ctx.tpoint);
05795 
05796           /* Note that this will cause original insns to be written back
05797              to where we jumped from, but that's OK because we're jumping
05798              back to the next whole instruction.  This will go badly if
05799              instruction restoration is not atomic though.  */
05800           if (stopping_tracepoint
05801               || trace_buffer_is_full
05802               || expr_eval_result != expr_eval_no_error)
05803             {
05804               stop_tracing ();
05805               break;
05806             }
05807         }
05808       else
05809         {
05810           /* If there was a condition and it evaluated to false, the only
05811              way we would stop tracing is if there was an error during
05812              condition expression evaluation.  */
05813           if (expr_eval_result != expr_eval_no_error)
05814             {
05815               stop_tracing ();
05816               break;
05817             }
05818         }
05819     }
05820 }
05821 
05822 #endif
05823 
05824 #ifndef IN_PROCESS_AGENT
05825 
05826 CORE_ADDR
05827 get_raw_reg_func_addr (void)
05828 {
05829   return ipa_sym_addrs.addr_get_raw_reg;
05830 }
05831 
05832 CORE_ADDR
05833 get_get_tsv_func_addr (void)
05834 {
05835   return ipa_sym_addrs.addr_get_trace_state_variable_value;
05836 }
05837 
05838 CORE_ADDR
05839 get_set_tsv_func_addr (void)
05840 {
05841   return ipa_sym_addrs.addr_set_trace_state_variable_value;
05842 }
05843 
05844 static void
05845 compile_tracepoint_condition (struct tracepoint *tpoint,
05846                               CORE_ADDR *jump_entry)
05847 {
05848   CORE_ADDR entry_point = *jump_entry;
05849   enum eval_result_type err;
05850 
05851   trace_debug ("Starting condition compilation for tracepoint %d\n",
05852                tpoint->number);
05853 
05854   /* Initialize the global pointer to the code being built.  */
05855   current_insn_ptr = *jump_entry;
05856 
05857   emit_prologue ();
05858 
05859   err = compile_bytecodes (tpoint->cond);
05860 
05861   if (err == expr_eval_no_error)
05862     {
05863       emit_epilogue ();
05864 
05865       /* Record the beginning of the compiled code.  */
05866       tpoint->compiled_cond = entry_point;
05867 
05868       trace_debug ("Condition compilation for tracepoint %d complete\n",
05869                    tpoint->number);
05870     }
05871   else
05872     {
05873       /* Leave the unfinished code in situ, but don't point to it.  */
05874 
05875       tpoint->compiled_cond = 0;
05876 
05877       trace_debug ("Condition compilation for tracepoint %d failed, "
05878                    "error code %d",
05879                    tpoint->number, err);
05880     }
05881 
05882   /* Update the code pointer passed in.  Note that we do this even if
05883      the compile fails, so that we can look at the partial results
05884      instead of letting them be overwritten.  */
05885   *jump_entry = current_insn_ptr;
05886 
05887   /* Leave a gap, to aid dump decipherment.  */
05888   *jump_entry += 16;
05889 }
05890 
05891 /* We'll need to adjust these when we consider bi-arch setups, and big
05892    endian machines.  */
05893 
05894 static int
05895 write_inferior_data_ptr (CORE_ADDR where, CORE_ADDR ptr)
05896 {
05897   return write_inferior_memory (where,
05898                                 (unsigned char *) &ptr, sizeof (void *));
05899 }
05900 
05901 /* The base pointer of the IPA's heap.  This is the only memory the
05902    IPA is allowed to use.  The IPA should _not_ call the inferior's
05903    `malloc' during operation.  That'd be slow, and, most importantly,
05904    it may not be safe.  We may be collecting a tracepoint in a signal
05905    handler, for example.  */
05906 static CORE_ADDR target_tp_heap;
05907 
05908 /* Allocate at least SIZE bytes of memory from the IPA heap, aligned
05909    to 8 bytes.  */
05910 
05911 static CORE_ADDR
05912 target_malloc (ULONGEST size)
05913 {
05914   CORE_ADDR ptr;
05915 
05916   if (target_tp_heap == 0)
05917     {
05918       /* We have the pointer *address*, need what it points to.  */
05919       if (read_inferior_data_pointer (ipa_sym_addrs.addr_gdb_tp_heap_buffer,
05920                                       &target_tp_heap))
05921         fatal ("could get target heap head pointer");
05922     }
05923 
05924   ptr = target_tp_heap;
05925   target_tp_heap += size;
05926 
05927   /* Pad to 8-byte alignment.  */
05928   target_tp_heap = ((target_tp_heap + 7) & ~0x7);
05929 
05930   return ptr;
05931 }
05932 
05933 static CORE_ADDR
05934 download_agent_expr (struct agent_expr *expr)
05935 {
05936   CORE_ADDR expr_addr;
05937   CORE_ADDR expr_bytes;
05938 
05939   expr_addr = target_malloc (sizeof (*expr));
05940   write_inferior_memory (expr_addr, (unsigned char *) expr, sizeof (*expr));
05941 
05942   expr_bytes = target_malloc (expr->length);
05943   write_inferior_data_ptr (expr_addr + offsetof (struct agent_expr, bytes),
05944                            expr_bytes);
05945   write_inferior_memory (expr_bytes, expr->bytes, expr->length);
05946 
05947   return expr_addr;
05948 }
05949 
05950 /* Align V up to N bits.  */
05951 #define UALIGN(V, N) (((V) + ((N) - 1)) & ~((N) - 1))
05952 
05953 /* Sync tracepoint with IPA, but leave maintenance of linked list to caller.  */
05954 
05955 static void
05956 download_tracepoint_1 (struct tracepoint *tpoint)
05957 {
05958   struct tracepoint target_tracepoint;
05959   CORE_ADDR tpptr = 0;
05960 
05961   gdb_assert (tpoint->type == fast_tracepoint
05962               || tpoint->type == static_tracepoint);
05963 
05964   if (tpoint->cond != NULL && target_emit_ops () != NULL)
05965     {
05966       CORE_ADDR jentry, jump_entry;
05967 
05968       jentry = jump_entry = get_jump_space_head ();
05969 
05970       if (tpoint->cond != NULL)
05971         {
05972           /* Pad to 8-byte alignment. (needed?)  */
05973           /* Actually this should be left for the target to
05974              decide.  */
05975           jentry = UALIGN (jentry, 8);
05976 
05977           compile_tracepoint_condition (tpoint, &jentry);
05978         }
05979 
05980       /* Pad to 8-byte alignment.  */
05981       jentry = UALIGN (jentry, 8);
05982       claim_jump_space (jentry - jump_entry);
05983     }
05984 
05985   target_tracepoint = *tpoint;
05986 
05987   tpptr = target_malloc (sizeof (*tpoint));
05988   tpoint->obj_addr_on_target = tpptr;
05989 
05990   /* Write the whole object.  We'll fix up its pointers in a bit.
05991      Assume no next for now.  This is fixed up above on the next
05992      iteration, if there's any.  */
05993   target_tracepoint.next = NULL;
05994   /* Need to clear this here too, since we're downloading the
05995      tracepoints before clearing our own copy.  */
05996   target_tracepoint.hit_count = 0;
05997 
05998   write_inferior_memory (tpptr, (unsigned char *) &target_tracepoint,
05999                          sizeof (target_tracepoint));
06000 
06001   if (tpoint->cond)
06002     write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
06003                                                cond),
06004                              download_agent_expr (tpoint->cond));
06005 
06006   if (tpoint->numactions)
06007     {
06008       int i;
06009       CORE_ADDR actions_array;
06010 
06011       /* The pointers array.  */
06012       actions_array
06013         = target_malloc (sizeof (*tpoint->actions) * tpoint->numactions);
06014       write_inferior_data_ptr (tpptr + offsetof (struct tracepoint,
06015                                                  actions),
06016                                actions_array);
06017 
06018       /* Now for each pointer, download the action.  */
06019       for (i = 0; i < tpoint->numactions; i++)
06020         {
06021           struct tracepoint_action *action = tpoint->actions[i];
06022           CORE_ADDR ipa_action = action->ops->download (action);
06023 
06024           if (ipa_action != 0)
06025             write_inferior_data_ptr
06026               (actions_array + i * sizeof (sizeof (*tpoint->actions)),
06027                ipa_action);
06028         }
06029     }
06030 }
06031 
06032 #define IPA_PROTO_FAST_TRACE_FLAG 0
06033 #define IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET 2
06034 #define IPA_PROTO_FAST_TRACE_JUMP_PAD 10
06035 #define IPA_PROTO_FAST_TRACE_FJUMP_SIZE 18
06036 #define IPA_PROTO_FAST_TRACE_FJUMP_INSN 22
06037 
06038 /* Send a command to agent to download and install tracepoint TPOINT.  */
06039 
06040 static int
06041 tracepoint_send_agent (struct tracepoint *tpoint)
06042 {
06043   char buf[IPA_CMD_BUF_SIZE];
06044   char *p;
06045   int i, ret;
06046 
06047   p = buf;
06048   strcpy (p, "FastTrace:");
06049   p += 10;
06050 
06051   COPY_FIELD_TO_BUF (p, tpoint, number);
06052   COPY_FIELD_TO_BUF (p, tpoint, address);
06053   COPY_FIELD_TO_BUF (p, tpoint, type);
06054   COPY_FIELD_TO_BUF (p, tpoint, enabled);
06055   COPY_FIELD_TO_BUF (p, tpoint, step_count);
06056   COPY_FIELD_TO_BUF (p, tpoint, pass_count);
06057   COPY_FIELD_TO_BUF (p, tpoint, numactions);
06058   COPY_FIELD_TO_BUF (p, tpoint, hit_count);
06059   COPY_FIELD_TO_BUF (p, tpoint, traceframe_usage);
06060   COPY_FIELD_TO_BUF (p, tpoint, compiled_cond);
06061   COPY_FIELD_TO_BUF (p, tpoint, orig_size);
06062 
06063   /* condition */
06064   p = agent_expr_send (p, tpoint->cond);
06065 
06066   /* tracepoint_action */
06067   for (i = 0; i < tpoint->numactions; i++)
06068     {
06069       struct tracepoint_action *action = tpoint->actions[i];
06070 
06071       p[0] = action->type;
06072       p = action->ops->send (&p[1], action);
06073     }
06074 
06075   get_jump_space_head ();
06076   /* Copy the value of GDB_JUMP_PAD_HEAD to command buffer, so that
06077      agent can use jump pad from it.  */
06078   if (tpoint->type == fast_tracepoint)
06079     {
06080       memcpy (p, &gdb_jump_pad_head, 8);
06081       p += 8;
06082     }
06083 
06084   ret = run_inferior_command (buf, (int) (ptrdiff_t) (p - buf));
06085   if (ret)
06086     return ret;
06087 
06088   if (strncmp (buf, "OK", 2) != 0)
06089     return 1;
06090 
06091   /* The value of tracepoint's target address is stored in BUF.  */
06092   memcpy (&tpoint->obj_addr_on_target,
06093           &buf[IPA_PROTO_FAST_TRACE_ADDR_ON_TARGET], 8);
06094 
06095   if (tpoint->type == fast_tracepoint)
06096     {
06097       unsigned char *insn
06098         = (unsigned char *) &buf[IPA_PROTO_FAST_TRACE_FJUMP_INSN];
06099       int fjump_size;
06100 
06101      trace_debug ("agent: read from cmd_buf 0x%x 0x%x\n",
06102                   (unsigned int) tpoint->obj_addr_on_target,
06103                   (unsigned int) gdb_jump_pad_head);
06104 
06105       memcpy (&gdb_jump_pad_head, &buf[IPA_PROTO_FAST_TRACE_JUMP_PAD], 8);
06106 
06107       /* This has been done in agent.  We should also set up record for it.  */
06108       memcpy (&fjump_size, &buf[IPA_PROTO_FAST_TRACE_FJUMP_SIZE], 4);
06109       /* Wire it in.  */
06110       tpoint->handle
06111         = set_fast_tracepoint_jump (tpoint->address, insn, fjump_size);
06112     }
06113 
06114   return 0;
06115 }
06116 
06117 static void
06118 download_tracepoint (struct tracepoint *tpoint)
06119 {
06120   struct tracepoint *tp, *tp_prev;
06121 
06122   if (tpoint->type != fast_tracepoint
06123       && tpoint->type != static_tracepoint)
06124     return;
06125 
06126   download_tracepoint_1 (tpoint);
06127 
06128   /* Find the previous entry of TPOINT, which is fast tracepoint or
06129      static tracepoint.  */
06130   tp_prev = NULL;
06131   for (tp = tracepoints; tp != tpoint; tp = tp->next)
06132     {
06133       if (tp->type == fast_tracepoint || tp->type == static_tracepoint)
06134         tp_prev = tp;
06135     }
06136 
06137   if (tp_prev)
06138     {
06139       CORE_ADDR tp_prev_target_next_addr;
06140 
06141       /* Insert TPOINT after TP_PREV in IPA.  */
06142       if (read_inferior_data_pointer (tp_prev->obj_addr_on_target
06143                                       + offsetof (struct tracepoint, next),
06144                                       &tp_prev_target_next_addr))
06145         fatal ("error reading `tp_prev->next'");
06146 
06147       /* tpoint->next = tp_prev->next */
06148       write_inferior_data_ptr (tpoint->obj_addr_on_target
06149                                + offsetof (struct tracepoint, next),
06150                                tp_prev_target_next_addr);
06151       /* tp_prev->next = tpoint */
06152       write_inferior_data_ptr (tp_prev->obj_addr_on_target
06153                                + offsetof (struct tracepoint, next),
06154                                tpoint->obj_addr_on_target);
06155     }
06156   else
06157     /* First object in list, set the head pointer in the
06158        inferior.  */
06159     write_inferior_data_ptr (ipa_sym_addrs.addr_tracepoints,
06160                              tpoint->obj_addr_on_target);
06161 
06162 }
06163 
06164 static void
06165 download_trace_state_variables (void)
06166 {
06167   CORE_ADDR ptr = 0, prev_ptr = 0;
06168   struct trace_state_variable *tsv;
06169 
06170   /* Start out empty.  */
06171   write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables, 0);
06172 
06173   for (tsv = trace_state_variables; tsv != NULL; tsv = tsv->next)
06174     {
06175       struct trace_state_variable target_tsv;
06176 
06177       /* TSV's with a getter have been initialized equally in both the
06178          inferior and GDBserver.  Skip them.  */
06179       if (tsv->getter != NULL)
06180         continue;
06181 
06182       target_tsv = *tsv;
06183 
06184       prev_ptr = ptr;
06185       ptr = target_malloc (sizeof (*tsv));
06186 
06187       if (tsv == trace_state_variables)
06188         {
06189           /* First object in list, set the head pointer in the
06190              inferior.  */
06191 
06192           write_inferior_data_ptr (ipa_sym_addrs.addr_trace_state_variables,
06193                                    ptr);
06194         }
06195       else
06196         {
06197           write_inferior_data_ptr (prev_ptr
06198                                    + offsetof (struct trace_state_variable,
06199                                                next),
06200                                    ptr);
06201         }
06202 
06203       /* Write the whole object.  We'll fix up its pointers in a bit.
06204          Assume no next, fixup when needed.  */
06205       target_tsv.next = NULL;
06206 
06207       write_inferior_memory (ptr, (unsigned char *) &target_tsv,
06208                              sizeof (target_tsv));
06209 
06210       if (tsv->name != NULL)
06211         {
06212           size_t size = strlen (tsv->name) + 1;
06213           CORE_ADDR name_addr = target_malloc (size);
06214           write_inferior_memory (name_addr,
06215                                  (unsigned char *) tsv->name, size);
06216           write_inferior_data_ptr (ptr
06217                                    + offsetof (struct trace_state_variable,
06218                                                name),
06219                                    name_addr);
06220         }
06221 
06222       if (tsv->getter != NULL)
06223         {
06224           fatal ("what to do with these?");
06225         }
06226     }
06227 
06228   if (prev_ptr != 0)
06229     {
06230       /* Fixup the next pointer in the last item in the list.  */
06231       write_inferior_data_ptr (prev_ptr
06232                                + offsetof (struct trace_state_variable,
06233                                            next), 0);
06234     }
06235 }
06236 
06237 /* Upload complete trace frames out of the IP Agent's trace buffer
06238    into GDBserver's trace buffer.  This always uploads either all or
06239    no trace frames.  This is the counter part of
06240    `trace_alloc_trace_buffer'.  See its description of the atomic
06241    synching mechanism.  */
06242 
06243 static void
06244 upload_fast_traceframes (void)
06245 {
06246   unsigned int ipa_traceframe_read_count, ipa_traceframe_write_count;
06247   unsigned int ipa_traceframe_read_count_racy, ipa_traceframe_write_count_racy;
06248   CORE_ADDR tf;
06249   struct ipa_trace_buffer_control ipa_trace_buffer_ctrl;
06250   unsigned int curr_tbctrl_idx;
06251   unsigned int ipa_trace_buffer_ctrl_curr;
06252   unsigned int ipa_trace_buffer_ctrl_curr_old;
06253   CORE_ADDR ipa_trace_buffer_ctrl_addr;
06254   struct breakpoint *about_to_request_buffer_space_bkpt;
06255   CORE_ADDR ipa_trace_buffer_lo;
06256   CORE_ADDR ipa_trace_buffer_hi;
06257 
06258   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
06259                               &ipa_traceframe_read_count_racy))
06260     {
06261       /* This will happen in most targets if the current thread is
06262          running.  */
06263       return;
06264     }
06265 
06266   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
06267                               &ipa_traceframe_write_count_racy))
06268     return;
06269 
06270   trace_debug ("ipa_traceframe_count (racy area): %d (w=%d, r=%d)",
06271                ipa_traceframe_write_count_racy
06272                - ipa_traceframe_read_count_racy,
06273                ipa_traceframe_write_count_racy,
06274                ipa_traceframe_read_count_racy);
06275 
06276   if (ipa_traceframe_write_count_racy == ipa_traceframe_read_count_racy)
06277     return;
06278 
06279   about_to_request_buffer_space_bkpt
06280     = set_breakpoint_at (ipa_sym_addrs.addr_about_to_request_buffer_space,
06281                          NULL);
06282 
06283   if (read_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
06284                               &ipa_trace_buffer_ctrl_curr))
06285     return;
06286 
06287   ipa_trace_buffer_ctrl_curr_old = ipa_trace_buffer_ctrl_curr;
06288 
06289   curr_tbctrl_idx = ipa_trace_buffer_ctrl_curr & ~GDBSERVER_FLUSH_COUNT_MASK;
06290 
06291   {
06292     unsigned int prev, counter;
06293 
06294     /* Update the token, with new counters, and the GDBserver stamp
06295        bit.  Alway reuse the current TBC index.  */
06296     prev = ipa_trace_buffer_ctrl_curr & GDBSERVER_FLUSH_COUNT_MASK_CURR;
06297     counter = (prev + 0x100) & GDBSERVER_FLUSH_COUNT_MASK_CURR;
06298 
06299     ipa_trace_buffer_ctrl_curr = (GDBSERVER_UPDATED_FLUSH_COUNT_BIT
06300                                   | (prev << 12)
06301                                   | counter
06302                                   | curr_tbctrl_idx);
06303   }
06304 
06305   if (write_inferior_uinteger (ipa_sym_addrs.addr_trace_buffer_ctrl_curr,
06306                                ipa_trace_buffer_ctrl_curr))
06307     return;
06308 
06309   trace_debug ("Lib: Committed %08x -> %08x",
06310                ipa_trace_buffer_ctrl_curr_old,
06311                ipa_trace_buffer_ctrl_curr);
06312 
06313   /* Re-read these, now that we've installed the
06314      `about_to_request_buffer_space' breakpoint/lock.  A thread could
06315      have finished a traceframe between the last read of these
06316      counters and setting the breakpoint above.  If we start
06317      uploading, we never want to leave this function with
06318      traceframe_read_count != 0, otherwise, GDBserver could end up
06319      incrementing the counter tokens more than once (due to event loop
06320      nesting), which would break the IP agent's "effective" detection
06321      (see trace_alloc_trace_buffer).  */
06322   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_read_count,
06323                               &ipa_traceframe_read_count))
06324     return;
06325   if (read_inferior_uinteger (ipa_sym_addrs.addr_traceframe_write_count,
06326                               &ipa_traceframe_write_count))
06327     return;
06328 
06329   if (debug_threads)
06330     {
06331       trace_debug ("ipa_traceframe_count (blocked area): %d (w=%d, r=%d)",
06332                    ipa_traceframe_write_count - ipa_traceframe_read_count,
06333                    ipa_traceframe_write_count, ipa_traceframe_read_count);
06334 
06335       if (ipa_traceframe_write_count != ipa_traceframe_write_count_racy
06336           || ipa_traceframe_read_count != ipa_traceframe_read_count_racy)
06337         trace_debug ("note that ipa_traceframe_count's parts changed");
06338     }
06339 
06340   /* Get the address of the current TBC object (the IP agent has an
06341      array of 3 such objects).  The index is stored in the TBC
06342      token.  */
06343   ipa_trace_buffer_ctrl_addr = ipa_sym_addrs.addr_trace_buffer_ctrl;
06344   ipa_trace_buffer_ctrl_addr
06345     += sizeof (struct ipa_trace_buffer_control) * curr_tbctrl_idx;
06346 
06347   if (read_inferior_memory (ipa_trace_buffer_ctrl_addr,
06348                             (unsigned char *) &ipa_trace_buffer_ctrl,
06349                             sizeof (struct ipa_trace_buffer_control)))
06350     return;
06351 
06352   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_lo,
06353                                   &ipa_trace_buffer_lo))
06354     return;
06355   if (read_inferior_data_pointer (ipa_sym_addrs.addr_trace_buffer_hi,
06356                                   &ipa_trace_buffer_hi))
06357     return;
06358 
06359   /* Offsets are easier to grok for debugging than raw addresses,
06360      especially for the small trace buffer sizes that are useful for
06361      testing.  */
06362   trace_debug ("Lib: Trace buffer [%d] start=%d free=%d "
06363                "endfree=%d wrap=%d hi=%d",
06364                curr_tbctrl_idx,
06365                (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
06366                (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
06367                (int) (ipa_trace_buffer_ctrl.end_free - ipa_trace_buffer_lo),
06368                (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
06369                (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
06370 
06371   /* Note that the IPA's buffer is always circular.  */
06372 
06373 #define IPA_FIRST_TRACEFRAME() (ipa_trace_buffer_ctrl.start)
06374 
06375 #define IPA_NEXT_TRACEFRAME_1(TF, TFOBJ)                \
06376   ((TF) + sizeof (struct traceframe) + (TFOBJ)->data_size)
06377 
06378 #define IPA_NEXT_TRACEFRAME(TF, TFOBJ)                                  \
06379   (IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ)                                    \
06380    - ((IPA_NEXT_TRACEFRAME_1 (TF, TFOBJ) >= ipa_trace_buffer_ctrl.wrap) \
06381       ? (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo)              \
06382       : 0))
06383 
06384   tf = IPA_FIRST_TRACEFRAME ();
06385 
06386   while (ipa_traceframe_write_count - ipa_traceframe_read_count)
06387     {
06388       struct tracepoint *tpoint;
06389       struct traceframe *tframe;
06390       unsigned char *block;
06391       struct traceframe ipa_tframe;
06392 
06393       if (read_inferior_memory (tf, (unsigned char *) &ipa_tframe,
06394                                 offsetof (struct traceframe, data)))
06395         error ("Uploading: couldn't read traceframe at %s\n", paddress (tf));
06396 
06397       if (ipa_tframe.tpnum == 0)
06398         fatal ("Uploading: No (more) fast traceframes, but "
06399                "ipa_traceframe_count == %u??\n",
06400                ipa_traceframe_write_count - ipa_traceframe_read_count);
06401 
06402       /* Note that this will be incorrect for multi-location
06403          tracepoints...  */
06404       tpoint = find_next_tracepoint_by_number (NULL, ipa_tframe.tpnum);
06405 
06406       tframe = add_traceframe (tpoint);
06407       if (tframe == NULL)
06408         {
06409           trace_buffer_is_full = 1;
06410           trace_debug ("Uploading: trace buffer is full");
06411         }
06412       else
06413         {
06414           /* Copy the whole set of blocks in one go for now.  FIXME:
06415              split this in smaller blocks.  */
06416           block = add_traceframe_block (tframe, tpoint,
06417                                         ipa_tframe.data_size);
06418           if (block != NULL)
06419             {
06420               if (read_inferior_memory (tf
06421                                         + offsetof (struct traceframe, data),
06422                                         block, ipa_tframe.data_size))
06423                 error ("Uploading: Couldn't read traceframe data at %s\n",
06424                        paddress (tf + offsetof (struct traceframe, data)));
06425             }
06426 
06427           trace_debug ("Uploading: traceframe didn't fit");
06428           finish_traceframe (tframe);
06429         }
06430 
06431       tf = IPA_NEXT_TRACEFRAME (tf, &ipa_tframe);
06432 
06433       /* If we freed the traceframe that wrapped around, go back
06434          to the non-wrap case.  */
06435       if (tf < ipa_trace_buffer_ctrl.start)
06436         {
06437           trace_debug ("Lib: Discarding past the wraparound");
06438           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
06439         }
06440       ipa_trace_buffer_ctrl.start = tf;
06441       ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_ctrl.start;
06442       ++ipa_traceframe_read_count;
06443 
06444       if (ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.free
06445           && ipa_trace_buffer_ctrl.start == ipa_trace_buffer_ctrl.end_free)
06446         {
06447           trace_debug ("Lib: buffer is fully empty.  "
06448                        "Trace buffer [%d] start=%d free=%d endfree=%d",
06449                        curr_tbctrl_idx,
06450                        (int) (ipa_trace_buffer_ctrl.start
06451                               - ipa_trace_buffer_lo),
06452                        (int) (ipa_trace_buffer_ctrl.free
06453                               - ipa_trace_buffer_lo),
06454                        (int) (ipa_trace_buffer_ctrl.end_free
06455                               - ipa_trace_buffer_lo));
06456 
06457           ipa_trace_buffer_ctrl.start = ipa_trace_buffer_lo;
06458           ipa_trace_buffer_ctrl.free = ipa_trace_buffer_lo;
06459           ipa_trace_buffer_ctrl.end_free = ipa_trace_buffer_hi;
06460           ipa_trace_buffer_ctrl.wrap = ipa_trace_buffer_hi;
06461         }
06462 
06463       trace_debug ("Uploaded a traceframe\n"
06464                    "Lib: Trace buffer [%d] start=%d free=%d "
06465                    "endfree=%d wrap=%d hi=%d",
06466                    curr_tbctrl_idx,
06467                    (int) (ipa_trace_buffer_ctrl.start - ipa_trace_buffer_lo),
06468                    (int) (ipa_trace_buffer_ctrl.free - ipa_trace_buffer_lo),
06469                    (int) (ipa_trace_buffer_ctrl.end_free
06470                           - ipa_trace_buffer_lo),
06471                    (int) (ipa_trace_buffer_ctrl.wrap - ipa_trace_buffer_lo),
06472                    (int) (ipa_trace_buffer_hi - ipa_trace_buffer_lo));
06473     }
06474 
06475   if (write_inferior_memory (ipa_trace_buffer_ctrl_addr,
06476                              (unsigned char *) &ipa_trace_buffer_ctrl,
06477                              sizeof (struct ipa_trace_buffer_control)))
06478     return;
06479 
06480   write_inferior_integer (ipa_sym_addrs.addr_traceframe_read_count,
06481                           ipa_traceframe_read_count);
06482 
06483   trace_debug ("Done uploading traceframes [%d]\n", curr_tbctrl_idx);
06484 
06485   pause_all (1);
06486   cancel_breakpoints ();
06487 
06488   delete_breakpoint (about_to_request_buffer_space_bkpt);
06489   about_to_request_buffer_space_bkpt = NULL;
06490 
06491   unpause_all (1);
06492 
06493   if (trace_buffer_is_full)
06494     stop_tracing ();
06495 }
06496 #endif
06497 
06498 #ifdef IN_PROCESS_AGENT
06499 
06500 IP_AGENT_EXPORT int ust_loaded;
06501 IP_AGENT_EXPORT char cmd_buf[IPA_CMD_BUF_SIZE];
06502 
06503 #ifdef HAVE_UST
06504 
06505 /* Static tracepoints.  */
06506 
06507 /* UST puts a "struct tracepoint" in the global namespace, which
06508    conflicts with our tracepoint.  Arguably, being a library, it
06509    shouldn't take ownership of such a generic name.  We work around it
06510    here.  */
06511 #define tracepoint ust_tracepoint
06512 #include <ust/ust.h>
06513 #undef tracepoint
06514 
06515 extern int serialize_to_text (char *outbuf, int bufsize,
06516                               const char *fmt, va_list ap);
06517 
06518 #define GDB_PROBE_NAME "gdb"
06519 
06520 /* We dynamically search for the UST symbols instead of linking them
06521    in.  This lets the user decide if the application uses static
06522    tracepoints, instead of always pulling libust.so in.  This vector
06523    holds pointers to all functions we care about.  */
06524 
06525 static struct
06526 {
06527   int (*serialize_to_text) (char *outbuf, int bufsize,
06528                             const char *fmt, va_list ap);
06529 
06530   int (*ltt_probe_register) (struct ltt_available_probe *pdata);
06531   int (*ltt_probe_unregister) (struct ltt_available_probe *pdata);
06532 
06533   int (*ltt_marker_connect) (const char *channel, const char *mname,
06534                              const char *pname);
06535   int (*ltt_marker_disconnect) (const char *channel, const char *mname,
06536                                 const char *pname);
06537 
06538   void (*marker_iter_start) (struct marker_iter *iter);
06539   void (*marker_iter_next) (struct marker_iter *iter);
06540   void (*marker_iter_stop) (struct marker_iter *iter);
06541   void (*marker_iter_reset) (struct marker_iter *iter);
06542 } ust_ops;
06543 
06544 #include <dlfcn.h>
06545 
06546 /* Cast through typeof to catch incompatible API changes.  Since UST
06547    only builds with gcc, we can freely use gcc extensions here
06548    too.  */
06549 #define GET_UST_SYM(SYM)                                        \
06550   do                                                            \
06551     {                                                           \
06552       if (ust_ops.SYM == NULL)                                  \
06553         ust_ops.SYM = (typeof (&SYM)) dlsym (RTLD_DEFAULT, #SYM);       \
06554       if (ust_ops.SYM == NULL)                                  \
06555         return 0;                                               \
06556     } while (0)
06557 
06558 #define USTF(SYM) ust_ops.SYM
06559 
06560 /* Get pointers to all libust.so functions we care about.  */
06561 
06562 static int
06563 dlsym_ust (void)
06564 {
06565   GET_UST_SYM (serialize_to_text);
06566 
06567   GET_UST_SYM (ltt_probe_register);
06568   GET_UST_SYM (ltt_probe_unregister);
06569   GET_UST_SYM (ltt_marker_connect);
06570   GET_UST_SYM (ltt_marker_disconnect);
06571 
06572   GET_UST_SYM (marker_iter_start);
06573   GET_UST_SYM (marker_iter_next);
06574   GET_UST_SYM (marker_iter_stop);
06575   GET_UST_SYM (marker_iter_reset);
06576 
06577   ust_loaded = 1;
06578   return 1;
06579 }
06580 
06581 /* Given an UST marker, return the matching gdb static tracepoint.
06582    The match is done by address.  */
06583 
06584 static struct tracepoint *
06585 ust_marker_to_static_tracepoint (const struct marker *mdata)
06586 {
06587   struct tracepoint *tpoint;
06588 
06589   for (tpoint = tracepoints; tpoint; tpoint = tpoint->next)
06590     {
06591       if (tpoint->type != static_tracepoint)
06592         continue;
06593 
06594       if (tpoint->address == (uintptr_t) mdata->location)
06595         return tpoint;
06596     }
06597 
06598   return NULL;
06599 }
06600 
06601 /* The probe function we install on lttng/ust markers.  Whenever a
06602    probed ust marker is hit, this function is called.  This is similar
06603    to gdb_collect, only for static tracepoints, instead of fast
06604    tracepoints.  */
06605 
06606 static void
06607 gdb_probe (const struct marker *mdata, void *probe_private,
06608            struct registers *regs, void *call_private,
06609            const char *fmt, va_list *args)
06610 {
06611   struct tracepoint *tpoint;
06612   struct static_tracepoint_ctx ctx;
06613 
06614   /* Don't do anything until the trace run is completely set up.  */
06615   if (!tracing)
06616     {
06617       trace_debug ("gdb_probe: not tracing\n");
06618       return;
06619     }
06620 
06621   ctx.base.type = static_tracepoint;
06622   ctx.regcache_initted = 0;
06623   ctx.regs = regs;
06624   ctx.fmt = fmt;
06625   ctx.args = args;
06626 
06627   /* Wrap the regblock in a register cache (in the stack, we don't
06628      want to malloc here).  */
06629   ctx.regspace = alloca (ipa_tdesc->registers_size);
06630   if (ctx.regspace == NULL)
06631     {
06632       trace_debug ("Trace buffer block allocation failed, skipping");
06633       return;
06634     }
06635 
06636   tpoint = ust_marker_to_static_tracepoint (mdata);
06637   if (tpoint == NULL)
06638     {
06639       trace_debug ("gdb_probe: marker not known: "
06640                    "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
06641                    mdata->location, mdata->channel,
06642                    mdata->name, mdata->format);
06643       return;
06644     }
06645 
06646   if (!tpoint->enabled)
06647     {
06648       trace_debug ("gdb_probe: tracepoint disabled");
06649       return;
06650     }
06651 
06652   ctx.tpoint = tpoint;
06653 
06654   trace_debug ("gdb_probe: collecting marker: "
06655                "loc:0x%p, ch:\"%s\",n:\"%s\",f:\"%s\"",
06656                mdata->location, mdata->channel,
06657                mdata->name, mdata->format);
06658 
06659   /* Test the condition if present, and collect if true.  */
06660   if (tpoint->cond == NULL
06661       || condition_true_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
06662                                        tpoint))
06663     {
06664       collect_data_at_tracepoint ((struct tracepoint_hit_ctx *) &ctx,
06665                                   tpoint->address, tpoint);
06666 
06667       if (stopping_tracepoint
06668           || trace_buffer_is_full
06669           || expr_eval_result != expr_eval_no_error)
06670         stop_tracing ();
06671     }
06672   else
06673     {
06674       /* If there was a condition and it evaluated to false, the only
06675          way we would stop tracing is if there was an error during
06676          condition expression evaluation.  */
06677       if (expr_eval_result != expr_eval_no_error)
06678         stop_tracing ();
06679     }
06680 }
06681 
06682 /* Called if the gdb static tracepoint requested collecting "$_sdata",
06683    static tracepoint string data.  This is a string passed to the
06684    tracing library by the user, at the time of the tracepoint marker
06685    call.  E.g., in the UST marker call:
06686 
06687      trace_mark (ust, bar33, "str %s", "FOOBAZ");
06688 
06689    the collected data is "str FOOBAZ".
06690 */
06691 
06692 static void
06693 collect_ust_data_at_tracepoint (struct tracepoint_hit_ctx *ctx,
06694                                 struct traceframe *tframe)
06695 {
06696   struct static_tracepoint_ctx *umd = (struct static_tracepoint_ctx *) ctx;
06697   unsigned char *bufspace;
06698   int size;
06699   va_list copy;
06700   unsigned short blocklen;
06701 
06702   if (umd == NULL)
06703     {
06704       trace_debug ("Wanted to collect static trace data, "
06705                    "but there's no static trace data");
06706       return;
06707     }
06708 
06709   va_copy (copy, *umd->args);
06710   size = USTF(serialize_to_text) (NULL, 0, umd->fmt, copy);
06711   va_end (copy);
06712 
06713   trace_debug ("Want to collect ust data");
06714 
06715   /* 'S' + size + string */
06716   bufspace = add_traceframe_block (tframe, umd->tpoint,
06717                                    1 + sizeof (blocklen) + size + 1);
06718   if (bufspace == NULL)
06719     {
06720       trace_debug ("Trace buffer block allocation failed, skipping");
06721       return;
06722     }
06723 
06724   /* Identify a static trace data block.  */
06725   *bufspace = 'S';
06726 
06727   blocklen = size + 1;
06728   memcpy (bufspace + 1, &blocklen, sizeof (blocklen));
06729 
06730   va_copy (copy, *umd->args);
06731   USTF(serialize_to_text) ((char *) bufspace + 1 + sizeof (blocklen),
06732                            size + 1, umd->fmt, copy);
06733   va_end (copy);
06734 
06735   trace_debug ("Storing static tracepoint data in regblock: %s",
06736                bufspace + 1 + sizeof (blocklen));
06737 }
06738 
06739 /* The probe to register with lttng/ust.  */
06740 static struct ltt_available_probe gdb_ust_probe =
06741   {
06742     GDB_PROBE_NAME,
06743     NULL,
06744     gdb_probe,
06745   };
06746 
06747 #endif /* HAVE_UST */
06748 #endif /* IN_PROCESS_AGENT */
06749 
06750 #ifndef IN_PROCESS_AGENT
06751 
06752 /* Ask the in-process agent to run a command.  Since we don't want to
06753    have to handle the IPA hitting breakpoints while running the
06754    command, we pause all threads, remove all breakpoints, and then set
06755    the helper thread re-running.  We communicate with the helper
06756    thread by means of direct memory xfering, and a socket for
06757    synchronization.  */
06758 
06759 static int
06760 run_inferior_command (char *cmd, int len)
06761 {
06762   int err = -1;
06763   int pid = ptid_get_pid (current_ptid);
06764 
06765   trace_debug ("run_inferior_command: running: %s", cmd);
06766 
06767   pause_all (0);
06768   uninsert_all_breakpoints ();
06769 
06770   err = agent_run_command (pid, (const char *) cmd, len);
06771 
06772   reinsert_all_breakpoints ();
06773   unpause_all (0);
06774 
06775   return err;
06776 }
06777 
06778 #else /* !IN_PROCESS_AGENT */
06779 
06780 #include <sys/socket.h>
06781 #include <sys/un.h>
06782 
06783 #ifndef UNIX_PATH_MAX
06784 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *) NULL)->sun_path)
06785 #endif
06786 
06787 /* Where we put the socked used for synchronization.  */
06788 #define SOCK_DIR P_tmpdir
06789 
06790 /* Thread ID of the helper thread.  GDBserver reads this to know which
06791    is the help thread.  This is an LWP id on Linux.  */
06792 int helper_thread_id;
06793 
06794 static int
06795 init_named_socket (const char *name)
06796 {
06797   int result, fd;
06798   struct sockaddr_un addr;
06799 
06800   result = fd = socket (PF_UNIX, SOCK_STREAM, 0);
06801   if (result == -1)
06802     {
06803       warning ("socket creation failed: %s", strerror (errno));
06804       return -1;
06805     }
06806 
06807   addr.sun_family = AF_UNIX;
06808 
06809   strncpy (addr.sun_path, name, UNIX_PATH_MAX);
06810   addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
06811 
06812   result = access (name, F_OK);
06813   if (result == 0)
06814     {
06815       /* File exists.  */
06816       result = unlink (name);
06817       if (result == -1)
06818         {
06819           warning ("unlink failed: %s", strerror (errno));
06820           close (fd);
06821           return -1;
06822         }
06823       warning ("socket %s already exists; overwriting", name);
06824     }
06825 
06826   result = bind (fd, (struct sockaddr *) &addr, sizeof (addr));
06827   if (result == -1)
06828     {
06829       warning ("bind failed: %s", strerror (errno));
06830       close (fd);
06831       return -1;
06832     }
06833 
06834   result = listen (fd, 1);
06835   if (result == -1)
06836     {
06837       warning ("listen: %s", strerror (errno));
06838       close (fd);
06839       return -1;
06840     }
06841 
06842   return fd;
06843 }
06844 
06845 static char agent_socket_name[UNIX_PATH_MAX];
06846 
06847 static int
06848 gdb_agent_socket_init (void)
06849 {
06850   int result, fd;
06851 
06852   result = xsnprintf (agent_socket_name, UNIX_PATH_MAX, "%s/gdb_ust%d",
06853                       SOCK_DIR, getpid ());
06854   if (result >= UNIX_PATH_MAX)
06855     {
06856       trace_debug ("string overflow allocating socket name");
06857       return -1;
06858     }
06859 
06860   fd = init_named_socket (agent_socket_name);
06861   if (fd < 0)
06862     warning ("Error initializing named socket (%s) for communication with the "
06863              "ust helper thread. Check that directory exists and that it "
06864              "is writable.", agent_socket_name);
06865 
06866   return fd;
06867 }
06868 
06869 #ifdef HAVE_UST
06870 
06871 /* The next marker to be returned on a qTsSTM command.  */
06872 static const struct marker *next_st;
06873 
06874 /* Returns the first known marker.  */
06875 
06876 struct marker *
06877 first_marker (void)
06878 {
06879   struct marker_iter iter;
06880 
06881   USTF(marker_iter_reset) (&iter);
06882   USTF(marker_iter_start) (&iter);
06883 
06884   return iter.marker;
06885 }
06886 
06887 /* Returns the marker following M.  */
06888 
06889 const struct marker *
06890 next_marker (const struct marker *m)
06891 {
06892   struct marker_iter iter;
06893 
06894   USTF(marker_iter_reset) (&iter);
06895   USTF(marker_iter_start) (&iter);
06896 
06897   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
06898     {
06899       if (iter.marker == m)
06900         {
06901           USTF(marker_iter_next) (&iter);
06902           return iter.marker;
06903         }
06904     }
06905 
06906   return NULL;
06907 }
06908 
06909 /* Return an hexstr version of the STR C string, fit for sending to
06910    GDB.  */
06911 
06912 static char *
06913 cstr_to_hexstr (const char *str)
06914 {
06915   int len = strlen (str);
06916   char *hexstr = xmalloc (len * 2 + 1);
06917   convert_int_to_ascii ((gdb_byte *) str, hexstr, len);
06918   return hexstr;
06919 }
06920 
06921 /* Compose packet that is the response to the qTsSTM/qTfSTM/qTSTMat
06922    packets.  */
06923 
06924 static void
06925 response_ust_marker (char *packet, const struct marker *st)
06926 {
06927   char *strid, *format, *tmp;
06928 
06929   next_st = next_marker (st);
06930 
06931   tmp = xmalloc (strlen (st->channel) + 1 +
06932                  strlen (st->name) + 1);
06933   sprintf (tmp, "%s/%s", st->channel, st->name);
06934 
06935   strid = cstr_to_hexstr (tmp);
06936   free (tmp);
06937 
06938   format = cstr_to_hexstr (st->format);
06939 
06940   sprintf (packet, "m%s:%s:%s",
06941            paddress ((uintptr_t) st->location),
06942            strid,
06943            format);
06944 
06945   free (strid);
06946   free (format);
06947 }
06948 
06949 /* Return the first static tracepoint, and initialize the state
06950    machine that will iterate through all the static tracepoints.  */
06951 
06952 static void
06953 cmd_qtfstm (char *packet)
06954 {
06955   trace_debug ("Returning first trace state variable definition");
06956 
06957   if (first_marker ())
06958     response_ust_marker (packet, first_marker ());
06959   else
06960     strcpy (packet, "l");
06961 }
06962 
06963 /* Return additional trace state variable definitions. */
06964 
06965 static void
06966 cmd_qtsstm (char *packet)
06967 {
06968   trace_debug ("Returning static tracepoint");
06969 
06970   if (next_st)
06971     response_ust_marker (packet, next_st);
06972   else
06973     strcpy (packet, "l");
06974 }
06975 
06976 /* Disconnect the GDB probe from a marker at a given address.  */
06977 
06978 static void
06979 unprobe_marker_at (char *packet)
06980 {
06981   char *p = packet;
06982   ULONGEST address;
06983   struct marker_iter iter;
06984 
06985   p += sizeof ("unprobe_marker_at:") - 1;
06986 
06987   p = unpack_varlen_hex (p, &address);
06988 
06989   USTF(marker_iter_reset) (&iter);
06990   USTF(marker_iter_start) (&iter);
06991   for (; iter.marker != NULL; USTF(marker_iter_next) (&iter))
06992     if ((uintptr_t ) iter.marker->location == address)
06993       {
06994         int result;
06995 
06996         result = USTF(ltt_marker_disconnect) (iter.marker->channel,
06997                                               iter.marker->name,
06998                                               GDB_PROBE_NAME);
06999         if (result < 0)
07000           warning ("could not disable marker %s/%s",
07001                    iter.marker->channel, iter.marker->name);
07002         break;
07003       }
07004 }
07005 
07006 /* Connect the GDB probe to a marker at a given address.  */
07007 
07008 static int
07009 probe_marker_at (char *packet)
07010 {
07011   char *p = packet;
07012   ULONGEST address;
07013   struct marker_iter iter;
07014   struct marker *m;
07015 
07016   p += sizeof ("probe_marker_at:") - 1;
07017 
07018   p = unpack_varlen_hex (p, &address);
07019 
07020   USTF(marker_iter_reset) (&iter);
07021 
07022   for (USTF(marker_iter_start) (&iter), m = iter.marker;
07023        m != NULL;
07024        USTF(marker_iter_next) (&iter), m = iter.marker)
07025     if ((uintptr_t ) m->location == address)
07026       {
07027         int result;
07028 
07029         trace_debug ("found marker for address.  "
07030                      "ltt_marker_connect (marker = %s/%s)",
07031                      m->channel, m->name);
07032 
07033         result = USTF(ltt_marker_connect) (m->channel, m->name,
07034                                            GDB_PROBE_NAME);
07035         if (result && result != -EEXIST)
07036           trace_debug ("ltt_marker_connect (marker = %s/%s, errno = %d)",
07037                        m->channel, m->name, -result);
07038 
07039         if (result < 0)
07040           {
07041             sprintf (packet, "E.could not connect marker: channel=%s, name=%s",
07042                      m->channel, m->name);
07043             return -1;
07044           }
07045 
07046         strcpy (packet, "OK");
07047         return 0;
07048       }
07049 
07050   sprintf (packet, "E.no marker found at 0x%s", paddress (address));
07051   return -1;
07052 }
07053 
07054 static int
07055 cmd_qtstmat (char *packet)
07056 {
07057   char *p = packet;
07058   ULONGEST address;
07059   struct marker_iter iter;
07060   struct marker *m;
07061 
07062   p += sizeof ("qTSTMat:") - 1;
07063 
07064   p = unpack_varlen_hex (p, &address);
07065 
07066   USTF(marker_iter_reset) (&iter);
07067 
07068   for (USTF(marker_iter_start) (&iter), m = iter.marker;
07069        m != NULL;
07070        USTF(marker_iter_next) (&iter), m = iter.marker)
07071     if ((uintptr_t ) m->location == address)
07072       {
07073         response_ust_marker (packet, m);
07074         return 0;
07075       }
07076 
07077   strcpy (packet, "l");
07078   return -1;
07079 }
07080 
07081 static void
07082 gdb_ust_init (void)
07083 {
07084   if (!dlsym_ust ())
07085     return;
07086 
07087   USTF(ltt_probe_register) (&gdb_ust_probe);
07088 }
07089 
07090 #endif /* HAVE_UST */
07091 
07092 #include <sys/syscall.h>
07093 #include <stdlib.h>
07094 
07095 static void
07096 gdb_agent_remove_socket (void)
07097 {
07098   unlink (agent_socket_name);
07099 }
07100 
07101 /* Helper thread of agent.  */
07102 
07103 static void *
07104 gdb_agent_helper_thread (void *arg)
07105 {
07106   int listen_fd;
07107 
07108   atexit (gdb_agent_remove_socket);
07109 
07110   while (1)
07111     {
07112       listen_fd = gdb_agent_socket_init ();
07113 
07114       if (helper_thread_id == 0)
07115         helper_thread_id = syscall (SYS_gettid);
07116 
07117       if (listen_fd == -1)
07118         {
07119           warning ("could not create sync socket\n");
07120           break;
07121         }
07122 
07123       while (1)
07124         {
07125           socklen_t tmp;
07126           struct sockaddr_un sockaddr;
07127           int fd;
07128           char buf[1];
07129           int ret;
07130           int stop_loop = 0;
07131 
07132           tmp = sizeof (sockaddr);
07133 
07134           do
07135             {
07136               fd = accept (listen_fd, &sockaddr, &tmp);
07137             }
07138           /* It seems an ERESTARTSYS can escape out of accept.  */
07139           while (fd == -512 || (fd == -1 && errno == EINTR));
07140 
07141           if (fd < 0)
07142             {
07143               warning ("Accept returned %d, error: %s\n",
07144                        fd, strerror (errno));
07145               break;
07146             }
07147 
07148           do
07149             {
07150               ret = read (fd, buf, 1);
07151             } while (ret == -1 && errno == EINTR);
07152 
07153           if (ret == -1)
07154             {
07155               warning ("reading socket (fd=%d) failed with %s",
07156                        fd, strerror (errno));
07157               close (fd);
07158               break;
07159             }
07160 
07161           if (cmd_buf[0])
07162             {
07163               if (strncmp ("close", cmd_buf, 5) == 0)
07164                 {
07165                   stop_loop = 1;
07166                 }
07167 #ifdef HAVE_UST
07168               else if (strcmp ("qTfSTM", cmd_buf) == 0)
07169                 {
07170                   cmd_qtfstm (cmd_buf);
07171                 }
07172               else if (strcmp ("qTsSTM", cmd_buf) == 0)
07173                 {
07174                   cmd_qtsstm (cmd_buf);
07175                 }
07176               else if (strncmp ("unprobe_marker_at:",
07177                                 cmd_buf,
07178                                 sizeof ("unprobe_marker_at:") - 1) == 0)
07179                 {
07180                   unprobe_marker_at (cmd_buf);
07181                 }
07182               else if (strncmp ("probe_marker_at:",
07183                                 cmd_buf,
07184                                 sizeof ("probe_marker_at:") - 1) == 0)
07185                 {
07186                   probe_marker_at (cmd_buf);
07187                 }
07188               else if (strncmp ("qTSTMat:",
07189                                 cmd_buf,
07190                                 sizeof ("qTSTMat:") - 1) == 0)
07191                 {
07192                   cmd_qtstmat (cmd_buf);
07193                 }
07194 #endif /* HAVE_UST */
07195             }
07196 
07197           /* Fix compiler's warning: ignoring return value of 'write'.  */
07198           ret = write (fd, buf, 1);
07199           close (fd);
07200 
07201           if (stop_loop)
07202             {
07203               close (listen_fd);
07204               unlink (agent_socket_name);
07205 
07206               /* Sleep endlessly to wait the whole inferior stops.  This
07207                  thread can not exit because GDB or GDBserver may still need
07208                  'current_inferior' (representing this thread) to access
07209                  inferior memory.  Otherwise, this thread exits earlier than
07210                  other threads, and 'current_inferior' is set to NULL.  */
07211               while (1)
07212                 sleep (10);
07213             }
07214         }
07215     }
07216 
07217   return NULL;
07218 }
07219 
07220 #include <signal.h>
07221 #include <pthread.h>
07222 
07223 IP_AGENT_EXPORT int gdb_agent_capability = AGENT_CAPA_STATIC_TRACE;
07224 
07225 static void
07226 gdb_agent_init (void)
07227 {
07228   int res;
07229   pthread_t thread;
07230   sigset_t new_mask;
07231   sigset_t orig_mask;
07232 
07233   /* We want the helper thread to be as transparent as possible, so
07234      have it inherit an all-signals-blocked mask.  */
07235 
07236   sigfillset (&new_mask);
07237   res = pthread_sigmask (SIG_SETMASK, &new_mask, &orig_mask);
07238   if (res)
07239     fatal ("pthread_sigmask (1) failed: %s", strerror (res));
07240 
07241   res = pthread_create (&thread,
07242                         NULL,
07243                         gdb_agent_helper_thread,
07244                         NULL);
07245 
07246   res = pthread_sigmask (SIG_SETMASK, &orig_mask, NULL);
07247   if (res)
07248     fatal ("pthread_sigmask (2) failed: %s", strerror (res));
07249 
07250   while (helper_thread_id == 0)
07251     usleep (1);
07252 
07253 #ifdef HAVE_UST
07254   gdb_ust_init ();
07255 #endif
07256 }
07257 
07258 #include <sys/mman.h>
07259 #include <fcntl.h>
07260 
07261 IP_AGENT_EXPORT char *gdb_tp_heap_buffer;
07262 IP_AGENT_EXPORT char *gdb_jump_pad_buffer;
07263 IP_AGENT_EXPORT char *gdb_jump_pad_buffer_end;
07264 IP_AGENT_EXPORT char *gdb_trampoline_buffer;
07265 IP_AGENT_EXPORT char *gdb_trampoline_buffer_end;
07266 IP_AGENT_EXPORT char *gdb_trampoline_buffer_error;
07267 
07268 /* Record the result of getting buffer space for fast tracepoint
07269    trampolines.  Any error message is copied, since caller may not be
07270    using persistent storage.  */
07271 
07272 void
07273 set_trampoline_buffer_space (CORE_ADDR begin, CORE_ADDR end, char *errmsg)
07274 {
07275   gdb_trampoline_buffer = (char *) (uintptr_t) begin;
07276   gdb_trampoline_buffer_end = (char *) (uintptr_t) end;
07277   if (errmsg)
07278     strncpy (gdb_trampoline_buffer_error, errmsg, 99);
07279   else
07280     strcpy (gdb_trampoline_buffer_error, "no buffer passed");
07281 }
07282 
07283 static void __attribute__ ((constructor))
07284 initialize_tracepoint_ftlib (void)
07285 {
07286   initialize_tracepoint ();
07287 
07288   gdb_agent_init ();
07289 }
07290 
07291 #endif /* IN_PROCESS_AGENT */
07292 
07293 /* Return a timestamp, expressed as microseconds of the usual Unix
07294    time.  (As the result is a 64-bit number, it will not overflow any
07295    time soon.)  */
07296 
07297 static LONGEST
07298 get_timestamp (void)
07299 {
07300    struct timeval tv;
07301 
07302    if (gettimeofday (&tv, 0) != 0)
07303      return -1;
07304    else
07305      return (LONGEST) tv.tv_sec * 1000000 + tv.tv_usec;
07306 }
07307 
07308 void
07309 initialize_tracepoint (void)
07310 {
07311   /* Start with the default size.  */
07312   init_trace_buffer (DEFAULT_TRACE_BUFFER_SIZE);
07313 
07314   /* Wire trace state variable 1 to be the timestamp.  This will be
07315      uploaded to GDB upon connection and become one of its trace state
07316      variables.  (In case you're wondering, if GDB already has a trace
07317      variable numbered 1, it will be renumbered.)  */
07318   create_trace_state_variable (1, 0);
07319   set_trace_state_variable_name (1, "trace_timestamp");
07320   set_trace_state_variable_getter (1, get_timestamp);
07321 
07322 #ifdef IN_PROCESS_AGENT
07323   {
07324     uintptr_t addr;
07325     int pagesize;
07326 
07327     pagesize = sysconf (_SC_PAGE_SIZE);
07328     if (pagesize == -1)
07329       fatal ("sysconf");
07330 
07331     gdb_tp_heap_buffer = xmalloc (5 * 1024 * 1024);
07332 
07333 #define SCRATCH_BUFFER_NPAGES 20
07334 
07335     /* Allocate scratch buffer aligned on a page boundary, at a low
07336        address (close to the main executable's code).  */
07337     for (addr = pagesize; addr != 0; addr += pagesize)
07338       {
07339         gdb_jump_pad_buffer = mmap ((void *) addr, pagesize * SCRATCH_BUFFER_NPAGES,
07340                                     PROT_READ | PROT_WRITE | PROT_EXEC,
07341                                     MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
07342                                     -1, 0);
07343         if (gdb_jump_pad_buffer != MAP_FAILED)
07344           break;
07345       }
07346 
07347     if (addr == 0)
07348       fatal ("\
07349 initialize_tracepoint: mmap'ing jump pad buffer failed with %s",
07350              strerror (errno));
07351 
07352     gdb_jump_pad_buffer_end = gdb_jump_pad_buffer + pagesize * SCRATCH_BUFFER_NPAGES;
07353   }
07354 
07355   gdb_trampoline_buffer = gdb_trampoline_buffer_end = 0;
07356 
07357   /* It's not a fatal error for something to go wrong with trampoline
07358      buffer setup, but it can be mysterious, so create a channel to
07359      report back on what went wrong, using a fixed size since we may
07360      not be able to allocate space later when the problem occurs.  */
07361   gdb_trampoline_buffer_error = xmalloc (IPA_BUFSIZ);
07362 
07363   strcpy (gdb_trampoline_buffer_error, "No errors reported");
07364 
07365   initialize_low_tracepoint ();
07366 #endif
07367 }
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Defines