gdb/tracepoint.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Tracing functionality for remote targets in custom GDB protocol

  2.    Copyright (C) 1997-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

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

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

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

  14. #include "defs.h"
  15. #include "arch-utils.h"
  16. #include "symtab.h"
  17. #include "frame.h"
  18. #include "gdbtypes.h"
  19. #include "expression.h"
  20. #include "gdbcmd.h"
  21. #include "value.h"
  22. #include "target.h"
  23. #include "target-dcache.h"
  24. #include "language.h"
  25. #include "inferior.h"
  26. #include "breakpoint.h"
  27. #include "tracepoint.h"
  28. #include "linespec.h"
  29. #include "regcache.h"
  30. #include "completer.h"
  31. #include "block.h"
  32. #include "dictionary.h"
  33. #include "observer.h"
  34. #include "user-regs.h"
  35. #include "valprint.h"
  36. #include "gdbcore.h"
  37. #include "objfiles.h"
  38. #include "filenames.h"
  39. #include "gdbthread.h"
  40. #include "stack.h"
  41. #include "remote.h"
  42. #include "source.h"
  43. #include "ax.h"
  44. #include "ax-gdb.h"
  45. #include "memrange.h"
  46. #include "cli/cli-utils.h"
  47. #include "probe.h"
  48. #include "ctf.h"
  49. #include "filestuff.h"
  50. #include "rsp-low.h"
  51. #include "tracefile.h"

  52. /* readline include files */
  53. #include "readline/readline.h"
  54. #include "readline/history.h"

  55. /* readline defines this.  */
  56. #undef savestring

  57. #include <unistd.h>

  58. /* Maximum length of an agent aexpression.
  59.    This accounts for the fact that packets are limited to 400 bytes
  60.    (which includes everything -- including the checksum), and assumes
  61.    the worst case of maximum length for each of the pieces of a
  62.    continuation packet.

  63.    NOTE: expressions get mem2hex'ed otherwise this would be twice as
  64.    large.  (400 - 31)/2 == 184 */
  65. #define MAX_AGENT_EXPR_LEN        184

  66. /* A hook used to notify the UI of tracepoint operations.  */

  67. void (*deprecated_trace_find_hook) (char *arg, int from_tty);
  68. void (*deprecated_trace_start_stop_hook) (int start, int from_tty);

  69. /*
  70.    Tracepoint.c:

  71.    This module defines the following debugger commands:
  72.    trace            : set a tracepoint on a function, line, or address.
  73.    info trace       : list all debugger-defined tracepoints.
  74.    delete trace     : delete one or more tracepoints.
  75.    enable trace     : enable one or more tracepoints.
  76.    disable trace    : disable one or more tracepoints.
  77.    actions          : specify actions to be taken at a tracepoint.
  78.    passcount        : specify a pass count for a tracepoint.
  79.    tstart           : start a trace experiment.
  80.    tstop            : stop a trace experiment.
  81.    tstatus          : query the status of a trace experiment.
  82.    tfind            : find a trace frame in the trace buffer.
  83.    tdump            : print everything collected at the current tracepoint.
  84.    save-tracepoints : write tracepoint setup into a file.

  85.    This module defines the following user-visible debugger variables:
  86.    $trace_frame : sequence number of trace frame currently being debugged.
  87.    $trace_line  : source line of trace frame currently being debugged.
  88.    $trace_file  : source file of trace frame currently being debugged.
  89.    $tracepoint  : tracepoint number of trace frame currently being debugged.
  90. */


  91. /* ======= Important global variables: ======= */

  92. /* The list of all trace state variables.  We don't retain pointers to
  93.    any of these for any reason - API is by name or number only - so it
  94.    works to have a vector of objects.  */

  95. typedef struct trace_state_variable tsv_s;
  96. DEF_VEC_O(tsv_s);

  97. static VEC(tsv_s) *tvariables;

  98. /* The next integer to assign to a variable.  */

  99. static int next_tsv_number = 1;

  100. /* Number of last traceframe collected.  */
  101. static int traceframe_number;

  102. /* Tracepoint for last traceframe collected.  */
  103. static int tracepoint_number;

  104. /* The traceframe info of the current traceframe.  NULL if we haven't
  105.    yet attempted to fetch it, or if the target does not support
  106.    fetching this object, or if we're not inspecting a traceframe
  107.    presently.  */
  108. static struct traceframe_info *traceframe_info;

  109. /* Tracing command lists.  */
  110. static struct cmd_list_element *tfindlist;

  111. /* List of expressions to collect by default at each tracepoint hit.  */
  112. char *default_collect = "";

  113. static int disconnected_tracing;

  114. /* This variable controls whether we ask the target for a linear or
  115.    circular trace buffer.  */

  116. static int circular_trace_buffer;

  117. /* This variable is the requested trace buffer size, or -1 to indicate
  118.    that we don't care and leave it up to the target to set a size.  */

  119. static int trace_buffer_size = -1;

  120. /* Textual notes applying to the current and/or future trace runs.  */

  121. char *trace_user = NULL;

  122. /* Textual notes applying to the current and/or future trace runs.  */

  123. char *trace_notes = NULL;

  124. /* Textual notes applying to the stopping of a trace.  */

  125. char *trace_stop_notes = NULL;

  126. /* ======= Important command functions: ======= */
  127. static void trace_actions_command (char *, int);
  128. static void trace_start_command (char *, int);
  129. static void trace_stop_command (char *, int);
  130. static void trace_status_command (char *, int);
  131. static void trace_find_command (char *, int);
  132. static void trace_find_pc_command (char *, int);
  133. static void trace_find_tracepoint_command (char *, int);
  134. static void trace_find_line_command (char *, int);
  135. static void trace_find_range_command (char *, int);
  136. static void trace_find_outside_command (char *, int);
  137. static void trace_dump_command (char *, int);

  138. /* support routines */

  139. struct collection_list;
  140. static void add_aexpr (struct collection_list *, struct agent_expr *);
  141. static char *mem2hex (gdb_byte *, char *, int);
  142. static void add_register (struct collection_list *collection,
  143.                           unsigned int regno);

  144. static struct command_line *
  145.   all_tracepoint_actions_and_cleanup (struct breakpoint *t);

  146. extern void _initialize_tracepoint (void);

  147. static struct trace_status trace_status;

  148. const char *stop_reason_names[] = {
  149.   "tunknown",
  150.   "tnotrun",
  151.   "tstop",
  152.   "tfull",
  153.   "tdisconnected",
  154.   "tpasscount",
  155.   "terror"
  156. };

  157. struct trace_status *
  158. current_trace_status (void)
  159. {
  160.   return &trace_status;
  161. }

  162. /* Destroy INFO.  */

  163. static void
  164. free_traceframe_info (struct traceframe_info *info)
  165. {
  166.   if (info != NULL)
  167.     {
  168.       VEC_free (mem_range_s, info->memory);
  169.       VEC_free (int, info->tvars);

  170.       xfree (info);
  171.     }
  172. }

  173. /* Free and clear the traceframe info cache of the current
  174.    traceframe.  */

  175. static void
  176. clear_traceframe_info (void)
  177. {
  178.   free_traceframe_info (traceframe_info);
  179.   traceframe_info = NULL;
  180. }

  181. /* Set traceframe number to NUM.  */
  182. static void
  183. set_traceframe_num (int num)
  184. {
  185.   traceframe_number = num;
  186.   set_internalvar_integer (lookup_internalvar ("trace_frame"), num);
  187. }

  188. /* Set tracepoint number to NUM.  */
  189. static void
  190. set_tracepoint_num (int num)
  191. {
  192.   tracepoint_number = num;
  193.   set_internalvar_integer (lookup_internalvar ("tracepoint"), num);
  194. }

  195. /* Set externally visible debug variables for querying/printing
  196.    the traceframe context (line, function, file).  */

  197. static void
  198. set_traceframe_context (struct frame_info *trace_frame)
  199. {
  200.   CORE_ADDR trace_pc;
  201.   struct symbol *traceframe_fun;
  202.   struct symtab_and_line traceframe_sal;

  203.   /* Save as globals for internal use.  */
  204.   if (trace_frame != NULL
  205.       && get_frame_pc_if_available (trace_frame, &trace_pc))
  206.     {
  207.       traceframe_sal = find_pc_line (trace_pc, 0);
  208.       traceframe_fun = find_pc_function (trace_pc);

  209.       /* Save linenumber as "$trace_line", a debugger variable visible to
  210.          users.  */
  211.       set_internalvar_integer (lookup_internalvar ("trace_line"),
  212.                                traceframe_sal.line);
  213.     }
  214.   else
  215.     {
  216.       init_sal (&traceframe_sal);
  217.       traceframe_fun = NULL;
  218.       set_internalvar_integer (lookup_internalvar ("trace_line"), -1);
  219.     }

  220.   /* Save func name as "$trace_func", a debugger variable visible to
  221.      users.  */
  222.   if (traceframe_fun == NULL
  223.       || SYMBOL_LINKAGE_NAME (traceframe_fun) == NULL)
  224.     clear_internalvar (lookup_internalvar ("trace_func"));
  225.   else
  226.     set_internalvar_string (lookup_internalvar ("trace_func"),
  227.                             SYMBOL_LINKAGE_NAME (traceframe_fun));

  228.   /* Save file name as "$trace_file", a debugger variable visible to
  229.      users.  */
  230.   if (traceframe_sal.symtab == NULL)
  231.     clear_internalvar (lookup_internalvar ("trace_file"));
  232.   else
  233.     set_internalvar_string (lookup_internalvar ("trace_file"),
  234.                         symtab_to_filename_for_display (traceframe_sal.symtab));
  235. }

  236. /* Create a new trace state variable with the given name.  */

  237. struct trace_state_variable *
  238. create_trace_state_variable (const char *name)
  239. {
  240.   struct trace_state_variable tsv;

  241.   memset (&tsv, 0, sizeof (tsv));
  242.   tsv.name = xstrdup (name);
  243.   tsv.number = next_tsv_number++;
  244.   return VEC_safe_push (tsv_s, tvariables, &tsv);
  245. }

  246. /* Look for a trace state variable of the given name.  */

  247. struct trace_state_variable *
  248. find_trace_state_variable (const char *name)
  249. {
  250.   struct trace_state_variable *tsv;
  251.   int ix;

  252.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  253.     if (strcmp (name, tsv->name) == 0)
  254.       return tsv;

  255.   return NULL;
  256. }

  257. /* Look for a trace state variable of the given number.  Return NULL if
  258.    not found.  */

  259. struct trace_state_variable *
  260. find_trace_state_variable_by_number (int number)
  261. {
  262.   struct trace_state_variable *tsv;
  263.   int ix;

  264.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  265.     if (tsv->number == number)
  266.       return tsv;

  267.   return NULL;
  268. }

  269. static void
  270. delete_trace_state_variable (const char *name)
  271. {
  272.   struct trace_state_variable *tsv;
  273.   int ix;

  274.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  275.     if (strcmp (name, tsv->name) == 0)
  276.       {
  277.         observer_notify_tsv_deleted (tsv);

  278.         xfree ((void *)tsv->name);
  279.         VEC_unordered_remove (tsv_s, tvariables, ix);

  280.         return;
  281.       }

  282.   warning (_("No trace variable named \"$%s\", not deleting"), name);
  283. }

  284. /* Throws an error if NAME is not valid syntax for a trace state
  285.    variable's name.  */

  286. void
  287. validate_trace_state_variable_name (const char *name)
  288. {
  289.   const char *p;

  290.   if (*name == '\0')
  291.     error (_("Must supply a non-empty variable name"));

  292.   /* All digits in the name is reserved for value history
  293.      references.  */
  294.   for (p = name; isdigit (*p); p++)
  295.     ;
  296.   if (*p == '\0')
  297.     error (_("$%s is not a valid trace state variable name"), name);

  298.   for (p = name; isalnum (*p) || *p == '_'; p++)
  299.     ;
  300.   if (*p != '\0')
  301.     error (_("$%s is not a valid trace state variable name"), name);
  302. }

  303. /* The 'tvariable' command collects a name and optional expression to
  304.    evaluate into an initial value.  */

  305. static void
  306. trace_variable_command (char *args, int from_tty)
  307. {
  308.   struct cleanup *old_chain;
  309.   LONGEST initval = 0;
  310.   struct trace_state_variable *tsv;
  311.   char *name, *p;

  312.   if (!args || !*args)
  313.     error_no_arg (_("Syntax is $NAME [ = EXPR ]"));

  314.   /* Only allow two syntaxes; "$name" and "$name=value".  */
  315.   p = skip_spaces (args);

  316.   if (*p++ != '$')
  317.     error (_("Name of trace variable should start with '$'"));

  318.   name = p;
  319.   while (isalnum (*p) || *p == '_')
  320.     p++;
  321.   name = savestring (name, p - name);
  322.   old_chain = make_cleanup (xfree, name);

  323.   p = skip_spaces (p);
  324.   if (*p != '=' && *p != '\0')
  325.     error (_("Syntax must be $NAME [ = EXPR ]"));

  326.   validate_trace_state_variable_name (name);

  327.   if (*p == '=')
  328.     initval = value_as_long (parse_and_eval (++p));

  329.   /* If the variable already exists, just change its initial value.  */
  330.   tsv = find_trace_state_variable (name);
  331.   if (tsv)
  332.     {
  333.       if (tsv->initial_value != initval)
  334.         {
  335.           tsv->initial_value = initval;
  336.           observer_notify_tsv_modified (tsv);
  337.         }
  338.       printf_filtered (_("Trace state variable $%s "
  339.                          "now has initial value %s.\n"),
  340.                        tsv->name, plongest (tsv->initial_value));
  341.       do_cleanups (old_chain);
  342.       return;
  343.     }

  344.   /* Create a new variable.  */
  345.   tsv = create_trace_state_variable (name);
  346.   tsv->initial_value = initval;

  347.   observer_notify_tsv_created (tsv);

  348.   printf_filtered (_("Trace state variable $%s "
  349.                      "created, with initial value %s.\n"),
  350.                    tsv->name, plongest (tsv->initial_value));

  351.   do_cleanups (old_chain);
  352. }

  353. static void
  354. delete_trace_variable_command (char *args, int from_tty)
  355. {
  356.   int ix;
  357.   char **argv;
  358.   struct cleanup *back_to;

  359.   if (args == NULL)
  360.     {
  361.       if (query (_("Delete all trace state variables? ")))
  362.         VEC_free (tsv_s, tvariables);
  363.       dont_repeat ();
  364.       observer_notify_tsv_deleted (NULL);
  365.       return;
  366.     }

  367.   argv = gdb_buildargv (args);
  368.   back_to = make_cleanup_freeargv (argv);

  369.   for (ix = 0; argv[ix] != NULL; ix++)
  370.     {
  371.       if (*argv[ix] == '$')
  372.         delete_trace_state_variable (argv[ix] + 1);
  373.       else
  374.         warning (_("Name \"%s\" not prefixed with '$', ignoring"), argv[ix]);
  375.     }

  376.   do_cleanups (back_to);

  377.   dont_repeat ();
  378. }

  379. void
  380. tvariables_info_1 (void)
  381. {
  382.   struct trace_state_variable *tsv;
  383.   int ix;
  384.   int count = 0;
  385.   struct cleanup *back_to;
  386.   struct ui_out *uiout = current_uiout;

  387.   if (VEC_length (tsv_s, tvariables) == 0 && !ui_out_is_mi_like_p (uiout))
  388.     {
  389.       printf_filtered (_("No trace state variables.\n"));
  390.       return;
  391.     }

  392.   /* Try to acquire values from the target.  */
  393.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix, ++count)
  394.     tsv->value_known = target_get_trace_state_variable_value (tsv->number,
  395.                                                               &(tsv->value));

  396.   back_to = make_cleanup_ui_out_table_begin_end (uiout, 3,
  397.                                                  count, "trace-variables");
  398.   ui_out_table_header (uiout, 15, ui_left, "name", "Name");
  399.   ui_out_table_header (uiout, 11, ui_left, "initial", "Initial");
  400.   ui_out_table_header (uiout, 11, ui_left, "current", "Current");

  401.   ui_out_table_body (uiout);

  402.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  403.     {
  404.       struct cleanup *back_to2;
  405.       char *c;
  406.       char *name;

  407.       back_to2 = make_cleanup_ui_out_tuple_begin_end (uiout, "variable");

  408.       name = concat ("$", tsv->name, (char *) NULL);
  409.       make_cleanup (xfree, name);
  410.       ui_out_field_string (uiout, "name", name);
  411.       ui_out_field_string (uiout, "initial", plongest (tsv->initial_value));

  412.       if (tsv->value_known)
  413.         c = plongest (tsv->value);
  414.       else if (ui_out_is_mi_like_p (uiout))
  415.         /* For MI, we prefer not to use magic string constants, but rather
  416.            omit the field completely.  The difference between unknown and
  417.            undefined does not seem important enough to represent.  */
  418.         c = NULL;
  419.       else if (current_trace_status ()->running || traceframe_number >= 0)
  420.         /* The value is/was defined, but we don't have it.  */
  421.         c = "<unknown>";
  422.       else
  423.         /* It is not meaningful to ask about the value.  */
  424.         c = "<undefined>";
  425.       if (c)
  426.         ui_out_field_string (uiout, "current", c);
  427.       ui_out_text (uiout, "\n");

  428.       do_cleanups (back_to2);
  429.     }

  430.   do_cleanups (back_to);
  431. }

  432. /* List all the trace state variables.  */

  433. static void
  434. tvariables_info (char *args, int from_tty)
  435. {
  436.   tvariables_info_1 ();
  437. }

  438. /* Stash definitions of tsvs into the given file.  */

  439. void
  440. save_trace_state_variables (struct ui_file *fp)
  441. {
  442.   struct trace_state_variable *tsv;
  443.   int ix;

  444.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  445.     {
  446.       fprintf_unfiltered (fp, "tvariable $%s", tsv->name);
  447.       if (tsv->initial_value)
  448.         fprintf_unfiltered (fp, " = %s", plongest (tsv->initial_value));
  449.       fprintf_unfiltered (fp, "\n");
  450.     }
  451. }

  452. /* ACTIONS functions: */

  453. /* The three functions:
  454.    collect_pseudocommand,
  455.    while_stepping_pseudocommand, and
  456.    end_actions_pseudocommand
  457.    are placeholders for "commands" that are actually ONLY to be used
  458.    within a tracepoint action list.  If the actual function is ever called,
  459.    it means that somebody issued the "command" at the top level,
  460.    which is always an error.  */

  461. static void
  462. end_actions_pseudocommand (char *args, int from_tty)
  463. {
  464.   error (_("This command cannot be used at the top level."));
  465. }

  466. static void
  467. while_stepping_pseudocommand (char *args, int from_tty)
  468. {
  469.   error (_("This command can only be used in a tracepoint actions list."));
  470. }

  471. static void
  472. collect_pseudocommand (char *args, int from_tty)
  473. {
  474.   error (_("This command can only be used in a tracepoint actions list."));
  475. }

  476. static void
  477. teval_pseudocommand (char *args, int from_tty)
  478. {
  479.   error (_("This command can only be used in a tracepoint actions list."));
  480. }

  481. /* Parse any collection options, such as /s for strings.  */

  482. const char *
  483. decode_agent_options (const char *exp, int *trace_string)
  484. {
  485.   struct value_print_options opts;

  486.   *trace_string = 0;

  487.   if (*exp != '/')
  488.     return exp;

  489.   /* Call this to borrow the print elements default for collection
  490.      size.  */
  491.   get_user_print_options (&opts);

  492.   exp++;
  493.   if (*exp == 's')
  494.     {
  495.       if (target_supports_string_tracing ())
  496.         {
  497.           /* Allow an optional decimal number giving an explicit maximum
  498.              string length, defaulting it to the "print elements" value;
  499.              so "collect/s80 mystr" gets at most 80 bytes of string.  */
  500.           *trace_string = opts.print_max;
  501.           exp++;
  502.           if (*exp >= '0' && *exp <= '9')
  503.             *trace_string = atoi (exp);
  504.           while (*exp >= '0' && *exp <= '9')
  505.             exp++;
  506.         }
  507.       else
  508.         error (_("Target does not support \"/s\" option for string tracing."));
  509.     }
  510.   else
  511.     error (_("Undefined collection format \"%c\"."), *exp);

  512.   exp = skip_spaces_const (exp);

  513.   return exp;
  514. }

  515. /* Enter a list of actions for a tracepoint.  */
  516. static void
  517. trace_actions_command (char *args, int from_tty)
  518. {
  519.   struct tracepoint *t;
  520.   struct command_line *l;

  521.   t = get_tracepoint_by_number (&args, NULL);
  522.   if (t)
  523.     {
  524.       char *tmpbuf =
  525.         xstrprintf ("Enter actions for tracepoint %d, one per line.",
  526.                     t->base.number);
  527.       struct cleanup *cleanups = make_cleanup (xfree, tmpbuf);

  528.       l = read_command_lines (tmpbuf, from_tty, 1,
  529.                               check_tracepoint_command, t);
  530.       do_cleanups (cleanups);
  531.       breakpoint_set_commands (&t->base, l);
  532.     }
  533.   /* else just return */
  534. }

  535. /* Report the results of checking the agent expression, as errors or
  536.    internal errors.  */

  537. static void
  538. report_agent_reqs_errors (struct agent_expr *aexpr)
  539. {
  540.   /* All of the "flaws" are serious bytecode generation issues that
  541.      should never occur.  */
  542.   if (aexpr->flaw != agent_flaw_none)
  543.     internal_error (__FILE__, __LINE__, _("expression is malformed"));

  544.   /* If analysis shows a stack underflow, GDB must have done something
  545.      badly wrong in its bytecode generation.  */
  546.   if (aexpr->min_height < 0)
  547.     internal_error (__FILE__, __LINE__,
  548.                     _("expression has min height < 0"));

  549.   /* Issue this error if the stack is predicted to get too deep.  The
  550.      limit is rather arbitrary; a better scheme might be for the
  551.      target to report how much stack it will have available.  The
  552.      depth roughly corresponds to parenthesization, so a limit of 20
  553.      amounts to 20 levels of expression nesting, which is actually
  554.      a pretty big hairy expression.  */
  555.   if (aexpr->max_height > 20)
  556.     error (_("Expression is too complicated."));
  557. }

  558. /* worker function */
  559. void
  560. validate_actionline (const char *line, struct breakpoint *b)
  561. {
  562.   struct cmd_list_element *c;
  563.   struct expression *exp = NULL;
  564.   struct cleanup *old_chain = NULL;
  565.   const char *tmp_p;
  566.   const char *p;
  567.   struct bp_location *loc;
  568.   struct agent_expr *aexpr;
  569.   struct tracepoint *t = (struct tracepoint *) b;

  570.   /* If EOF is typed, *line is NULL.  */
  571.   if (line == NULL)
  572.     return;

  573.   p = skip_spaces_const (line);

  574.   /* Symbol lookup etc.  */
  575.   if (*p == '\0')        /* empty line: just prompt for another line.  */
  576.     return;

  577.   if (*p == '#')                /* comment line */
  578.     return;

  579.   c = lookup_cmd (&p, cmdlist, "", -1, 1);
  580.   if (c == 0)
  581.     error (_("`%s' is not a tracepoint action, or is ambiguous."), p);

  582.   if (cmd_cfunc_eq (c, collect_pseudocommand))
  583.     {
  584.       int trace_string = 0;

  585.       if (*p == '/')
  586.         p = decode_agent_options (p, &trace_string);

  587.       do
  588.         {                        /* Repeat over a comma-separated list.  */
  589.           QUIT;                        /* Allow user to bail out with ^C.  */
  590.           p = skip_spaces_const (p);

  591.           if (*p == '$')        /* Look for special pseudo-symbols.  */
  592.             {
  593.               if (0 == strncasecmp ("reg", p + 1, 3)
  594.                   || 0 == strncasecmp ("arg", p + 1, 3)
  595.                   || 0 == strncasecmp ("loc", p + 1, 3)
  596.                   || 0 == strncasecmp ("_ret", p + 1, 4)
  597.                   || 0 == strncasecmp ("_sdata", p + 1, 6))
  598.                 {
  599.                   p = strchr (p, ',');
  600.                   continue;
  601.                 }
  602.               /* else fall thru, treat p as an expression and parse it!  */
  603.             }
  604.           tmp_p = p;
  605.           for (loc = t->base.loc; loc; loc = loc->next)
  606.             {
  607.               p = tmp_p;
  608.               exp = parse_exp_1 (&p, loc->address,
  609.                                  block_for_pc (loc->address), 1);
  610.               old_chain = make_cleanup (free_current_contents, &exp);

  611.               if (exp->elts[0].opcode == OP_VAR_VALUE)
  612.                 {
  613.                   if (SYMBOL_CLASS (exp->elts[2].symbol) == LOC_CONST)
  614.                     {
  615.                       error (_("constant `%s' (value %s) "
  616.                                "will not be collected."),
  617.                              SYMBOL_PRINT_NAME (exp->elts[2].symbol),
  618.                              plongest (SYMBOL_VALUE (exp->elts[2].symbol)));
  619.                     }
  620.                   else if (SYMBOL_CLASS (exp->elts[2].symbol)
  621.                            == LOC_OPTIMIZED_OUT)
  622.                     {
  623.                       error (_("`%s' is optimized away "
  624.                                "and cannot be collected."),
  625.                              SYMBOL_PRINT_NAME (exp->elts[2].symbol));
  626.                     }
  627.                 }

  628.               /* We have something to collect, make sure that the expr to
  629.                  bytecode translator can handle it and that it's not too
  630.                  long.  */
  631.               aexpr = gen_trace_for_expr (loc->address, exp, trace_string);
  632.               make_cleanup_free_agent_expr (aexpr);

  633.               if (aexpr->len > MAX_AGENT_EXPR_LEN)
  634.                 error (_("Expression is too complicated."));

  635.               ax_reqs (aexpr);

  636.               report_agent_reqs_errors (aexpr);

  637.               do_cleanups (old_chain);
  638.             }
  639.         }
  640.       while (p && *p++ == ',');
  641.     }

  642.   else if (cmd_cfunc_eq (c, teval_pseudocommand))
  643.     {
  644.       do
  645.         {                        /* Repeat over a comma-separated list.  */
  646.           QUIT;                        /* Allow user to bail out with ^C.  */
  647.           p = skip_spaces_const (p);

  648.           tmp_p = p;
  649.           for (loc = t->base.loc; loc; loc = loc->next)
  650.             {
  651.               p = tmp_p;

  652.               /* Only expressions are allowed for this action.  */
  653.               exp = parse_exp_1 (&p, loc->address,
  654.                                  block_for_pc (loc->address), 1);
  655.               old_chain = make_cleanup (free_current_contents, &exp);

  656.               /* We have something to evaluate, make sure that the expr to
  657.                  bytecode translator can handle it and that it's not too
  658.                  long.  */
  659.               aexpr = gen_eval_for_expr (loc->address, exp);
  660.               make_cleanup_free_agent_expr (aexpr);

  661.               if (aexpr->len > MAX_AGENT_EXPR_LEN)
  662.                 error (_("Expression is too complicated."));

  663.               ax_reqs (aexpr);
  664.               report_agent_reqs_errors (aexpr);

  665.               do_cleanups (old_chain);
  666.             }
  667.         }
  668.       while (p && *p++ == ',');
  669.     }

  670.   else if (cmd_cfunc_eq (c, while_stepping_pseudocommand))
  671.     {
  672.       char *endp;

  673.       p = skip_spaces_const (p);
  674.       t->step_count = strtol (p, &endp, 0);
  675.       if (endp == p || t->step_count == 0)
  676.         error (_("while-stepping step count `%s' is malformed."), line);
  677.       p = endp;
  678.     }

  679.   else if (cmd_cfunc_eq (c, end_actions_pseudocommand))
  680.     ;

  681.   else
  682.     error (_("`%s' is not a supported tracepoint action."), line);
  683. }

  684. enum {
  685.   memrange_absolute = -1
  686. };

  687. /* MEMRANGE functions: */

  688. static int memrange_cmp (const void *, const void *);

  689. /* Compare memranges for qsort.  */
  690. static int
  691. memrange_cmp (const void *va, const void *vb)
  692. {
  693.   const struct memrange *a = va, *b = vb;

  694.   if (a->type < b->type)
  695.     return -1;
  696.   if (a->type > b->type)
  697.     return 1;
  698.   if (a->type == memrange_absolute)
  699.     {
  700.       if ((bfd_vma) a->start < (bfd_vma) b->start)
  701.         return -1;
  702.       if ((bfd_vma) a->start > (bfd_vma) b->start)
  703.         return 1;
  704.     }
  705.   else
  706.     {
  707.       if (a->start < b->start)
  708.         return -1;
  709.       if (a->start > b->start)
  710.         return 1;
  711.     }
  712.   return 0;
  713. }

  714. /* Sort the memrange list using qsort, and merge adjacent memranges.  */
  715. static void
  716. memrange_sortmerge (struct collection_list *memranges)
  717. {
  718.   int a, b;

  719.   qsort (memranges->list, memranges->next_memrange,
  720.          sizeof (struct memrange), memrange_cmp);
  721.   if (memranges->next_memrange > 0)
  722.     {
  723.       for (a = 0, b = 1; b < memranges->next_memrange; b++)
  724.         {
  725.           /* If memrange b overlaps or is adjacent to memrange a,
  726.              merge them.  */
  727.           if (memranges->list[a].type == memranges->list[b].type
  728.               && memranges->list[b].start <= memranges->list[a].end)
  729.             {
  730.               if (memranges->list[b].end > memranges->list[a].end)
  731.                 memranges->list[a].end = memranges->list[b].end;
  732.               continue;                /* next b, same a */
  733.             }
  734.           a++;                        /* next a */
  735.           if (a != b)
  736.             memcpy (&memranges->list[a], &memranges->list[b],
  737.                     sizeof (struct memrange));
  738.         }
  739.       memranges->next_memrange = a + 1;
  740.     }
  741. }

  742. /* Add a register to a collection list.  */
  743. static void
  744. add_register (struct collection_list *collection, unsigned int regno)
  745. {
  746.   if (info_verbose)
  747.     printf_filtered ("collect register %d\n", regno);
  748.   if (regno >= (8 * sizeof (collection->regs_mask)))
  749.     error (_("Internal: register number %d too large for tracepoint"),
  750.            regno);
  751.   collection->regs_mask[regno / 8] |= 1 << (regno % 8);
  752. }

  753. /* Add a memrange to a collection list.  */
  754. static void
  755. add_memrange (struct collection_list *memranges,
  756.               int type, bfd_signed_vma base,
  757.               unsigned long len)
  758. {
  759.   if (info_verbose)
  760.     {
  761.       printf_filtered ("(%d,", type);
  762.       printf_vma (base);
  763.       printf_filtered (",%ld)\n", len);
  764.     }

  765.   /* type: memrange_absolute == memory, other n == basereg */
  766.   memranges->list[memranges->next_memrange].type = type;
  767.   /* base: addr if memory, offset if reg relative.  */
  768.   memranges->list[memranges->next_memrange].start = base;
  769.   /* len: we actually save end (base + len) for convenience */
  770.   memranges->list[memranges->next_memrange].end = base + len;
  771.   memranges->next_memrange++;
  772.   if (memranges->next_memrange >= memranges->listsize)
  773.     {
  774.       memranges->listsize *= 2;
  775.       memranges->list = xrealloc (memranges->list,
  776.                                   memranges->listsize);
  777.     }

  778.   if (type != memrange_absolute)    /* Better collect the base register!  */
  779.     add_register (memranges, type);
  780. }

  781. /* Add a symbol to a collection list.  */
  782. static void
  783. collect_symbol (struct collection_list *collect,
  784.                 struct symbol *sym,
  785.                 struct gdbarch *gdbarch,
  786.                 long frame_regno, long frame_offset,
  787.                 CORE_ADDR scope,
  788.                 int trace_string)
  789. {
  790.   unsigned long len;
  791.   unsigned int reg;
  792.   bfd_signed_vma offset;
  793.   int treat_as_expr = 0;

  794.   len = TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym)));
  795.   switch (SYMBOL_CLASS (sym))
  796.     {
  797.     default:
  798.       printf_filtered ("%s: don't know symbol class %d\n",
  799.                        SYMBOL_PRINT_NAME (sym),
  800.                        SYMBOL_CLASS (sym));
  801.       break;
  802.     case LOC_CONST:
  803.       printf_filtered ("constant %s (value %s) will not be collected.\n",
  804.                        SYMBOL_PRINT_NAME (sym), plongest (SYMBOL_VALUE (sym)));
  805.       break;
  806.     case LOC_STATIC:
  807.       offset = SYMBOL_VALUE_ADDRESS (sym);
  808.       if (info_verbose)
  809.         {
  810.           char tmp[40];

  811.           sprintf_vma (tmp, offset);
  812.           printf_filtered ("LOC_STATIC %s: collect %ld bytes at %s.\n",
  813.                            SYMBOL_PRINT_NAME (sym), len,
  814.                            tmp /* address */);
  815.         }
  816.       /* A struct may be a C++ class with static fields, go to general
  817.          expression handling.  */
  818.       if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_STRUCT)
  819.         treat_as_expr = 1;
  820.       else
  821.         add_memrange (collect, memrange_absolute, offset, len);
  822.       break;
  823.     case LOC_REGISTER:
  824.       reg = SYMBOL_REGISTER_OPS (sym)->register_number (sym, gdbarch);
  825.       if (info_verbose)
  826.         printf_filtered ("LOC_REG[parm] %s: ",
  827.                          SYMBOL_PRINT_NAME (sym));
  828.       add_register (collect, reg);
  829.       /* Check for doubles stored in two registers.  */
  830.       /* FIXME: how about larger types stored in 3 or more regs?  */
  831.       if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_FLT &&
  832.           len > register_size (gdbarch, reg))
  833.         add_register (collect, reg + 1);
  834.       break;
  835.     case LOC_REF_ARG:
  836.       printf_filtered ("Sorry, don't know how to do LOC_REF_ARG yet.\n");
  837.       printf_filtered ("       (will not collect %s)\n",
  838.                        SYMBOL_PRINT_NAME (sym));
  839.       break;
  840.     case LOC_ARG:
  841.       reg = frame_regno;
  842.       offset = frame_offset + SYMBOL_VALUE (sym);
  843.       if (info_verbose)
  844.         {
  845.           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
  846.                            SYMBOL_PRINT_NAME (sym), len);
  847.           printf_vma (offset);
  848.           printf_filtered (" from frame ptr reg %d\n", reg);
  849.         }
  850.       add_memrange (collect, reg, offset, len);
  851.       break;
  852.     case LOC_REGPARM_ADDR:
  853.       reg = SYMBOL_VALUE (sym);
  854.       offset = 0;
  855.       if (info_verbose)
  856.         {
  857.           printf_filtered ("LOC_REGPARM_ADDR %s: Collect %ld bytes at offset ",
  858.                            SYMBOL_PRINT_NAME (sym), len);
  859.           printf_vma (offset);
  860.           printf_filtered (" from reg %d\n", reg);
  861.         }
  862.       add_memrange (collect, reg, offset, len);
  863.       break;
  864.     case LOC_LOCAL:
  865.       reg = frame_regno;
  866.       offset = frame_offset + SYMBOL_VALUE (sym);
  867.       if (info_verbose)
  868.         {
  869.           printf_filtered ("LOC_LOCAL %s: Collect %ld bytes at offset ",
  870.                            SYMBOL_PRINT_NAME (sym), len);
  871.           printf_vma (offset);
  872.           printf_filtered (" from frame ptr reg %d\n", reg);
  873.         }
  874.       add_memrange (collect, reg, offset, len);
  875.       break;

  876.     case LOC_UNRESOLVED:
  877.       treat_as_expr = 1;
  878.       break;

  879.     case LOC_OPTIMIZED_OUT:
  880.       printf_filtered ("%s has been optimized out of existence.\n",
  881.                        SYMBOL_PRINT_NAME (sym));
  882.       break;

  883.     case LOC_COMPUTED:
  884.       treat_as_expr = 1;
  885.       break;
  886.     }

  887.   /* Expressions are the most general case.  */
  888.   if (treat_as_expr)
  889.     {
  890.       struct agent_expr *aexpr;
  891.       struct cleanup *old_chain1 = NULL;

  892.       aexpr = gen_trace_for_var (scope, gdbarch, sym, trace_string);

  893.       /* It can happen that the symbol is recorded as a computed
  894.          location, but it's been optimized away and doesn't actually
  895.          have a location expression.  */
  896.       if (!aexpr)
  897.         {
  898.           printf_filtered ("%s has been optimized out of existence.\n",
  899.                            SYMBOL_PRINT_NAME (sym));
  900.           return;
  901.         }

  902.       old_chain1 = make_cleanup_free_agent_expr (aexpr);

  903.       ax_reqs (aexpr);

  904.       report_agent_reqs_errors (aexpr);

  905.       discard_cleanups (old_chain1);
  906.       add_aexpr (collect, aexpr);

  907.       /* Take care of the registers.  */
  908.       if (aexpr->reg_mask_len > 0)
  909.         {
  910.           int ndx1, ndx2;

  911.           for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
  912.             {
  913.               QUIT;        /* Allow user to bail out with ^C.  */
  914.               if (aexpr->reg_mask[ndx1] != 0)
  915.                 {
  916.                   /* Assume chars have 8 bits.  */
  917.                   for (ndx2 = 0; ndx2 < 8; ndx2++)
  918.                     if (aexpr->reg_mask[ndx1] & (1 << ndx2))
  919.                       /* It's used -- record it.  */
  920.                       add_register (collect, ndx1 * 8 + ndx2);
  921.                 }
  922.             }
  923.         }
  924.     }
  925. }

  926. /* Data to be passed around in the calls to the locals and args
  927.    iterators.  */

  928. struct add_local_symbols_data
  929. {
  930.   struct collection_list *collect;
  931.   struct gdbarch *gdbarch;
  932.   CORE_ADDR pc;
  933.   long frame_regno;
  934.   long frame_offset;
  935.   int count;
  936.   int trace_string;
  937. };

  938. /* The callback for the locals and args iterators.  */

  939. static void
  940. do_collect_symbol (const char *print_name,
  941.                    struct symbol *sym,
  942.                    void *cb_data)
  943. {
  944.   struct add_local_symbols_data *p = cb_data;

  945.   collect_symbol (p->collect, sym, p->gdbarch, p->frame_regno,
  946.                   p->frame_offset, p->pc, p->trace_string);
  947.   p->count++;

  948.   VEC_safe_push (char_ptr, p->collect->wholly_collected,
  949.                  xstrdup (print_name));
  950. }

  951. /* Add all locals (or args) symbols to collection list.  */
  952. static void
  953. add_local_symbols (struct collection_list *collect,
  954.                    struct gdbarch *gdbarch, CORE_ADDR pc,
  955.                    long frame_regno, long frame_offset, int type,
  956.                    int trace_string)
  957. {
  958.   const struct block *block;
  959.   struct add_local_symbols_data cb_data;

  960.   cb_data.collect = collect;
  961.   cb_data.gdbarch = gdbarch;
  962.   cb_data.pc = pc;
  963.   cb_data.frame_regno = frame_regno;
  964.   cb_data.frame_offset = frame_offset;
  965.   cb_data.count = 0;
  966.   cb_data.trace_string = trace_string;

  967.   if (type == 'L')
  968.     {
  969.       block = block_for_pc (pc);
  970.       if (block == NULL)
  971.         {
  972.           warning (_("Can't collect locals; "
  973.                      "no symbol table info available.\n"));
  974.           return;
  975.         }

  976.       iterate_over_block_local_vars (block, do_collect_symbol, &cb_data);
  977.       if (cb_data.count == 0)
  978.         warning (_("No locals found in scope."));
  979.     }
  980.   else
  981.     {
  982.       pc = get_pc_function_start (pc);
  983.       block = block_for_pc (pc);
  984.       if (block == NULL)
  985.         {
  986.           warning (_("Can't collect args; no symbol table info available."));
  987.           return;
  988.         }

  989.       iterate_over_block_arg_vars (block, do_collect_symbol, &cb_data);
  990.       if (cb_data.count == 0)
  991.         warning (_("No args found in scope."));
  992.     }
  993. }

  994. static void
  995. add_static_trace_data (struct collection_list *collection)
  996. {
  997.   if (info_verbose)
  998.     printf_filtered ("collect static trace data\n");
  999.   collection->strace_data = 1;
  1000. }

  1001. /* worker function */
  1002. static void
  1003. clear_collection_list (struct collection_list *list)
  1004. {
  1005.   int ndx;

  1006.   list->next_memrange = 0;
  1007.   for (ndx = 0; ndx < list->next_aexpr_elt; ndx++)
  1008.     {
  1009.       free_agent_expr (list->aexpr_list[ndx]);
  1010.       list->aexpr_list[ndx] = NULL;
  1011.     }
  1012.   list->next_aexpr_elt = 0;
  1013.   memset (list->regs_mask, 0, sizeof (list->regs_mask));
  1014.   list->strace_data = 0;

  1015.   xfree (list->aexpr_list);
  1016.   xfree (list->list);

  1017.   VEC_free (char_ptr, list->wholly_collected);
  1018.   VEC_free (char_ptr, list->computed);
  1019. }

  1020. /* A cleanup wrapper for function clear_collection_list.  */

  1021. static void
  1022. do_clear_collection_list (void *list)
  1023. {
  1024.   struct collection_list *l = list;

  1025.   clear_collection_list (l);
  1026. }

  1027. /* Initialize collection_list CLIST.  */

  1028. static void
  1029. init_collection_list (struct collection_list *clist)
  1030. {
  1031.   memset (clist, 0, sizeof *clist);

  1032.   clist->listsize = 128;
  1033.   clist->list = xcalloc (clist->listsize,
  1034.                          sizeof (struct memrange));

  1035.   clist->aexpr_listsize = 128;
  1036.   clist->aexpr_list = xcalloc (clist->aexpr_listsize,
  1037.                                sizeof (struct agent_expr *));
  1038. }

  1039. /* Reduce a collection list to string form (for gdb protocol).  */
  1040. static char **
  1041. stringify_collection_list (struct collection_list *list)
  1042. {
  1043.   char temp_buf[2048];
  1044.   char tmp2[40];
  1045.   int count;
  1046.   int ndx = 0;
  1047.   char *(*str_list)[];
  1048.   char *end;
  1049.   long i;

  1050.   count = 1 + 1 + list->next_memrange + list->next_aexpr_elt + 1;
  1051.   str_list = (char *(*)[]) xmalloc (count * sizeof (char *));

  1052.   if (list->strace_data)
  1053.     {
  1054.       if (info_verbose)
  1055.         printf_filtered ("\nCollecting static trace data\n");
  1056.       end = temp_buf;
  1057.       *end++ = 'L';
  1058.       (*str_list)[ndx] = savestring (temp_buf, end - temp_buf);
  1059.       ndx++;
  1060.     }

  1061.   for (i = sizeof (list->regs_mask) - 1; i > 0; i--)
  1062.     if (list->regs_mask[i] != 0)    /* Skip leading zeroes in regs_mask.  */
  1063.       break;
  1064.   if (list->regs_mask[i] != 0)        /* Prepare to send regs_mask to the stub.  */
  1065.     {
  1066.       if (info_verbose)
  1067.         printf_filtered ("\nCollecting registers (mask): 0x");
  1068.       end = temp_buf;
  1069.       *end++ = 'R';
  1070.       for (; i >= 0; i--)
  1071.         {
  1072.           QUIT;                        /* Allow user to bail out with ^C.  */
  1073.           if (info_verbose)
  1074.             printf_filtered ("%02X", list->regs_mask[i]);
  1075.           sprintf (end, "%02X", list->regs_mask[i]);
  1076.           end += 2;
  1077.         }
  1078.       (*str_list)[ndx] = xstrdup (temp_buf);
  1079.       ndx++;
  1080.     }
  1081.   if (info_verbose)
  1082.     printf_filtered ("\n");
  1083.   if (list->next_memrange > 0 && info_verbose)
  1084.     printf_filtered ("Collecting memranges: \n");
  1085.   for (i = 0, count = 0, end = temp_buf; i < list->next_memrange; i++)
  1086.     {
  1087.       QUIT;                        /* Allow user to bail out with ^C.  */
  1088.       sprintf_vma (tmp2, list->list[i].start);
  1089.       if (info_verbose)
  1090.         {
  1091.           printf_filtered ("(%d, %s, %ld)\n",
  1092.                            list->list[i].type,
  1093.                            tmp2,
  1094.                            (long) (list->list[i].end - list->list[i].start));
  1095.         }
  1096.       if (count + 27 > MAX_AGENT_EXPR_LEN)
  1097.         {
  1098.           (*str_list)[ndx] = savestring (temp_buf, count);
  1099.           ndx++;
  1100.           count = 0;
  1101.           end = temp_buf;
  1102.         }

  1103.       {
  1104.         bfd_signed_vma length = list->list[i].end - list->list[i].start;

  1105.         /* The "%X" conversion specifier expects an unsigned argument,
  1106.            so passing -1 (memrange_absolute) to it directly gives you
  1107.            "FFFFFFFF" (or more, depending on sizeof (unsigned)).
  1108.            Special-case it.  */
  1109.         if (list->list[i].type == memrange_absolute)
  1110.           sprintf (end, "M-1,%s,%lX", tmp2, (long) length);
  1111.         else
  1112.           sprintf (end, "M%X,%s,%lX", list->list[i].type, tmp2, (long) length);
  1113.       }

  1114.       count += strlen (end);
  1115.       end = temp_buf + count;
  1116.     }

  1117.   for (i = 0; i < list->next_aexpr_elt; i++)
  1118.     {
  1119.       QUIT;                        /* Allow user to bail out with ^C.  */
  1120.       if ((count + 10 + 2 * list->aexpr_list[i]->len) > MAX_AGENT_EXPR_LEN)
  1121.         {
  1122.           (*str_list)[ndx] = savestring (temp_buf, count);
  1123.           ndx++;
  1124.           count = 0;
  1125.           end = temp_buf;
  1126.         }
  1127.       sprintf (end, "X%08X,", list->aexpr_list[i]->len);
  1128.       end += 10;                /* 'X' + 8 hex digits + ',' */
  1129.       count += 10;

  1130.       end = mem2hex (list->aexpr_list[i]->buf,
  1131.                      end, list->aexpr_list[i]->len);
  1132.       count += 2 * list->aexpr_list[i]->len;
  1133.     }

  1134.   if (count != 0)
  1135.     {
  1136.       (*str_list)[ndx] = savestring (temp_buf, count);
  1137.       ndx++;
  1138.       count = 0;
  1139.       end = temp_buf;
  1140.     }
  1141.   (*str_list)[ndx] = NULL;

  1142.   if (ndx == 0)
  1143.     {
  1144.       xfree (str_list);
  1145.       return NULL;
  1146.     }
  1147.   else
  1148.     return *str_list;
  1149. }

  1150. /* Add the printed expression EXP to *LIST.  */

  1151. static void
  1152. append_exp (struct expression *exp, VEC(char_ptr) **list)
  1153. {
  1154.   struct ui_file *tmp_stream = mem_fileopen ();
  1155.   char *text;

  1156.   print_expression (exp, tmp_stream);

  1157.   text = ui_file_xstrdup (tmp_stream, NULL);

  1158.   VEC_safe_push (char_ptr, *list, text);
  1159.   ui_file_delete (tmp_stream);
  1160. }

  1161. static void
  1162. encode_actions_1 (struct command_line *action,
  1163.                   struct bp_location *tloc,
  1164.                   int frame_reg,
  1165.                   LONGEST frame_offset,
  1166.                   struct collection_list *collect,
  1167.                   struct collection_list *stepping_list)
  1168. {
  1169.   const char *action_exp;
  1170.   struct expression *exp = NULL;
  1171.   int i;
  1172.   struct value *tempval;
  1173.   struct cmd_list_element *cmd;
  1174.   struct agent_expr *aexpr;

  1175.   for (; action; action = action->next)
  1176.     {
  1177.       QUIT;                        /* Allow user to bail out with ^C.  */
  1178.       action_exp = action->line;
  1179.       action_exp = skip_spaces_const (action_exp);

  1180.       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
  1181.       if (cmd == 0)
  1182.         error (_("Bad action list item: %s"), action_exp);

  1183.       if (cmd_cfunc_eq (cmd, collect_pseudocommand))
  1184.         {
  1185.           int trace_string = 0;

  1186.           if (*action_exp == '/')
  1187.             action_exp = decode_agent_options (action_exp, &trace_string);

  1188.           do
  1189.             {                        /* Repeat over a comma-separated list.  */
  1190.               QUIT;                /* Allow user to bail out with ^C.  */
  1191.               action_exp = skip_spaces_const (action_exp);

  1192.               if (0 == strncasecmp ("$reg", action_exp, 4))
  1193.                 {
  1194.                   for (i = 0; i < gdbarch_num_regs (tloc->gdbarch); i++)
  1195.                     add_register (collect, i);
  1196.                   action_exp = strchr (action_exp, ',');        /* more? */
  1197.                 }
  1198.               else if (0 == strncasecmp ("$arg", action_exp, 4))
  1199.                 {
  1200.                   add_local_symbols (collect,
  1201.                                      tloc->gdbarch,
  1202.                                      tloc->address,
  1203.                                      frame_reg,
  1204.                                      frame_offset,
  1205.                                      'A',
  1206.                                      trace_string);
  1207.                   action_exp = strchr (action_exp, ',');        /* more? */
  1208.                 }
  1209.               else if (0 == strncasecmp ("$loc", action_exp, 4))
  1210.                 {
  1211.                   add_local_symbols (collect,
  1212.                                      tloc->gdbarch,
  1213.                                      tloc->address,
  1214.                                      frame_reg,
  1215.                                      frame_offset,
  1216.                                      'L',
  1217.                                      trace_string);
  1218.                   action_exp = strchr (action_exp, ',');        /* more? */
  1219.                 }
  1220.               else if (0 == strncasecmp ("$_ret", action_exp, 5))
  1221.                 {
  1222.                   struct cleanup *old_chain1 = NULL;

  1223.                   aexpr = gen_trace_for_return_address (tloc->address,
  1224.                                                         tloc->gdbarch,
  1225.                                                         trace_string);

  1226.                   old_chain1 = make_cleanup_free_agent_expr (aexpr);

  1227.                   ax_reqs (aexpr);
  1228.                   report_agent_reqs_errors (aexpr);

  1229.                   discard_cleanups (old_chain1);
  1230.                   add_aexpr (collect, aexpr);

  1231.                   /* take care of the registers */
  1232.                   if (aexpr->reg_mask_len > 0)
  1233.                     {
  1234.                       int ndx1, ndx2;

  1235.                       for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
  1236.                         {
  1237.                           QUIT;        /* allow user to bail out with ^C */
  1238.                           if (aexpr->reg_mask[ndx1] != 0)
  1239.                             {
  1240.                               /* assume chars have 8 bits */
  1241.                               for (ndx2 = 0; ndx2 < 8; ndx2++)
  1242.                                 if (aexpr->reg_mask[ndx1] & (1 << ndx2))
  1243.                                   /* it's used -- record it */
  1244.                                   add_register (collect,
  1245.                                                 ndx1 * 8 + ndx2);
  1246.                             }
  1247.                         }
  1248.                     }

  1249.                   action_exp = strchr (action_exp, ',');        /* more? */
  1250.                 }
  1251.               else if (0 == strncasecmp ("$_sdata", action_exp, 7))
  1252.                 {
  1253.                   add_static_trace_data (collect);
  1254.                   action_exp = strchr (action_exp, ',');        /* more? */
  1255.                 }
  1256.               else
  1257.                 {
  1258.                   unsigned long addr;
  1259.                   struct cleanup *old_chain = NULL;
  1260.                   struct cleanup *old_chain1 = NULL;

  1261.                   exp = parse_exp_1 (&action_exp, tloc->address,
  1262.                                      block_for_pc (tloc->address), 1);
  1263.                   old_chain = make_cleanup (free_current_contents, &exp);

  1264.                   switch (exp->elts[0].opcode)
  1265.                     {
  1266.                     case OP_REGISTER:
  1267.                       {
  1268.                         const char *name = &exp->elts[2].string;

  1269.                         i = user_reg_map_name_to_regnum (tloc->gdbarch,
  1270.                                                          name, strlen (name));
  1271.                         if (i == -1)
  1272.                           internal_error (__FILE__, __LINE__,
  1273.                                           _("Register $%s not available"),
  1274.                                           name);
  1275.                         if (info_verbose)
  1276.                           printf_filtered ("OP_REGISTER: ");
  1277.                         add_register (collect, i);
  1278.                         break;
  1279.                       }

  1280.                     case UNOP_MEMVAL:
  1281.                       /* Safe because we know it's a simple expression.  */
  1282.                       tempval = evaluate_expression (exp);
  1283.                       addr = value_address (tempval);
  1284.                       /* Initialize the TYPE_LENGTH if it is a typedef.  */
  1285.                       check_typedef (exp->elts[1].type);
  1286.                       add_memrange (collect, memrange_absolute, addr,
  1287.                                     TYPE_LENGTH (exp->elts[1].type));
  1288.                       append_exp (exp, &collect->computed);
  1289.                       break;

  1290.                     case OP_VAR_VALUE:
  1291.                       {
  1292.                         struct symbol *sym = exp->elts[2].symbol;
  1293.                         char_ptr name = (char_ptr) SYMBOL_NATURAL_NAME (sym);

  1294.                         collect_symbol (collect,
  1295.                                         exp->elts[2].symbol,
  1296.                                         tloc->gdbarch,
  1297.                                         frame_reg,
  1298.                                         frame_offset,
  1299.                                         tloc->address,
  1300.                                         trace_string);
  1301.                         VEC_safe_push (char_ptr,
  1302.                                        collect->wholly_collected,
  1303.                                        name);
  1304.                       }
  1305.                       break;

  1306.                     default:        /* Full-fledged expression.  */
  1307.                       aexpr = gen_trace_for_expr (tloc->address, exp,
  1308.                                                   trace_string);

  1309.                       old_chain1 = make_cleanup_free_agent_expr (aexpr);

  1310.                       ax_reqs (aexpr);

  1311.                       report_agent_reqs_errors (aexpr);

  1312.                       discard_cleanups (old_chain1);
  1313.                       add_aexpr (collect, aexpr);

  1314.                       /* Take care of the registers.  */
  1315.                       if (aexpr->reg_mask_len > 0)
  1316.                         {
  1317.                           int ndx1;
  1318.                           int ndx2;

  1319.                           for (ndx1 = 0; ndx1 < aexpr->reg_mask_len; ndx1++)
  1320.                             {
  1321.                               QUIT;        /* Allow user to bail out with ^C.  */
  1322.                               if (aexpr->reg_mask[ndx1] != 0)
  1323.                                 {
  1324.                                   /* Assume chars have 8 bits.  */
  1325.                                   for (ndx2 = 0; ndx2 < 8; ndx2++)
  1326.                                     if (aexpr->reg_mask[ndx1] & (1 << ndx2))
  1327.                                       /* It's used -- record it.  */
  1328.                                       add_register (collect,
  1329.                                                     ndx1 * 8 + ndx2);
  1330.                                 }
  1331.                             }
  1332.                         }

  1333.                       append_exp (exp, &collect->computed);
  1334.                       break;
  1335.                     }                /* switch */
  1336.                   do_cleanups (old_chain);
  1337.                 }                /* do */
  1338.             }
  1339.           while (action_exp && *action_exp++ == ',');
  1340.         }                        /* if */
  1341.       else if (cmd_cfunc_eq (cmd, teval_pseudocommand))
  1342.         {
  1343.           do
  1344.             {                        /* Repeat over a comma-separated list.  */
  1345.               QUIT;                /* Allow user to bail out with ^C.  */
  1346.               action_exp = skip_spaces_const (action_exp);

  1347.                 {
  1348.                   struct cleanup *old_chain = NULL;
  1349.                   struct cleanup *old_chain1 = NULL;

  1350.                   exp = parse_exp_1 (&action_exp, tloc->address,
  1351.                                      block_for_pc (tloc->address), 1);
  1352.                   old_chain = make_cleanup (free_current_contents, &exp);

  1353.                   aexpr = gen_eval_for_expr (tloc->address, exp);
  1354.                   old_chain1 = make_cleanup_free_agent_expr (aexpr);

  1355.                   ax_reqs (aexpr);
  1356.                   report_agent_reqs_errors (aexpr);

  1357.                   discard_cleanups (old_chain1);
  1358.                   /* Even though we're not officially collecting, add
  1359.                      to the collect list anyway.  */
  1360.                   add_aexpr (collect, aexpr);

  1361.                   do_cleanups (old_chain);
  1362.                 }                /* do */
  1363.             }
  1364.           while (action_exp && *action_exp++ == ',');
  1365.         }                        /* if */
  1366.       else if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
  1367.         {
  1368.           /* We check against nested while-stepping when setting
  1369.              breakpoint action, so no way to run into nested
  1370.              here.  */
  1371.           gdb_assert (stepping_list);

  1372.           encode_actions_1 (action->body_list[0], tloc, frame_reg,
  1373.                             frame_offset, stepping_list, NULL);
  1374.         }
  1375.       else
  1376.         error (_("Invalid tracepoint command '%s'"), action->line);
  1377.     }                                /* for */
  1378. }

  1379. /* Encode actions of tracepoint TLOC->owner and fill TRACEPOINT_LIST
  1380.    and STEPPING_LIST.  Return a cleanup pointer to clean up both
  1381.    TRACEPOINT_LIST and STEPPING_LIST.  */

  1382. struct cleanup *
  1383. encode_actions_and_make_cleanup (struct bp_location *tloc,
  1384.                                  struct collection_list *tracepoint_list,
  1385.                                  struct collection_list *stepping_list)
  1386. {
  1387.   char *default_collect_line = NULL;
  1388.   struct command_line *actions;
  1389.   struct command_line *default_collect_action = NULL;
  1390.   int frame_reg;
  1391.   LONGEST frame_offset;
  1392.   struct cleanup *back_to, *return_chain;

  1393.   return_chain = make_cleanup (null_cleanup, NULL);
  1394.   init_collection_list (tracepoint_list);
  1395.   init_collection_list (stepping_list);

  1396.   make_cleanup (do_clear_collection_list, tracepoint_list);
  1397.   make_cleanup (do_clear_collection_list, stepping_list);

  1398.   back_to = make_cleanup (null_cleanup, NULL);
  1399.   gdbarch_virtual_frame_pointer (tloc->gdbarch,
  1400.                                  tloc->address, &frame_reg, &frame_offset);

  1401.   actions = all_tracepoint_actions_and_cleanup (tloc->owner);

  1402.   encode_actions_1 (actions, tloc, frame_reg, frame_offset,
  1403.                     tracepoint_list, stepping_list);

  1404.   memrange_sortmerge (tracepoint_list);
  1405.   memrange_sortmerge (stepping_list);

  1406.   do_cleanups (back_to);
  1407.   return return_chain;
  1408. }

  1409. /* Render all actions into gdb protocol.  */

  1410. void
  1411. encode_actions_rsp (struct bp_location *tloc, char ***tdp_actions,
  1412.                     char ***stepping_actions)
  1413. {
  1414.   struct collection_list tracepoint_list, stepping_list;
  1415.   struct cleanup *cleanup;

  1416.   *tdp_actions = NULL;
  1417.   *stepping_actions = NULL;

  1418.   cleanup = encode_actions_and_make_cleanup (tloc, &tracepoint_list,
  1419.                                              &stepping_list);

  1420.   *tdp_actions = stringify_collection_list (&tracepoint_list);
  1421.   *stepping_actions = stringify_collection_list (&stepping_list);

  1422.   do_cleanups (cleanup);
  1423. }

  1424. static void
  1425. add_aexpr (struct collection_list *collect, struct agent_expr *aexpr)
  1426. {
  1427.   if (collect->next_aexpr_elt >= collect->aexpr_listsize)
  1428.     {
  1429.       collect->aexpr_list =
  1430.         xrealloc (collect->aexpr_list,
  1431.                   2 * collect->aexpr_listsize * sizeof (struct agent_expr *));
  1432.       collect->aexpr_listsize *= 2;
  1433.     }
  1434.   collect->aexpr_list[collect->next_aexpr_elt] = aexpr;
  1435.   collect->next_aexpr_elt++;
  1436. }

  1437. static void
  1438. process_tracepoint_on_disconnect (void)
  1439. {
  1440.   VEC(breakpoint_p) *tp_vec = NULL;
  1441.   int ix;
  1442.   struct breakpoint *b;
  1443.   int has_pending_p = 0;

  1444.   /* Check whether we still have pending tracepoint.  If we have, warn the
  1445.      user that pending tracepoint will no longer work.  */
  1446.   tp_vec = all_tracepoints ();
  1447.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
  1448.     {
  1449.       if (b->loc == NULL)
  1450.         {
  1451.           has_pending_p = 1;
  1452.           break;
  1453.         }
  1454.       else
  1455.         {
  1456.           struct bp_location *loc1;

  1457.           for (loc1 = b->loc; loc1; loc1 = loc1->next)
  1458.             {
  1459.               if (loc1->shlib_disabled)
  1460.                 {
  1461.                   has_pending_p = 1;
  1462.                   break;
  1463.                 }
  1464.             }

  1465.           if (has_pending_p)
  1466.             break;
  1467.         }
  1468.     }
  1469.   VEC_free (breakpoint_p, tp_vec);

  1470.   if (has_pending_p)
  1471.     warning (_("Pending tracepoints will not be resolved while"
  1472.                " GDB is disconnected\n"));
  1473. }

  1474. /* Reset local state of tracing.  */

  1475. void
  1476. trace_reset_local_state (void)
  1477. {
  1478.   set_traceframe_num (-1);
  1479.   set_tracepoint_num (-1);
  1480.   set_traceframe_context (NULL);
  1481.   clear_traceframe_info ();
  1482. }

  1483. void
  1484. start_tracing (char *notes)
  1485. {
  1486.   VEC(breakpoint_p) *tp_vec = NULL;
  1487.   int ix;
  1488.   struct breakpoint *b;
  1489.   struct trace_state_variable *tsv;
  1490.   int any_enabled = 0, num_to_download = 0;
  1491.   int ret;

  1492.   tp_vec = all_tracepoints ();

  1493.   /* No point in tracing without any tracepoints...  */
  1494.   if (VEC_length (breakpoint_p, tp_vec) == 0)
  1495.     {
  1496.       VEC_free (breakpoint_p, tp_vec);
  1497.       error (_("No tracepoints defined, not starting trace"));
  1498.     }

  1499.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
  1500.     {
  1501.       struct tracepoint *t = (struct tracepoint *) b;
  1502.       struct bp_location *loc;

  1503.       if (b->enable_state == bp_enabled)
  1504.         any_enabled = 1;

  1505.       if ((b->type == bp_fast_tracepoint
  1506.            ? may_insert_fast_tracepoints
  1507.            : may_insert_tracepoints))
  1508.         ++num_to_download;
  1509.       else
  1510.         warning (_("May not insert %stracepoints, skipping tracepoint %d"),
  1511.                  (b->type == bp_fast_tracepoint ? "fast " : ""), b->number);
  1512.     }

  1513.   if (!any_enabled)
  1514.     {
  1515.       if (target_supports_enable_disable_tracepoint ())
  1516.         warning (_("No tracepoints enabled"));
  1517.       else
  1518.         {
  1519.           /* No point in tracing with only disabled tracepoints that
  1520.              cannot be re-enabled.  */
  1521.           VEC_free (breakpoint_p, tp_vec);
  1522.           error (_("No tracepoints enabled, not starting trace"));
  1523.         }
  1524.     }

  1525.   if (num_to_download <= 0)
  1526.     {
  1527.       VEC_free (breakpoint_p, tp_vec);
  1528.       error (_("No tracepoints that may be downloaded, not starting trace"));
  1529.     }

  1530.   target_trace_init ();

  1531.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
  1532.     {
  1533.       struct tracepoint *t = (struct tracepoint *) b;
  1534.       struct bp_location *loc;
  1535.       int bp_location_downloaded = 0;

  1536.       /* Clear `inserted' flag.  */
  1537.       for (loc = b->loc; loc; loc = loc->next)
  1538.         loc->inserted = 0;

  1539.       if ((b->type == bp_fast_tracepoint
  1540.            ? !may_insert_fast_tracepoints
  1541.            : !may_insert_tracepoints))
  1542.         continue;

  1543.       t->number_on_target = 0;

  1544.       for (loc = b->loc; loc; loc = loc->next)
  1545.         {
  1546.           /* Since tracepoint locations are never duplicated, `inserted'
  1547.              flag should be zero.  */
  1548.           gdb_assert (!loc->inserted);

  1549.           target_download_tracepoint (loc);

  1550.           loc->inserted = 1;
  1551.           bp_location_downloaded = 1;
  1552.         }

  1553.       t->number_on_target = b->number;

  1554.       for (loc = b->loc; loc; loc = loc->next)
  1555.         if (loc->probe.probe != NULL
  1556.             && loc->probe.probe->pops->set_semaphore != NULL)
  1557.           loc->probe.probe->pops->set_semaphore (loc->probe.probe,
  1558.                                                  loc->probe.objfile,
  1559.                                                  loc->gdbarch);

  1560.       if (bp_location_downloaded)
  1561.         observer_notify_breakpoint_modified (b);
  1562.     }
  1563.   VEC_free (breakpoint_p, tp_vec);

  1564.   /* Send down all the trace state variables too.  */
  1565.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  1566.     {
  1567.       target_download_trace_state_variable (tsv);
  1568.     }

  1569.   /* Tell target to treat text-like sections as transparent.  */
  1570.   target_trace_set_readonly_regions ();
  1571.   /* Set some mode flags.  */
  1572.   target_set_disconnected_tracing (disconnected_tracing);
  1573.   target_set_circular_trace_buffer (circular_trace_buffer);
  1574.   target_set_trace_buffer_size (trace_buffer_size);

  1575.   if (!notes)
  1576.     notes = trace_notes;
  1577.   ret = target_set_trace_notes (trace_user, notes, NULL);

  1578.   if (!ret && (trace_user || notes))
  1579.     warning (_("Target does not support trace user/notes, info ignored"));

  1580.   /* Now insert traps and begin collecting data.  */
  1581.   target_trace_start ();

  1582.   /* Reset our local state.  */
  1583.   trace_reset_local_state ();
  1584.   current_trace_status()->running = 1;
  1585. }

  1586. /* The tstart command requests the target to start a new trace run.
  1587.    The command passes any arguments it has to the target verbatim, as
  1588.    an optional "trace note".  This is useful as for instance a warning
  1589.    to other users if the trace runs disconnected, and you don't want
  1590.    anybody else messing with the target.  */

  1591. static void
  1592. trace_start_command (char *args, int from_tty)
  1593. {
  1594.   dont_repeat ();        /* Like "run", dangerous to repeat accidentally.  */

  1595.   if (current_trace_status ()->running)
  1596.     {
  1597.       if (from_tty
  1598.           && !query (_("A trace is running already.  Start a new run? ")))
  1599.         error (_("New trace run not started."));
  1600.     }

  1601.   start_tracing (args);
  1602. }

  1603. /* The tstop command stops the tracing run.  The command passes any
  1604.    supplied arguments to the target verbatim as a "stop note"; if the
  1605.    target supports trace notes, then it will be reported back as part
  1606.    of the trace run's status.  */

  1607. static void
  1608. trace_stop_command (char *args, int from_tty)
  1609. {
  1610.   if (!current_trace_status ()->running)
  1611.     error (_("Trace is not running."));

  1612.   stop_tracing (args);
  1613. }

  1614. void
  1615. stop_tracing (char *note)
  1616. {
  1617.   int ret;
  1618.   VEC(breakpoint_p) *tp_vec = NULL;
  1619.   int ix;
  1620.   struct breakpoint *t;

  1621.   target_trace_stop ();

  1622.   tp_vec = all_tracepoints ();
  1623.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, t); ix++)
  1624.     {
  1625.       struct bp_location *loc;

  1626.       if ((t->type == bp_fast_tracepoint
  1627.            ? !may_insert_fast_tracepoints
  1628.            : !may_insert_tracepoints))
  1629.         continue;

  1630.       for (loc = t->loc; loc; loc = loc->next)
  1631.         {
  1632.           /* GDB can be totally absent in some disconnected trace scenarios,
  1633.              but we don't really care if this semaphore goes out of sync.
  1634.              That's why we are decrementing it here, but not taking care
  1635.              in other places.  */
  1636.           if (loc->probe.probe != NULL
  1637.               && loc->probe.probe->pops->clear_semaphore != NULL)
  1638.             loc->probe.probe->pops->clear_semaphore (loc->probe.probe,
  1639.                                                      loc->probe.objfile,
  1640.                                                      loc->gdbarch);
  1641.         }
  1642.     }

  1643.   VEC_free (breakpoint_p, tp_vec);

  1644.   if (!note)
  1645.     note = trace_stop_notes;
  1646.   ret = target_set_trace_notes (NULL, NULL, note);

  1647.   if (!ret && note)
  1648.     warning (_("Target does not support trace notes, note ignored"));

  1649.   /* Should change in response to reply?  */
  1650.   current_trace_status ()->running = 0;
  1651. }

  1652. /* tstatus command */
  1653. static void
  1654. trace_status_command (char *args, int from_tty)
  1655. {
  1656.   struct trace_status *ts = current_trace_status ();
  1657.   int status, ix;
  1658.   VEC(breakpoint_p) *tp_vec = NULL;
  1659.   struct breakpoint *t;

  1660.   status = target_get_trace_status (ts);

  1661.   if (status == -1)
  1662.     {
  1663.       if (ts->filename != NULL)
  1664.         printf_filtered (_("Using a trace file.\n"));
  1665.       else
  1666.         {
  1667.           printf_filtered (_("Trace can not be run on this target.\n"));
  1668.           return;
  1669.         }
  1670.     }

  1671.   if (!ts->running_known)
  1672.     {
  1673.       printf_filtered (_("Run/stop status is unknown.\n"));
  1674.     }
  1675.   else if (ts->running)
  1676.     {
  1677.       printf_filtered (_("Trace is running on the target.\n"));
  1678.     }
  1679.   else
  1680.     {
  1681.       switch (ts->stop_reason)
  1682.         {
  1683.         case trace_never_run:
  1684.           printf_filtered (_("No trace has been run on the target.\n"));
  1685.           break;
  1686.         case tstop_command:
  1687.           if (ts->stop_desc)
  1688.             printf_filtered (_("Trace stopped by a tstop command (%s).\n"),
  1689.                              ts->stop_desc);
  1690.           else
  1691.             printf_filtered (_("Trace stopped by a tstop command.\n"));
  1692.           break;
  1693.         case trace_buffer_full:
  1694.           printf_filtered (_("Trace stopped because the buffer was full.\n"));
  1695.           break;
  1696.         case trace_disconnected:
  1697.           printf_filtered (_("Trace stopped because of disconnection.\n"));
  1698.           break;
  1699.         case tracepoint_passcount:
  1700.           printf_filtered (_("Trace stopped by tracepoint %d.\n"),
  1701.                            ts->stopping_tracepoint);
  1702.           break;
  1703.         case tracepoint_error:
  1704.           if (ts->stopping_tracepoint)
  1705.             printf_filtered (_("Trace stopped by an "
  1706.                                "error (%s, tracepoint %d).\n"),
  1707.                              ts->stop_desc, ts->stopping_tracepoint);
  1708.           else
  1709.             printf_filtered (_("Trace stopped by an error (%s).\n"),
  1710.                              ts->stop_desc);
  1711.           break;
  1712.         case trace_stop_reason_unknown:
  1713.           printf_filtered (_("Trace stopped for an unknown reason.\n"));
  1714.           break;
  1715.         default:
  1716.           printf_filtered (_("Trace stopped for some other reason (%d).\n"),
  1717.                            ts->stop_reason);
  1718.           break;
  1719.         }
  1720.     }

  1721.   if (ts->traceframes_created >= 0
  1722.       && ts->traceframe_count != ts->traceframes_created)
  1723.     {
  1724.       printf_filtered (_("Buffer contains %d trace "
  1725.                          "frames (of %d created total).\n"),
  1726.                        ts->traceframe_count, ts->traceframes_created);
  1727.     }
  1728.   else if (ts->traceframe_count >= 0)
  1729.     {
  1730.       printf_filtered (_("Collected %d trace frames.\n"),
  1731.                        ts->traceframe_count);
  1732.     }

  1733.   if (ts->buffer_free >= 0)
  1734.     {
  1735.       if (ts->buffer_size >= 0)
  1736.         {
  1737.           printf_filtered (_("Trace buffer has %d bytes of %d bytes free"),
  1738.                            ts->buffer_free, ts->buffer_size);
  1739.           if (ts->buffer_size > 0)
  1740.             printf_filtered (_(" (%d%% full)"),
  1741.                              ((int) ((((long long) (ts->buffer_size
  1742.                                                     - ts->buffer_free)) * 100)
  1743.                                      / ts->buffer_size)));
  1744.           printf_filtered (_(".\n"));
  1745.         }
  1746.       else
  1747.         printf_filtered (_("Trace buffer has %d bytes free.\n"),
  1748.                          ts->buffer_free);
  1749.     }

  1750.   if (ts->disconnected_tracing)
  1751.     printf_filtered (_("Trace will continue if GDB disconnects.\n"));
  1752.   else
  1753.     printf_filtered (_("Trace will stop if GDB disconnects.\n"));

  1754.   if (ts->circular_buffer)
  1755.     printf_filtered (_("Trace buffer is circular.\n"));

  1756.   if (ts->user_name && strlen (ts->user_name) > 0)
  1757.     printf_filtered (_("Trace user is %s.\n"), ts->user_name);

  1758.   if (ts->notes && strlen (ts->notes) > 0)
  1759.     printf_filtered (_("Trace notes: %s.\n"), ts->notes);

  1760.   /* Now report on what we're doing with tfind.  */
  1761.   if (traceframe_number >= 0)
  1762.     printf_filtered (_("Looking at trace frame %d, tracepoint %d.\n"),
  1763.                      traceframe_number, tracepoint_number);
  1764.   else
  1765.     printf_filtered (_("Not looking at any trace frame.\n"));

  1766.   /* Report start/stop times if supplied.  */
  1767.   if (ts->start_time)
  1768.     {
  1769.       if (ts->stop_time)
  1770.         {
  1771.           LONGEST run_time = ts->stop_time - ts->start_time;

  1772.           /* Reporting a run time is more readable than two long numbers.  */
  1773.           printf_filtered (_("Trace started at %ld.%06ld secs, stopped %ld.%06ld secs later.\n"),
  1774.                            (long int) (ts->start_time / 1000000),
  1775.                            (long int) (ts->start_time % 1000000),
  1776.                            (long int) (run_time / 1000000),
  1777.                            (long int) (run_time % 1000000));
  1778.         }
  1779.       else
  1780.         printf_filtered (_("Trace started at %ld.%06ld secs.\n"),
  1781.                          (long int) (ts->start_time / 1000000),
  1782.                          (long int) (ts->start_time % 1000000));
  1783.     }
  1784.   else if (ts->stop_time)
  1785.     printf_filtered (_("Trace stopped at %ld.%06ld secs.\n"),
  1786.                      (long int) (ts->stop_time / 1000000),
  1787.                      (long int) (ts->stop_time % 1000000));

  1788.   /* Now report any per-tracepoint status available.  */
  1789.   tp_vec = all_tracepoints ();

  1790.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, t); ix++)
  1791.     target_get_tracepoint_status (t, NULL);

  1792.   VEC_free (breakpoint_p, tp_vec);
  1793. }

  1794. /* Report the trace status to uiout, in a way suitable for MI, and not
  1795.    suitable for CLI.  If ON_STOP is true, suppress a few fields that
  1796.    are not meaningful in the -trace-stop response.

  1797.    The implementation is essentially parallel to trace_status_command, but
  1798.    merging them will result in unreadable code.  */
  1799. void
  1800. trace_status_mi (int on_stop)
  1801. {
  1802.   struct ui_out *uiout = current_uiout;
  1803.   struct trace_status *ts = current_trace_status ();
  1804.   int status;

  1805.   status = target_get_trace_status (ts);

  1806.   if (status == -1 && ts->filename == NULL)
  1807.     {
  1808.       ui_out_field_string (uiout, "supported", "0");
  1809.       return;
  1810.     }

  1811.   if (ts->filename != NULL)
  1812.     ui_out_field_string (uiout, "supported", "file");
  1813.   else if (!on_stop)
  1814.     ui_out_field_string (uiout, "supported", "1");

  1815.   if (ts->filename != NULL)
  1816.     ui_out_field_string (uiout, "trace-file", ts->filename);

  1817.   gdb_assert (ts->running_known);

  1818.   if (ts->running)
  1819.     {
  1820.       ui_out_field_string (uiout, "running", "1");

  1821.       /* Unlike CLI, do not show the state of 'disconnected-tracing' variable.
  1822.          Given that the frontend gets the status either on -trace-stop, or from
  1823.          -trace-status after re-connection, it does not seem like this
  1824.          information is necessary for anything.  It is not necessary for either
  1825.          figuring the vital state of the target nor for navigation of trace
  1826.          frames.  If the frontend wants to show the current state is some
  1827.          configure dialog, it can request the value when such dialog is
  1828.          invoked by the user.  */
  1829.     }
  1830.   else
  1831.     {
  1832.       char *stop_reason = NULL;
  1833.       int stopping_tracepoint = -1;

  1834.       if (!on_stop)
  1835.         ui_out_field_string (uiout, "running", "0");

  1836.       if (ts->stop_reason != trace_stop_reason_unknown)
  1837.         {
  1838.           switch (ts->stop_reason)
  1839.             {
  1840.             case tstop_command:
  1841.               stop_reason = "request";
  1842.               break;
  1843.             case trace_buffer_full:
  1844.               stop_reason = "overflow";
  1845.               break;
  1846.             case trace_disconnected:
  1847.               stop_reason = "disconnection";
  1848.               break;
  1849.             case tracepoint_passcount:
  1850.               stop_reason = "passcount";
  1851.               stopping_tracepoint = ts->stopping_tracepoint;
  1852.               break;
  1853.             case tracepoint_error:
  1854.               stop_reason = "error";
  1855.               stopping_tracepoint = ts->stopping_tracepoint;
  1856.               break;
  1857.             }

  1858.           if (stop_reason)
  1859.             {
  1860.               ui_out_field_string (uiout, "stop-reason", stop_reason);
  1861.               if (stopping_tracepoint != -1)
  1862.                 ui_out_field_int (uiout, "stopping-tracepoint",
  1863.                                   stopping_tracepoint);
  1864.               if (ts->stop_reason == tracepoint_error)
  1865.                 ui_out_field_string (uiout, "error-description",
  1866.                                      ts->stop_desc);
  1867.             }
  1868.         }
  1869.     }

  1870.   if (ts->traceframe_count != -1)
  1871.     ui_out_field_int (uiout, "frames", ts->traceframe_count);
  1872.   if (ts->traceframes_created != -1)
  1873.     ui_out_field_int (uiout, "frames-created", ts->traceframes_created);
  1874.   if (ts->buffer_size != -1)
  1875.     ui_out_field_int (uiout, "buffer-size", ts->buffer_size);
  1876.   if (ts->buffer_free != -1)
  1877.     ui_out_field_int (uiout, "buffer-free", ts->buffer_free);

  1878.   ui_out_field_int (uiout, "disconnected"ts->disconnected_tracing);
  1879.   ui_out_field_int (uiout, "circular"ts->circular_buffer);

  1880.   ui_out_field_string (uiout, "user-name", ts->user_name);
  1881.   ui_out_field_string (uiout, "notes", ts->notes);

  1882.   {
  1883.     char buf[100];

  1884.     xsnprintf (buf, sizeof buf, "%ld.%06ld",
  1885.                (long int) (ts->start_time / 1000000),
  1886.                (long int) (ts->start_time % 1000000));
  1887.     ui_out_field_string (uiout, "start-time", buf);
  1888.     xsnprintf (buf, sizeof buf, "%ld.%06ld",
  1889.                (long int) (ts->stop_time / 1000000),
  1890.                (long int) (ts->stop_time % 1000000));
  1891.     ui_out_field_string (uiout, "stop-time", buf);
  1892.   }
  1893. }

  1894. /* Check if a trace run is ongoing.  If so, and FROM_TTY, query the
  1895.    user if she really wants to detach.  */

  1896. void
  1897. query_if_trace_running (int from_tty)
  1898. {
  1899.   if (!from_tty)
  1900.     return;

  1901.   /* It can happen that the target that was tracing went away on its
  1902.      own, and we didn't notice.  Get a status update, and if the
  1903.      current target doesn't even do tracing, then assume it's not
  1904.      running anymore.  */
  1905.   if (target_get_trace_status (current_trace_status ()) < 0)
  1906.     current_trace_status ()->running = 0;

  1907.   /* If running interactively, give the user the option to cancel and
  1908.      then decide what to do differently with the run.  Scripts are
  1909.      just going to disconnect and let the target deal with it,
  1910.      according to how it's been instructed previously via
  1911.      disconnected-tracing.  */
  1912.   if (current_trace_status ()->running)
  1913.     {
  1914.       process_tracepoint_on_disconnect ();

  1915.       if (current_trace_status ()->disconnected_tracing)
  1916.         {
  1917.           if (!query (_("Trace is running and will "
  1918.                         "continue after detach; detach anyway? ")))
  1919.             error (_("Not confirmed."));
  1920.         }
  1921.       else
  1922.         {
  1923.           if (!query (_("Trace is running but will "
  1924.                         "stop on detach; detach anyway? ")))
  1925.             error (_("Not confirmed."));
  1926.         }
  1927.     }
  1928. }

  1929. /* This function handles the details of what to do about an ongoing
  1930.    tracing run if the user has asked to detach or otherwise disconnect
  1931.    from the target.  */

  1932. void
  1933. disconnect_tracing (void)
  1934. {
  1935.   /* Also we want to be out of tfind mode, otherwise things can get
  1936.      confusing upon reconnection.  Just use these calls instead of
  1937.      full tfind_1 behavior because we're in the middle of detaching,
  1938.      and there's no point to updating current stack frame etc.  */
  1939.   trace_reset_local_state ();
  1940. }

  1941. /* Worker function for the various flavors of the tfind command.  */
  1942. void
  1943. tfind_1 (enum trace_find_type type, int num,
  1944.          CORE_ADDR addr1, CORE_ADDR addr2,
  1945.          int from_tty)
  1946. {
  1947.   int target_frameno = -1, target_tracept = -1;
  1948.   struct frame_id old_frame_id = null_frame_id;
  1949.   struct tracepoint *tp;
  1950.   struct ui_out *uiout = current_uiout;

  1951.   /* Only try to get the current stack frame if we have a chance of
  1952.      succeeding.  In particular, if we're trying to get a first trace
  1953.      frame while all threads are running, it's not going to succeed,
  1954.      so leave it with a default value and let the frame comparison
  1955.      below (correctly) decide to print out the source location of the
  1956.      trace frame.  */
  1957.   if (!(type == tfind_number && num == -1)
  1958.       && (has_stack_frames () || traceframe_number >= 0))
  1959.     old_frame_id = get_frame_id (get_current_frame ());

  1960.   target_frameno = target_trace_find (type, num, addr1, addr2,
  1961.                                       &target_tracept);

  1962.   if (type == tfind_number
  1963.       && num == -1
  1964.       && target_frameno == -1)
  1965.     {
  1966.       /* We told the target to get out of tfind mode, and it did.  */
  1967.     }
  1968.   else if (target_frameno == -1)
  1969.     {
  1970.       /* A request for a non-existent trace frame has failed.
  1971.          Our response will be different, depending on FROM_TTY:

  1972.          If FROM_TTY is true, meaning that this command was
  1973.          typed interactively by the user, then give an error
  1974.          and DO NOT change the state of traceframe_number etc.

  1975.          However if FROM_TTY is false, meaning that we're either
  1976.          in a script, a loop, or a user-defined command, then
  1977.          DON'T give an error, but DO change the state of
  1978.          traceframe_number etc. to invalid.

  1979.          The rationalle is that if you typed the command, you
  1980.          might just have committed a typo or something, and you'd
  1981.          like to NOT lose your current debugging state.  However
  1982.          if you're in a user-defined command or especially in a
  1983.          loop, then you need a way to detect that the command
  1984.          failed WITHOUT aborting.  This allows you to write
  1985.          scripts that search thru the trace buffer until the end,
  1986.          and then continue on to do something else.  */

  1987.       if (from_tty)
  1988.         error (_("Target failed to find requested trace frame."));
  1989.       else
  1990.         {
  1991.           if (info_verbose)
  1992.             printf_filtered ("End of trace buffer.\n");
  1993. #if 0 /* dubious now?  */
  1994.           /* The following will not recurse, since it's
  1995.              special-cased.  */
  1996.           trace_find_command ("-1", from_tty);
  1997. #endif
  1998.         }
  1999.     }

  2000.   tp = get_tracepoint_by_number_on_target (target_tracept);

  2001.   reinit_frame_cache ();
  2002.   target_dcache_invalidate ();

  2003.   set_tracepoint_num (tp ? tp->base.number : target_tracept);

  2004.   if (target_frameno != get_traceframe_number ())
  2005.     observer_notify_traceframe_changed (target_frameno, tracepoint_number);

  2006.   set_current_traceframe (target_frameno);

  2007.   if (target_frameno == -1)
  2008.     set_traceframe_context (NULL);
  2009.   else
  2010.     set_traceframe_context (get_current_frame ());

  2011.   if (traceframe_number >= 0)
  2012.     {
  2013.       /* Use different branches for MI and CLI to make CLI messages
  2014.          i18n-eable.  */
  2015.       if (ui_out_is_mi_like_p (uiout))
  2016.         {
  2017.           ui_out_field_string (uiout, "found", "1");
  2018.           ui_out_field_int (uiout, "tracepoint", tracepoint_number);
  2019.           ui_out_field_int (uiout, "traceframe", traceframe_number);
  2020.         }
  2021.       else
  2022.         {
  2023.           printf_unfiltered (_("Found trace frame %d, tracepoint %d\n"),
  2024.                              traceframe_number, tracepoint_number);
  2025.         }
  2026.     }
  2027.   else
  2028.     {
  2029.       if (ui_out_is_mi_like_p (uiout))
  2030.         ui_out_field_string (uiout, "found", "0");
  2031.       else if (type == tfind_number && num == -1)
  2032.         printf_unfiltered (_("No longer looking at any trace frame\n"));
  2033.       else /* This case may never occur, check.  */
  2034.         printf_unfiltered (_("No trace frame found\n"));
  2035.     }

  2036.   /* If we're in nonstop mode and getting out of looking at trace
  2037.      frames, there won't be any current frame to go back to and
  2038.      display.  */
  2039.   if (from_tty
  2040.       && (has_stack_frames () || traceframe_number >= 0))
  2041.     {
  2042.       enum print_what print_what;

  2043.       /* NOTE: in imitation of the step command, try to determine
  2044.          whether we have made a transition from one function to
  2045.          another.  If so, we'll print the "stack frame" (ie. the new
  2046.          function and it's arguments) -- otherwise we'll just show the
  2047.          new source line.  */

  2048.       if (frame_id_eq (old_frame_id,
  2049.                        get_frame_id (get_current_frame ())))
  2050.         print_what = SRC_LINE;
  2051.       else
  2052.         print_what = SRC_AND_LOC;

  2053.       print_stack_frame (get_selected_frame (NULL), 1, print_what, 1);
  2054.       do_displays ();
  2055.     }
  2056. }

  2057. /* Error on looking at traceframes while trace is running.  */

  2058. void
  2059. check_trace_running (struct trace_status *status)
  2060. {
  2061.   if (status->running && status->filename == NULL)
  2062.     error (_("May not look at trace frames while trace is running."));
  2063. }

  2064. /* trace_find_command takes a trace frame number n,
  2065.    sends "QTFrame:<n>" to the target,
  2066.    and accepts a reply that may contain several optional pieces
  2067.    of information: a frame number, a tracepoint number, and an
  2068.    indication of whether this is a trap frame or a stepping frame.

  2069.    The minimal response is just "OK" (which indicates that the
  2070.    target does not give us a frame number or a tracepoint number).
  2071.    Instead of that, the target may send us a string containing
  2072.    any combination of:
  2073.    F<hexnum>    (gives the selected frame number)
  2074.    T<hexnum>    (gives the selected tracepoint number)
  2075. */

  2076. /* tfind command */
  2077. static void
  2078. trace_find_command (char *args, int from_tty)
  2079. { /* This should only be called with a numeric argument.  */
  2080.   int frameno = -1;

  2081.   check_trace_running (current_trace_status ());

  2082.   if (args == 0 || *args == 0)
  2083.     { /* TFIND with no args means find NEXT trace frame.  */
  2084.       if (traceframe_number == -1)
  2085.         frameno = 0;        /* "next" is first one.  */
  2086.         else
  2087.         frameno = traceframe_number + 1;
  2088.     }
  2089.   else if (0 == strcmp (args, "-"))
  2090.     {
  2091.       if (traceframe_number == -1)
  2092.         error (_("not debugging trace buffer"));
  2093.       else if (from_tty && traceframe_number == 0)
  2094.         error (_("already at start of trace buffer"));

  2095.       frameno = traceframe_number - 1;
  2096.       }
  2097.   /* A hack to work around eval's need for fp to have been collected.  */
  2098.   else if (0 == strcmp (args, "-1"))
  2099.     frameno = -1;
  2100.   else
  2101.     frameno = parse_and_eval_long (args);

  2102.   if (frameno < -1)
  2103.     error (_("invalid input (%d is less than zero)"), frameno);

  2104.   tfind_1 (tfind_number, frameno, 0, 0, from_tty);
  2105. }

  2106. /* tfind end */
  2107. static void
  2108. trace_find_end_command (char *args, int from_tty)
  2109. {
  2110.   trace_find_command ("-1", from_tty);
  2111. }

  2112. /* tfind start */
  2113. static void
  2114. trace_find_start_command (char *args, int from_tty)
  2115. {
  2116.   trace_find_command ("0", from_tty);
  2117. }

  2118. /* tfind pc command */
  2119. static void
  2120. trace_find_pc_command (char *args, int from_tty)
  2121. {
  2122.   CORE_ADDR pc;

  2123.   check_trace_running (current_trace_status ());

  2124.   if (args == 0 || *args == 0)
  2125.     pc = regcache_read_pc (get_current_regcache ());
  2126.   else
  2127.     pc = parse_and_eval_address (args);

  2128.   tfind_1 (tfind_pc, 0, pc, 0, from_tty);
  2129. }

  2130. /* tfind tracepoint command */
  2131. static void
  2132. trace_find_tracepoint_command (char *args, int from_tty)
  2133. {
  2134.   int tdp;
  2135.   struct tracepoint *tp;

  2136.   check_trace_running (current_trace_status ());

  2137.   if (args == 0 || *args == 0)
  2138.     {
  2139.       if (tracepoint_number == -1)
  2140.         error (_("No current tracepoint -- please supply an argument."));
  2141.       else
  2142.         tdp = tracepoint_number;        /* Default is current TDP.  */
  2143.     }
  2144.   else
  2145.     tdp = parse_and_eval_long (args);

  2146.   /* If we have the tracepoint on hand, use the number that the
  2147.      target knows about (which may be different if we disconnected
  2148.      and reconnected).  */
  2149.   tp = get_tracepoint (tdp);
  2150.   if (tp)
  2151.     tdp = tp->number_on_target;

  2152.   tfind_1 (tfind_tp, tdp, 0, 0, from_tty);
  2153. }

  2154. /* TFIND LINE command:

  2155.    This command will take a sourceline for argument, just like BREAK
  2156.    or TRACE (ie. anything that "decode_line_1" can handle).

  2157.    With no argument, this command will find the next trace frame
  2158.    corresponding to a source line OTHER THAN THE CURRENT ONE.  */

  2159. static void
  2160. trace_find_line_command (char *args, int from_tty)
  2161. {
  2162.   static CORE_ADDR start_pc, end_pc;
  2163.   struct symtabs_and_lines sals;
  2164.   struct symtab_and_line sal;
  2165.   struct cleanup *old_chain;

  2166.   check_trace_running (current_trace_status ());

  2167.   if (args == 0 || *args == 0)
  2168.     {
  2169.       sal = find_pc_line (get_frame_pc (get_current_frame ()), 0);
  2170.       sals.nelts = 1;
  2171.       sals.sals = (struct symtab_and_line *)
  2172.         xmalloc (sizeof (struct symtab_and_line));
  2173.       sals.sals[0] = sal;
  2174.     }
  2175.   else
  2176.     {
  2177.       sals = decode_line_with_current_source (args, DECODE_LINE_FUNFIRSTLINE);
  2178.       sal = sals.sals[0];
  2179.     }

  2180.   old_chain = make_cleanup (xfree, sals.sals);
  2181.   if (sal.symtab == 0)
  2182.     error (_("No line number information available."));

  2183.   if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
  2184.     {
  2185.       if (start_pc == end_pc)
  2186.           {
  2187.           printf_filtered ("Line %d of \"%s\"",
  2188.                            sal.line,
  2189.                            symtab_to_filename_for_display (sal.symtab));
  2190.           wrap_here ("  ");
  2191.           printf_filtered (" is at address ");
  2192.           print_address (get_current_arch (), start_pc, gdb_stdout);
  2193.           wrap_here ("  ");
  2194.           printf_filtered (" but contains no code.\n");
  2195.           sal = find_pc_line (start_pc, 0);
  2196.           if (sal.line > 0
  2197.               && find_line_pc_range (sal, &start_pc, &end_pc)
  2198.               && start_pc != end_pc)
  2199.             printf_filtered ("Attempting to find line %d instead.\n",
  2200.                              sal.line);
  2201.             else
  2202.             error (_("Cannot find a good line."));
  2203.           }
  2204.       }
  2205.     else
  2206.     /* Is there any case in which we get here, and have an address
  2207.        which the user would want to see?  If we have debugging
  2208.        symbols and no line numbers?  */
  2209.     error (_("Line number %d is out of range for \"%s\"."),
  2210.            sal.line, symtab_to_filename_for_display (sal.symtab));

  2211.   /* Find within range of stated line.  */
  2212.   if (args && *args)
  2213.     tfind_1 (tfind_range, 0, start_pc, end_pc - 1, from_tty);
  2214.   else
  2215.     tfind_1 (tfind_outside, 0, start_pc, end_pc - 1, from_tty);
  2216.   do_cleanups (old_chain);
  2217. }

  2218. /* tfind range command */
  2219. static void
  2220. trace_find_range_command (char *args, int from_tty)
  2221. {
  2222.   static CORE_ADDR start, stop;
  2223.   char *tmp;

  2224.   check_trace_running (current_trace_status ());

  2225.   if (args == 0 || *args == 0)
  2226.     { /* XXX FIXME: what should default behavior be?  */
  2227.       printf_filtered ("Usage: tfind range <startaddr>,<endaddr>\n");
  2228.       return;
  2229.     }

  2230.   if (0 != (tmp = strchr (args, ',')))
  2231.     {
  2232.       *tmp++ = '\0';        /* Terminate start address.  */
  2233.       tmp = skip_spaces (tmp);
  2234.       start = parse_and_eval_address (args);
  2235.       stop = parse_and_eval_address (tmp);
  2236.     }
  2237.   else
  2238.     {                        /* No explicit end address?  */
  2239.       start = parse_and_eval_address (args);
  2240.       stop = start + 1;        /* ??? */
  2241.     }

  2242.   tfind_1 (tfind_range, 0, start, stop, from_tty);
  2243. }

  2244. /* tfind outside command */
  2245. static void
  2246. trace_find_outside_command (char *args, int from_tty)
  2247. {
  2248.   CORE_ADDR start, stop;
  2249.   char *tmp;

  2250.   if (current_trace_status ()->running
  2251.       && current_trace_status ()->filename == NULL)
  2252.     error (_("May not look at trace frames while trace is running."));

  2253.   if (args == 0 || *args == 0)
  2254.     { /* XXX FIXME: what should default behavior be?  */
  2255.       printf_filtered ("Usage: tfind outside <startaddr>,<endaddr>\n");
  2256.       return;
  2257.     }

  2258.   if (0 != (tmp = strchr (args, ',')))
  2259.     {
  2260.       *tmp++ = '\0';        /* Terminate start address.  */
  2261.       tmp = skip_spaces (tmp);
  2262.       start = parse_and_eval_address (args);
  2263.       stop = parse_and_eval_address (tmp);
  2264.     }
  2265.   else
  2266.     {                        /* No explicit end address?  */
  2267.       start = parse_and_eval_address (args);
  2268.       stop = start + 1;        /* ??? */
  2269.     }

  2270.   tfind_1 (tfind_outside, 0, start, stop, from_tty);
  2271. }

  2272. /* info scope command: list the locals for a scope.  */
  2273. static void
  2274. scope_info (char *args, int from_tty)
  2275. {
  2276.   struct symtabs_and_lines sals;
  2277.   struct symbol *sym;
  2278.   struct bound_minimal_symbol msym;
  2279.   const struct block *block;
  2280.   const char *symname;
  2281.   char *save_args = args;
  2282.   struct block_iterator iter;
  2283.   int j, count = 0;
  2284.   struct gdbarch *gdbarch;
  2285.   int regno;

  2286.   if (args == 0 || *args == 0)
  2287.     error (_("requires an argument (function, "
  2288.              "line or *addr) to define a scope"));

  2289.   sals = decode_line_1 (&args, DECODE_LINE_FUNFIRSTLINE, NULL, 0);
  2290.   if (sals.nelts == 0)
  2291.     return;                /* Presumably decode_line_1 has already warned.  */

  2292.   /* Resolve line numbers to PC.  */
  2293.   resolve_sal_pc (&sals.sals[0]);
  2294.   block = block_for_pc (sals.sals[0].pc);

  2295.   while (block != 0)
  2296.     {
  2297.       QUIT;                        /* Allow user to bail out with ^C.  */
  2298.       ALL_BLOCK_SYMBOLS (block, iter, sym)
  2299.         {
  2300.           QUIT;                        /* Allow user to bail out with ^C.  */
  2301.           if (count == 0)
  2302.             printf_filtered ("Scope for %s:\n", save_args);
  2303.           count++;

  2304.           symname = SYMBOL_PRINT_NAME (sym);
  2305.           if (symname == NULL || *symname == '\0')
  2306.             continue;                /* Probably botched, certainly useless.  */

  2307.           gdbarch = symbol_arch (sym);

  2308.           printf_filtered ("Symbol %s is ", symname);

  2309.           if (SYMBOL_COMPUTED_OPS (sym) != NULL)
  2310.             SYMBOL_COMPUTED_OPS (sym)->describe_location (sym,
  2311.                                                           BLOCK_START (block),
  2312.                                                           gdb_stdout);
  2313.           else
  2314.             {
  2315.               switch (SYMBOL_CLASS (sym))
  2316.                 {
  2317.                 default:
  2318.                 case LOC_UNDEF:        /* Messed up symbol?  */
  2319.                   printf_filtered ("a bogus symbol, class %d.\n",
  2320.                                    SYMBOL_CLASS (sym));
  2321.                   count--;                /* Don't count this one.  */
  2322.                   continue;
  2323.                 case LOC_CONST:
  2324.                   printf_filtered ("a constant with value %s (%s)",
  2325.                                    plongest (SYMBOL_VALUE (sym)),
  2326.                                    hex_string (SYMBOL_VALUE (sym)));
  2327.                   break;
  2328.                 case LOC_CONST_BYTES:
  2329.                   printf_filtered ("constant bytes: ");
  2330.                   if (SYMBOL_TYPE (sym))
  2331.                     for (j = 0; j < TYPE_LENGTH (SYMBOL_TYPE (sym)); j++)
  2332.                       fprintf_filtered (gdb_stdout, " %02x",
  2333.                                         (unsigned) SYMBOL_VALUE_BYTES (sym)[j]);
  2334.                   break;
  2335.                 case LOC_STATIC:
  2336.                   printf_filtered ("in static storage at address ");
  2337.                   printf_filtered ("%s", paddress (gdbarch,
  2338.                                                    SYMBOL_VALUE_ADDRESS (sym)));
  2339.                   break;
  2340.                 case LOC_REGISTER:
  2341.                   /* GDBARCH is the architecture associated with the objfile
  2342.                      the symbol is defined in; the target architecture may be
  2343.                      different, and may provide additional registers.  However,
  2344.                      we do not know the target architecture at this point.
  2345.                      We assume the objfile architecture will contain all the
  2346.                      standard registers that occur in debug info in that
  2347.                      objfile.  */
  2348.                   regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym,
  2349.                                                                       gdbarch);

  2350.                   if (SYMBOL_IS_ARGUMENT (sym))
  2351.                     printf_filtered ("an argument in register $%s",
  2352.                                      gdbarch_register_name (gdbarch, regno));
  2353.                   else
  2354.                     printf_filtered ("a local variable in register $%s",
  2355.                                      gdbarch_register_name (gdbarch, regno));
  2356.                   break;
  2357.                 case LOC_ARG:
  2358.                   printf_filtered ("an argument at stack/frame offset %s",
  2359.                                    plongest (SYMBOL_VALUE (sym)));
  2360.                   break;
  2361.                 case LOC_LOCAL:
  2362.                   printf_filtered ("a local variable at frame offset %s",
  2363.                                    plongest (SYMBOL_VALUE (sym)));
  2364.                   break;
  2365.                 case LOC_REF_ARG:
  2366.                   printf_filtered ("a reference argument at offset %s",
  2367.                                    plongest (SYMBOL_VALUE (sym)));
  2368.                   break;
  2369.                 case LOC_REGPARM_ADDR:
  2370.                   /* Note comment at LOC_REGISTER.  */
  2371.                   regno = SYMBOL_REGISTER_OPS (sym)->register_number (sym,
  2372.                                                                       gdbarch);
  2373.                   printf_filtered ("the address of an argument, in register $%s",
  2374.                                    gdbarch_register_name (gdbarch, regno));
  2375.                   break;
  2376.                 case LOC_TYPEDEF:
  2377.                   printf_filtered ("a typedef.\n");
  2378.                   continue;
  2379.                 case LOC_LABEL:
  2380.                   printf_filtered ("a label at address ");
  2381.                   printf_filtered ("%s", paddress (gdbarch,
  2382.                                                    SYMBOL_VALUE_ADDRESS (sym)));
  2383.                   break;
  2384.                 case LOC_BLOCK:
  2385.                   printf_filtered ("a function at address ");
  2386.                   printf_filtered ("%s",
  2387.                                    paddress (gdbarch, BLOCK_START (SYMBOL_BLOCK_VALUE (sym))));
  2388.                   break;
  2389.                 case LOC_UNRESOLVED:
  2390.                   msym = lookup_minimal_symbol (SYMBOL_LINKAGE_NAME (sym),
  2391.                                                 NULL, NULL);
  2392.                   if (msym.minsym == NULL)
  2393.                     printf_filtered ("Unresolved Static");
  2394.                   else
  2395.                     {
  2396.                       printf_filtered ("static storage at address ");
  2397.                       printf_filtered ("%s",
  2398.                                        paddress (gdbarch,
  2399.                                                  BMSYMBOL_VALUE_ADDRESS (msym)));
  2400.                     }
  2401.                   break;
  2402.                 case LOC_OPTIMIZED_OUT:
  2403.                   printf_filtered ("optimized out.\n");
  2404.                   continue;
  2405.                 case LOC_COMPUTED:
  2406.                   gdb_assert_not_reached (_("LOC_COMPUTED variable missing a method"));
  2407.                 }
  2408.             }
  2409.           if (SYMBOL_TYPE (sym))
  2410.             printf_filtered (", length %d.\n",
  2411.                              TYPE_LENGTH (check_typedef (SYMBOL_TYPE (sym))));
  2412.         }
  2413.       if (BLOCK_FUNCTION (block))
  2414.         break;
  2415.       else
  2416.         block = BLOCK_SUPERBLOCK (block);
  2417.     }
  2418.   if (count <= 0)
  2419.     printf_filtered ("Scope for %s contains no locals or arguments.\n",
  2420.                      save_args);
  2421. }

  2422. /* Helper for trace_dump_command.  Dump the action list starting at
  2423.    ACTION.  STEPPING_ACTIONS is true if we're iterating over the
  2424.    actions of the body of a while-stepping action.  STEPPING_FRAME is
  2425.    set if the current traceframe was determined to be a while-stepping
  2426.    traceframe.  */

  2427. static void
  2428. trace_dump_actions (struct command_line *action,
  2429.                     int stepping_actions, int stepping_frame,
  2430.                     int from_tty)
  2431. {
  2432.   const char *action_exp, *next_comma;

  2433.   for (; action != NULL; action = action->next)
  2434.     {
  2435.       struct cmd_list_element *cmd;

  2436.       QUIT;                        /* Allow user to bail out with ^C.  */
  2437.       action_exp = action->line;
  2438.       action_exp = skip_spaces_const (action_exp);

  2439.       /* The collection actions to be done while stepping are
  2440.          bracketed by the commands "while-stepping" and "end".  */

  2441.       if (*action_exp == '#')        /* comment line */
  2442.         continue;

  2443.       cmd = lookup_cmd (&action_exp, cmdlist, "", -1, 1);
  2444.       if (cmd == 0)
  2445.         error (_("Bad action list item: %s"), action_exp);

  2446.       if (cmd_cfunc_eq (cmd, while_stepping_pseudocommand))
  2447.         {
  2448.           int i;

  2449.           for (i = 0; i < action->body_count; ++i)
  2450.             trace_dump_actions (action->body_list[i],
  2451.                                 1, stepping_frame, from_tty);
  2452.         }
  2453.       else if (cmd_cfunc_eq (cmd, collect_pseudocommand))
  2454.         {
  2455.           /* Display the collected data.
  2456.              For the trap frame, display only what was collected at
  2457.              the trap.  Likewise for stepping frames, display only
  2458.              what was collected while stepping.  This means that the
  2459.              two boolean variables, STEPPING_FRAME and
  2460.              STEPPING_ACTIONS should be equal.  */
  2461.           if (stepping_frame == stepping_actions)
  2462.             {
  2463.               char *cmd = NULL;
  2464.               struct cleanup *old_chain
  2465.                 = make_cleanup (free_current_contents, &cmd);
  2466.               int trace_string = 0;

  2467.               if (*action_exp == '/')
  2468.                 action_exp = decode_agent_options (action_exp, &trace_string);

  2469.               do
  2470.                 {                /* Repeat over a comma-separated list.  */
  2471.                   QUIT;                /* Allow user to bail out with ^C.  */
  2472.                   if (*action_exp == ',')
  2473.                     action_exp++;
  2474.                   action_exp = skip_spaces_const (action_exp);

  2475.                   next_comma = strchr (action_exp, ',');

  2476.                   if (0 == strncasecmp (action_exp, "$reg", 4))
  2477.                     registers_info (NULL, from_tty);
  2478.                   else if (0 == strncasecmp (action_exp, "$_ret", 5))
  2479.                     ;
  2480.                   else if (0 == strncasecmp (action_exp, "$loc", 4))
  2481.                     locals_info (NULL, from_tty);
  2482.                   else if (0 == strncasecmp (action_exp, "$arg", 4))
  2483.                     args_info (NULL, from_tty);
  2484.                   else
  2485.                     {                /* variable */
  2486.                       if (next_comma != NULL)
  2487.                         {
  2488.                           size_t len = next_comma - action_exp;

  2489.                           cmd = xrealloc (cmd, len + 1);
  2490.                           memcpy (cmd, action_exp, len);
  2491.                           cmd[len] = 0;
  2492.                         }
  2493.                       else
  2494.                         {
  2495.                           size_t len = strlen (action_exp);

  2496.                           cmd = xrealloc (cmd, len + 1);
  2497.                           memcpy (cmd, action_exp, len + 1);
  2498.                         }

  2499.                       printf_filtered ("%s = ", cmd);
  2500.                       output_command_const (cmd, from_tty);
  2501.                       printf_filtered ("\n");
  2502.                     }
  2503.                   action_exp = next_comma;
  2504.                 }
  2505.               while (action_exp && *action_exp == ',');

  2506.               do_cleanups (old_chain);
  2507.             }
  2508.         }
  2509.     }
  2510. }

  2511. /* Return bp_location of the tracepoint associated with the current
  2512.    traceframe.  Set *STEPPING_FRAME_P to 1 if the current traceframe
  2513.    is a stepping traceframe.  */

  2514. struct bp_location *
  2515. get_traceframe_location (int *stepping_frame_p)
  2516. {
  2517.   struct tracepoint *t;
  2518.   struct bp_location *tloc;
  2519.   struct regcache *regcache;

  2520.   if (tracepoint_number == -1)
  2521.     error (_("No current trace frame."));

  2522.   t = get_tracepoint (tracepoint_number);

  2523.   if (t == NULL)
  2524.     error (_("No known tracepoint matches 'current' tracepoint #%d."),
  2525.            tracepoint_number);

  2526.   /* The current frame is a trap frame if the frame PC is equal to the
  2527.      tracepoint PC.  If not, then the current frame was collected
  2528.      during single-stepping.  */
  2529.   regcache = get_current_regcache ();

  2530.   /* If the traceframe's address matches any of the tracepoint's
  2531.      locations, assume it is a direct hit rather than a while-stepping
  2532.      frame.  (FIXME this is not reliable, should record each frame's
  2533.      type.)  */
  2534.   for (tloc = t->base.loc; tloc; tloc = tloc->next)
  2535.     if (tloc->address == regcache_read_pc (regcache))
  2536.       {
  2537.         *stepping_frame_p = 0;
  2538.         return tloc;
  2539.       }

  2540.   /* If this is a stepping frame, we don't know which location
  2541.      triggered.  The first is as good (or bad) a guess as any...  */
  2542.   *stepping_frame_p = 1;
  2543.   return t->base.loc;
  2544. }

  2545. /* Return all the actions, including default collect, of a tracepoint
  2546.    T.  It constructs cleanups into the chain, and leaves the caller to
  2547.    handle them (call do_cleanups).  */

  2548. static struct command_line *
  2549. all_tracepoint_actions_and_cleanup (struct breakpoint *t)
  2550. {
  2551.   struct command_line *actions;

  2552.   actions = breakpoint_commands (t);

  2553.   /* If there are default expressions to collect, make up a collect
  2554.      action and prepend to the action list to encode.  Note that since
  2555.      validation is per-tracepoint (local var "xyz" might be valid for
  2556.      one tracepoint and not another, etc), we make up the action on
  2557.      the fly, and don't cache it.  */
  2558.   if (*default_collect)
  2559.     {
  2560.       struct command_line *default_collect_action;
  2561.       char *default_collect_line;

  2562.       default_collect_line = xstrprintf ("collect %s", default_collect);
  2563.       make_cleanup (xfree, default_collect_line);

  2564.       validate_actionline (default_collect_line, t);
  2565.       default_collect_action = xmalloc (sizeof (struct command_line));
  2566.       make_cleanup (xfree, default_collect_action);
  2567.       default_collect_action->next = actions;
  2568.       default_collect_action->line = default_collect_line;
  2569.       actions = default_collect_action;
  2570.     }

  2571.   return actions;
  2572. }

  2573. /* The tdump command.  */

  2574. static void
  2575. trace_dump_command (char *args, int from_tty)
  2576. {
  2577.   int stepping_frame = 0;
  2578.   struct bp_location *loc;
  2579.   struct cleanup *old_chain;
  2580.   struct command_line *actions;

  2581.   /* This throws an error is not inspecting a trace frame.  */
  2582.   loc = get_traceframe_location (&stepping_frame);

  2583.   printf_filtered ("Data collected at tracepoint %d, trace frame %d:\n",
  2584.                    tracepoint_number, traceframe_number);

  2585.   old_chain = make_cleanup (null_cleanup, NULL);

  2586.   /* This command only makes sense for the current frame, not the
  2587.      selected frame.  */
  2588.   make_cleanup_restore_current_thread ();
  2589.   select_frame (get_current_frame ());

  2590.   actions = all_tracepoint_actions_and_cleanup (loc->owner);

  2591.   trace_dump_actions (actions, 0, stepping_frame, from_tty);

  2592.   do_cleanups (old_chain);
  2593. }

  2594. /* Encode a piece of a tracepoint's source-level definition in a form
  2595.    that is suitable for both protocol and saving in files.  */
  2596. /* This version does not do multiple encodes for long strings; it should
  2597.    return an offset to the next piece to encode.  FIXME  */

  2598. extern int
  2599. encode_source_string (int tpnum, ULONGEST addr,
  2600.                       char *srctype, char *src, char *buf, int buf_size)
  2601. {
  2602.   if (80 + strlen (srctype) > buf_size)
  2603.     error (_("Buffer too small for source encoding"));
  2604.   sprintf (buf, "%x:%s:%s:%x:%x:",
  2605.            tpnum, phex_nz (addr, sizeof (addr)),
  2606.            srctype, 0, (int) strlen (src));
  2607.   if (strlen (buf) + strlen (src) * 2 >= buf_size)
  2608.     error (_("Source string too long for buffer"));
  2609.   bin2hex ((gdb_byte *) src, buf + strlen (buf), strlen (src));
  2610.   return -1;
  2611. }

  2612. /* Tell the target what to do with an ongoing tracing run if GDB
  2613.    disconnects for some reason.  */

  2614. static void
  2615. set_disconnected_tracing (char *args, int from_tty,
  2616.                           struct cmd_list_element *c)
  2617. {
  2618.   target_set_disconnected_tracing (disconnected_tracing);
  2619. }

  2620. static void
  2621. set_circular_trace_buffer (char *args, int from_tty,
  2622.                            struct cmd_list_element *c)
  2623. {
  2624.   target_set_circular_trace_buffer (circular_trace_buffer);
  2625. }

  2626. static void
  2627. set_trace_buffer_size (char *args, int from_tty,
  2628.                            struct cmd_list_element *c)
  2629. {
  2630.   target_set_trace_buffer_size (trace_buffer_size);
  2631. }

  2632. static void
  2633. set_trace_user (char *args, int from_tty,
  2634.                 struct cmd_list_element *c)
  2635. {
  2636.   int ret;

  2637.   ret = target_set_trace_notes (trace_user, NULL, NULL);

  2638.   if (!ret)
  2639.     warning (_("Target does not support trace notes, user ignored"));
  2640. }

  2641. static void
  2642. set_trace_notes (char *args, int from_tty,
  2643.                  struct cmd_list_element *c)
  2644. {
  2645.   int ret;

  2646.   ret = target_set_trace_notes (NULL, trace_notes, NULL);

  2647.   if (!ret)
  2648.     warning (_("Target does not support trace notes, note ignored"));
  2649. }

  2650. static void
  2651. set_trace_stop_notes (char *args, int from_tty,
  2652.                       struct cmd_list_element *c)
  2653. {
  2654.   int ret;

  2655.   ret = target_set_trace_notes (NULL, NULL, trace_stop_notes);

  2656.   if (!ret)
  2657.     warning (_("Target does not support trace notes, stop note ignored"));
  2658. }

  2659. /* Convert the memory pointed to by mem into hex, placing result in buf.
  2660. * Return a pointer to the last char put in buf (null)
  2661. * "stolen" from sparc-stub.c
  2662. */

  2663. static const char hexchars[] = "0123456789abcdef";

  2664. static char *
  2665. mem2hex (gdb_byte *mem, char *buf, int count)
  2666. {
  2667.   gdb_byte ch;

  2668.   while (count-- > 0)
  2669.     {
  2670.       ch = *mem++;

  2671.       *buf++ = hexchars[ch >> 4];
  2672.       *buf++ = hexchars[ch & 0xf];
  2673.     }

  2674.   *buf = 0;

  2675.   return buf;
  2676. }

  2677. int
  2678. get_traceframe_number (void)
  2679. {
  2680.   return traceframe_number;
  2681. }

  2682. int
  2683. get_tracepoint_number (void)
  2684. {
  2685.   return tracepoint_number;
  2686. }

  2687. /* Make the traceframe NUM be the current trace frame.  Does nothing
  2688.    if NUM is already current.  */

  2689. void
  2690. set_current_traceframe (int num)
  2691. {
  2692.   int newnum;

  2693.   if (traceframe_number == num)
  2694.     {
  2695.       /* Nothing to do.  */
  2696.       return;
  2697.     }

  2698.   newnum = target_trace_find (tfind_number, num, 0, 0, NULL);

  2699.   if (newnum != num)
  2700.     warning (_("could not change traceframe"));

  2701.   set_traceframe_num (newnum);

  2702.   /* Changing the traceframe changes our view of registers and of the
  2703.      frame chain.  */
  2704.   registers_changed ();

  2705.   clear_traceframe_info ();
  2706. }

  2707. /* A cleanup used when switching away and back from tfind mode.  */

  2708. struct current_traceframe_cleanup
  2709. {
  2710.   /* The traceframe we were inspecting.  */
  2711.   int traceframe_number;
  2712. };

  2713. static void
  2714. do_restore_current_traceframe_cleanup (void *arg)
  2715. {
  2716.   struct current_traceframe_cleanup *old = arg;

  2717.   set_current_traceframe (old->traceframe_number);
  2718. }

  2719. static void
  2720. restore_current_traceframe_cleanup_dtor (void *arg)
  2721. {
  2722.   struct current_traceframe_cleanup *old = arg;

  2723.   xfree (old);
  2724. }

  2725. struct cleanup *
  2726. make_cleanup_restore_current_traceframe (void)
  2727. {
  2728.   struct current_traceframe_cleanup *old;

  2729.   old = xmalloc (sizeof (struct current_traceframe_cleanup));
  2730.   old->traceframe_number = traceframe_number;

  2731.   return make_cleanup_dtor (do_restore_current_traceframe_cleanup, old,
  2732.                             restore_current_traceframe_cleanup_dtor);
  2733. }

  2734. /* Given a number and address, return an uploaded tracepoint with that
  2735.    number, creating if necessary.  */

  2736. struct uploaded_tp *
  2737. get_uploaded_tp (int num, ULONGEST addr, struct uploaded_tp **utpp)
  2738. {
  2739.   struct uploaded_tp *utp;

  2740.   for (utp = *utpp; utp; utp = utp->next)
  2741.     if (utp->number == num && utp->addr == addr)
  2742.       return utp;
  2743.   utp = (struct uploaded_tp *) xmalloc (sizeof (struct uploaded_tp));
  2744.   memset (utp, 0, sizeof (struct uploaded_tp));
  2745.   utp->number = num;
  2746.   utp->addr = addr;
  2747.   utp->actions = NULL;
  2748.   utp->step_actions = NULL;
  2749.   utp->cmd_strings = NULL;
  2750.   utp->next = *utpp;
  2751.   *utpp = utp;
  2752.   return utp;
  2753. }

  2754. void
  2755. free_uploaded_tps (struct uploaded_tp **utpp)
  2756. {
  2757.   struct uploaded_tp *next_one;

  2758.   while (*utpp)
  2759.     {
  2760.       next_one = (*utpp)->next;
  2761.       xfree (*utpp);
  2762.       *utpp = next_one;
  2763.     }
  2764. }

  2765. /* Given a number and address, return an uploaded tracepoint with that
  2766.    number, creating if necessary.  */

  2767. struct uploaded_tsv *
  2768. get_uploaded_tsv (int num, struct uploaded_tsv **utsvp)
  2769. {
  2770.   struct uploaded_tsv *utsv;

  2771.   for (utsv = *utsvp; utsv; utsv = utsv->next)
  2772.     if (utsv->number == num)
  2773.       return utsv;
  2774.   utsv = (struct uploaded_tsv *) xmalloc (sizeof (struct uploaded_tsv));
  2775.   memset (utsv, 0, sizeof (struct uploaded_tsv));
  2776.   utsv->number = num;
  2777.   utsv->next = *utsvp;
  2778.   *utsvp = utsv;
  2779.   return utsv;
  2780. }

  2781. void
  2782. free_uploaded_tsvs (struct uploaded_tsv **utsvp)
  2783. {
  2784.   struct uploaded_tsv *next_one;

  2785.   while (*utsvp)
  2786.     {
  2787.       next_one = (*utsvp)->next;
  2788.       xfree (*utsvp);
  2789.       *utsvp = next_one;
  2790.     }
  2791. }

  2792. /* FIXME this function is heuristic and will miss the cases where the
  2793.    conditional is semantically identical but differs in whitespace,
  2794.    such as "x == 0" vs "x==0".  */

  2795. static int
  2796. cond_string_is_same (char *str1, char *str2)
  2797. {
  2798.   if (str1 == NULL || str2 == NULL)
  2799.     return (str1 == str2);

  2800.   return (strcmp (str1, str2) == 0);
  2801. }

  2802. /* Look for an existing tracepoint that seems similar enough to the
  2803.    uploaded one.  Enablement isn't compared, because the user can
  2804.    toggle that freely, and may have done so in anticipation of the
  2805.    next trace run.  Return the location of matched tracepoint.  */

  2806. static struct bp_location *
  2807. find_matching_tracepoint_location (struct uploaded_tp *utp)
  2808. {
  2809.   VEC(breakpoint_p) *tp_vec = all_tracepoints ();
  2810.   int ix;
  2811.   struct breakpoint *b;
  2812.   struct bp_location *loc;

  2813.   for (ix = 0; VEC_iterate (breakpoint_p, tp_vec, ix, b); ix++)
  2814.     {
  2815.       struct tracepoint *t = (struct tracepoint *) b;

  2816.       if (b->type == utp->type
  2817.           && t->step_count == utp->step
  2818.           && t->pass_count == utp->pass
  2819.           && cond_string_is_same (t->base.cond_string, utp->cond_string)
  2820.           /* FIXME also test actions.  */
  2821.           )
  2822.         {
  2823.           /* Scan the locations for an address match.  */
  2824.           for (loc = b->loc; loc; loc = loc->next)
  2825.             {
  2826.               if (loc->address == utp->addr)
  2827.                 return loc;
  2828.             }
  2829.         }
  2830.     }
  2831.   return NULL;
  2832. }

  2833. /* Given a list of tracepoints uploaded from a target, attempt to
  2834.    match them up with existing tracepoints, and create new ones if not
  2835.    found.  */

  2836. void
  2837. merge_uploaded_tracepoints (struct uploaded_tp **uploaded_tps)
  2838. {
  2839.   struct uploaded_tp *utp;
  2840.   /* A set of tracepoints which are modified.  */
  2841.   VEC(breakpoint_p) *modified_tp = NULL;
  2842.   int ix;
  2843.   struct breakpoint *b;

  2844.   /* Look for GDB tracepoints that match up with our uploaded versions.  */
  2845.   for (utp = *uploaded_tps; utp; utp = utp->next)
  2846.     {
  2847.       struct bp_location *loc;
  2848.       struct tracepoint *t;

  2849.       loc = find_matching_tracepoint_location (utp);
  2850.       if (loc)
  2851.         {
  2852.           int found = 0;

  2853.           /* Mark this location as already inserted.  */
  2854.           loc->inserted = 1;
  2855.           t = (struct tracepoint *) loc->owner;
  2856.           printf_filtered (_("Assuming tracepoint %d is same "
  2857.                              "as target's tracepoint %d at %s.\n"),
  2858.                            loc->owner->number, utp->number,
  2859.                            paddress (loc->gdbarch, utp->addr));

  2860.           /* The tracepoint LOC->owner was modified (the location LOC
  2861.              was marked as inserted in the target).  Save it in
  2862.              MODIFIED_TP if not there yet.  The 'breakpoint-modified'
  2863.              observers will be notified later once for each tracepoint
  2864.              saved in MODIFIED_TP.  */
  2865.           for (ix = 0;
  2866.                VEC_iterate (breakpoint_p, modified_tp, ix, b);
  2867.                ix++)
  2868.             if (b == loc->owner)
  2869.               {
  2870.                 found = 1;
  2871.                 break;
  2872.               }
  2873.           if (!found)
  2874.             VEC_safe_push (breakpoint_p, modified_tp, loc->owner);
  2875.         }
  2876.       else
  2877.         {
  2878.           t = create_tracepoint_from_upload (utp);
  2879.           if (t)
  2880.             printf_filtered (_("Created tracepoint %d for "
  2881.                                "target's tracepoint %d at %s.\n"),
  2882.                              t->base.number, utp->number,
  2883.                              paddress (get_current_arch (), utp->addr));
  2884.           else
  2885.             printf_filtered (_("Failed to create tracepoint for target's "
  2886.                                "tracepoint %d at %s, skipping it.\n"),
  2887.                              utp->number,
  2888.                              paddress (get_current_arch (), utp->addr));
  2889.         }
  2890.       /* Whether found or created, record the number used by the
  2891.          target, to help with mapping target tracepoints back to their
  2892.          counterparts here.  */
  2893.       if (t)
  2894.         t->number_on_target = utp->number;
  2895.     }

  2896.   /* Notify 'breakpoint-modified' observer that at least one of B's
  2897.      locations was changed.  */
  2898.   for (ix = 0; VEC_iterate (breakpoint_p, modified_tp, ix, b); ix++)
  2899.     observer_notify_breakpoint_modified (b);

  2900.   VEC_free (breakpoint_p, modified_tp);
  2901.   free_uploaded_tps (uploaded_tps);
  2902. }

  2903. /* Trace state variables don't have much to identify them beyond their
  2904.    name, so just use that to detect matches.  */

  2905. static struct trace_state_variable *
  2906. find_matching_tsv (struct uploaded_tsv *utsv)
  2907. {
  2908.   if (!utsv->name)
  2909.     return NULL;

  2910.   return find_trace_state_variable (utsv->name);
  2911. }

  2912. static struct trace_state_variable *
  2913. create_tsv_from_upload (struct uploaded_tsv *utsv)
  2914. {
  2915.   const char *namebase;
  2916.   char *buf;
  2917.   int try_num = 0;
  2918.   struct trace_state_variable *tsv;
  2919.   struct cleanup *old_chain;

  2920.   if (utsv->name)
  2921.     {
  2922.       namebase = utsv->name;
  2923.       buf = xstrprintf ("%s", namebase);
  2924.     }
  2925.   else
  2926.     {
  2927.       namebase = "__tsv";
  2928.       buf = xstrprintf ("%s_%d", namebase, try_num++);
  2929.     }

  2930.   /* Fish for a name that is not in use.  */
  2931.   /* (should check against all internal vars?)  */
  2932.   while (find_trace_state_variable (buf))
  2933.     {
  2934.       xfree (buf);
  2935.       buf = xstrprintf ("%s_%d", namebase, try_num++);
  2936.     }

  2937.   old_chain = make_cleanup (xfree, buf);

  2938.   /* We have an available name, create the variable.  */
  2939.   tsv = create_trace_state_variable (buf);
  2940.   tsv->initial_value = utsv->initial_value;
  2941.   tsv->builtin = utsv->builtin;

  2942.   observer_notify_tsv_created (tsv);

  2943.   do_cleanups (old_chain);

  2944.   return tsv;
  2945. }

  2946. /* Given a list of uploaded trace state variables, try to match them
  2947.    up with existing variables, or create additional ones.  */

  2948. void
  2949. merge_uploaded_trace_state_variables (struct uploaded_tsv **uploaded_tsvs)
  2950. {
  2951.   int ix;
  2952.   struct uploaded_tsv *utsv;
  2953.   struct trace_state_variable *tsv;
  2954.   int highest;

  2955.   /* Most likely some numbers will have to be reassigned as part of
  2956.      the merge, so clear them all in anticipation.  */
  2957.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  2958.     tsv->number = 0;

  2959.   for (utsv = *uploaded_tsvs; utsv; utsv = utsv->next)
  2960.     {
  2961.       tsv = find_matching_tsv (utsv);
  2962.       if (tsv)
  2963.         {
  2964.           if (info_verbose)
  2965.             printf_filtered (_("Assuming trace state variable $%s "
  2966.                                "is same as target's variable %d.\n"),
  2967.                              tsv->name, utsv->number);
  2968.         }
  2969.       else
  2970.         {
  2971.           tsv = create_tsv_from_upload (utsv);
  2972.           if (info_verbose)
  2973.             printf_filtered (_("Created trace state variable "
  2974.                                "$%s for target's variable %d.\n"),
  2975.                              tsv->name, utsv->number);
  2976.         }
  2977.       /* Give precedence to numberings that come from the target.  */
  2978.       if (tsv)
  2979.         tsv->number = utsv->number;
  2980.     }

  2981.   /* Renumber everything that didn't get a target-assigned number.  */
  2982.   highest = 0;
  2983.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  2984.     if (tsv->number > highest)
  2985.       highest = tsv->number;

  2986.   ++highest;
  2987.   for (ix = 0; VEC_iterate (tsv_s, tvariables, ix, tsv); ++ix)
  2988.     if (tsv->number == 0)
  2989.       tsv->number = highest++;

  2990.   free_uploaded_tsvs (uploaded_tsvs);
  2991. }

  2992. /* Parse the part of trace status syntax that is shared between
  2993.    the remote protocol and the trace file reader.  */

  2994. void
  2995. parse_trace_status (char *line, struct trace_status *ts)
  2996. {
  2997.   char *p = line, *p1, *p2, *p3, *p_temp;
  2998.   int end;
  2999.   ULONGEST val;

  3000.   ts->running_known = 1;
  3001.   ts->running = (*p++ == '1');
  3002.   ts->stop_reason = trace_stop_reason_unknown;
  3003.   xfree (ts->stop_desc);
  3004.   ts->stop_desc = NULL;
  3005.   ts->traceframe_count = -1;
  3006.   ts->traceframes_created = -1;
  3007.   ts->buffer_free = -1;
  3008.   ts->buffer_size = -1;
  3009.   ts->disconnected_tracing = 0;
  3010.   ts->circular_buffer = 0;
  3011.   xfree (ts->user_name);
  3012.   ts->user_name = NULL;
  3013.   xfree (ts->notes);
  3014.   ts->notes = NULL;
  3015.   ts->start_time = ts->stop_time = 0;

  3016.   while (*p++)
  3017.     {
  3018.       p1 = strchr (p, ':');
  3019.       if (p1 == NULL)
  3020.         error (_("Malformed trace status, at %s\n\
  3021. Status line: '%s'\n"), p, line);
  3022.       p3 = strchr (p, ';');
  3023.       if (p3 == NULL)
  3024.         p3 = p + strlen (p);
  3025.       if (strncmp (p, stop_reason_names[trace_buffer_full], p1 - p) == 0)
  3026.         {
  3027.           p = unpack_varlen_hex (++p1, &val);
  3028.           ts->stop_reason = trace_buffer_full;
  3029.         }
  3030.       else if (strncmp (p, stop_reason_names[trace_never_run], p1 - p) == 0)
  3031.         {
  3032.           p = unpack_varlen_hex (++p1, &val);
  3033.           ts->stop_reason = trace_never_run;
  3034.         }
  3035.       else if (strncmp (p, stop_reason_names[tracepoint_passcount],
  3036.                         p1 - p) == 0)
  3037.         {
  3038.           p = unpack_varlen_hex (++p1, &val);
  3039.           ts->stop_reason = tracepoint_passcount;
  3040.           ts->stopping_tracepoint = val;
  3041.         }
  3042.       else if (strncmp (p, stop_reason_names[tstop_command], p1 - p) == 0)
  3043.         {
  3044.           p2 = strchr (++p1, ':');
  3045.           if (!p2 || p2 > p3)
  3046.             {
  3047.               /*older style*/
  3048.               p2 = p1;
  3049.             }
  3050.           else if (p2 != p1)
  3051.             {
  3052.               ts->stop_desc = xmalloc (strlen (line));
  3053.               end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
  3054.               ts->stop_desc[end] = '\0';
  3055.             }
  3056.           else
  3057.             ts->stop_desc = xstrdup ("");

  3058.           p = unpack_varlen_hex (++p2, &val);
  3059.           ts->stop_reason = tstop_command;
  3060.         }
  3061.       else if (strncmp (p, stop_reason_names[trace_disconnected], p1 - p) == 0)
  3062.         {
  3063.           p = unpack_varlen_hex (++p1, &val);
  3064.           ts->stop_reason = trace_disconnected;
  3065.         }
  3066.       else if (strncmp (p, stop_reason_names[tracepoint_error], p1 - p) == 0)
  3067.         {
  3068.           p2 = strchr (++p1, ':');
  3069.           if (p2 != p1)
  3070.             {
  3071.               ts->stop_desc = xmalloc ((p2 - p1) / 2 + 1);
  3072.               end = hex2bin (p1, (gdb_byte *) ts->stop_desc, (p2 - p1) / 2);
  3073.               ts->stop_desc[end] = '\0';
  3074.             }
  3075.           else
  3076.             ts->stop_desc = xstrdup ("");

  3077.           p = unpack_varlen_hex (++p2, &val);
  3078.           ts->stopping_tracepoint = val;
  3079.           ts->stop_reason = tracepoint_error;
  3080.         }
  3081.       else if (strncmp (p, "tframes", p1 - p) == 0)
  3082.         {
  3083.           p = unpack_varlen_hex (++p1, &val);
  3084.           ts->traceframe_count = val;
  3085.         }
  3086.       else if (strncmp (p, "tcreated", p1 - p) == 0)
  3087.         {
  3088.           p = unpack_varlen_hex (++p1, &val);
  3089.           ts->traceframes_created = val;
  3090.         }
  3091.       else if (strncmp (p, "tfree", p1 - p) == 0)
  3092.         {
  3093.           p = unpack_varlen_hex (++p1, &val);
  3094.           ts->buffer_free = val;
  3095.         }
  3096.       else if (strncmp (p, "tsize", p1 - p) == 0)
  3097.         {
  3098.           p = unpack_varlen_hex (++p1, &val);
  3099.           ts->buffer_size = val;
  3100.         }
  3101.       else if (strncmp (p, "disconn", p1 - p) == 0)
  3102.         {
  3103.           p = unpack_varlen_hex (++p1, &val);
  3104.           ts->disconnected_tracing = val;
  3105.         }
  3106.       else if (strncmp (p, "circular", p1 - p) == 0)
  3107.         {
  3108.           p = unpack_varlen_hex (++p1, &val);
  3109.           ts->circular_buffer = val;
  3110.         }
  3111.       else if (strncmp (p, "starttime", p1 - p) == 0)
  3112.         {
  3113.           p = unpack_varlen_hex (++p1, &val);
  3114.           ts->start_time = val;
  3115.         }
  3116.       else if (strncmp (p, "stoptime", p1 - p) == 0)
  3117.         {
  3118.           p = unpack_varlen_hex (++p1, &val);
  3119.           ts->stop_time = val;
  3120.         }
  3121.       else if (strncmp (p, "username", p1 - p) == 0)
  3122.         {
  3123.           ++p1;
  3124.           ts->user_name = xmalloc (strlen (p) / 2);
  3125.           end = hex2bin (p1, (gdb_byte *) ts->user_name, (p3 - p1)  / 2);
  3126.           ts->user_name[end] = '\0';
  3127.           p = p3;
  3128.         }
  3129.       else if (strncmp (p, "notes", p1 - p) == 0)
  3130.         {
  3131.           ++p1;
  3132.           ts->notes = xmalloc (strlen (p) / 2);
  3133.           end = hex2bin (p1, (gdb_byte *) ts->notes, (p3 - p1) / 2);
  3134.           ts->notes[end] = '\0';
  3135.           p = p3;
  3136.         }
  3137.       else
  3138.         {
  3139.           /* Silently skip unknown optional info.  */
  3140.           p_temp = strchr (p1 + 1, ';');
  3141.           if (p_temp)
  3142.             p = p_temp;
  3143.           else
  3144.             /* Must be at the end.  */
  3145.             break;
  3146.         }
  3147.     }
  3148. }

  3149. void
  3150. parse_tracepoint_status (char *p, struct breakpoint *bp,
  3151.                          struct uploaded_tp *utp)
  3152. {
  3153.   ULONGEST uval;
  3154.   struct tracepoint *tp = (struct tracepoint *) bp;

  3155.   p = unpack_varlen_hex (p, &uval);
  3156.   if (tp)
  3157.     tp->base.hit_count += uval;
  3158.   else
  3159.     utp->hit_count += uval;
  3160.   p = unpack_varlen_hex (p + 1, &uval);
  3161.   if (tp)
  3162.     tp->traceframe_usage += uval;
  3163.   else
  3164.     utp->traceframe_usage += uval;
  3165.   /* Ignore any extra, allowing for future extensions.  */
  3166. }

  3167. /* Given a line of text defining a part of a tracepoint, parse it into
  3168.    an "uploaded tracepoint".  */

  3169. void
  3170. parse_tracepoint_definition (char *line, struct uploaded_tp **utpp)
  3171. {
  3172.   char *p;
  3173.   char piece;
  3174.   ULONGEST num, addr, step, pass, orig_size, xlen, start;
  3175.   int enabled, end;
  3176.   enum bptype type;
  3177.   char *cond, *srctype, *buf;
  3178.   struct uploaded_tp *utp = NULL;

  3179.   p = line;
  3180.   /* Both tracepoint and action definitions start with the same number
  3181.      and address sequence.  */
  3182.   piece = *p++;
  3183.   p = unpack_varlen_hex (p, &num);
  3184.   p++;  /* skip a colon */
  3185.   p = unpack_varlen_hex (p, &addr);
  3186.   p++;  /* skip a colon */
  3187.   if (piece == 'T')
  3188.     {
  3189.       enabled = (*p++ == 'E');
  3190.       p++;  /* skip a colon */
  3191.       p = unpack_varlen_hex (p, &step);
  3192.       p++;  /* skip a colon */
  3193.       p = unpack_varlen_hex (p, &pass);
  3194.       type = bp_tracepoint;
  3195.       cond = NULL;
  3196.       /* Thumb through optional fields.  */
  3197.       while (*p == ':')
  3198.         {
  3199.           p++;  /* skip a colon */
  3200.           if (*p == 'F')
  3201.             {
  3202.               type = bp_fast_tracepoint;
  3203.               p++;
  3204.               p = unpack_varlen_hex (p, &orig_size);
  3205.             }
  3206.           else if (*p == 'S')
  3207.             {
  3208.               type = bp_static_tracepoint;
  3209.               p++;
  3210.             }
  3211.           else if (*p == 'X')
  3212.             {
  3213.               p++;
  3214.               p = unpack_varlen_hex (p, &xlen);
  3215.               p++;  /* skip a comma */
  3216.               cond = (char *) xmalloc (2 * xlen + 1);
  3217.               strncpy (cond, p, 2 * xlen);
  3218.               cond[2 * xlen] = '\0';
  3219.               p += 2 * xlen;
  3220.             }
  3221.           else
  3222.             warning (_("Unrecognized char '%c' in tracepoint "
  3223.                        "definition, skipping rest"), *p);
  3224.         }
  3225.       utp = get_uploaded_tp (num, addr, utpp);
  3226.       utp->type = type;
  3227.       utp->enabled = enabled;
  3228.       utp->step = step;
  3229.       utp->pass = pass;
  3230.       utp->cond = cond;
  3231.     }
  3232.   else if (piece == 'A')
  3233.     {
  3234.       utp = get_uploaded_tp (num, addr, utpp);
  3235.       VEC_safe_push (char_ptr, utp->actions, xstrdup (p));
  3236.     }
  3237.   else if (piece == 'S')
  3238.     {
  3239.       utp = get_uploaded_tp (num, addr, utpp);
  3240.       VEC_safe_push (char_ptr, utp->step_actions, xstrdup (p));
  3241.     }
  3242.   else if (piece == 'Z')
  3243.     {
  3244.       /* Parse a chunk of source form definition.  */
  3245.       utp = get_uploaded_tp (num, addr, utpp);
  3246.       srctype = p;
  3247.       p = strchr (p, ':');
  3248.       p++;  /* skip a colon */
  3249.       p = unpack_varlen_hex (p, &start);
  3250.       p++;  /* skip a colon */
  3251.       p = unpack_varlen_hex (p, &xlen);
  3252.       p++;  /* skip a colon */

  3253.       buf = alloca (strlen (line));

  3254.       end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
  3255.       buf[end] = '\0';

  3256.       if (strncmp (srctype, "at:", strlen ("at:")) == 0)
  3257.         utp->at_string = xstrdup (buf);
  3258.       else if (strncmp (srctype, "cond:", strlen ("cond:")) == 0)
  3259.         utp->cond_string = xstrdup (buf);
  3260.       else if (strncmp (srctype, "cmd:", strlen ("cmd:")) == 0)
  3261.         VEC_safe_push (char_ptr, utp->cmd_strings, xstrdup (buf));
  3262.     }
  3263.   else if (piece == 'V')
  3264.     {
  3265.       utp = get_uploaded_tp (num, addr, utpp);

  3266.       parse_tracepoint_status (p, NULL, utp);
  3267.     }
  3268.   else
  3269.     {
  3270.       /* Don't error out, the target might be sending us optional
  3271.          info that we don't care about.  */
  3272.       warning (_("Unrecognized tracepoint piece '%c', ignoring"), piece);
  3273.     }
  3274. }

  3275. /* Convert a textual description of a trace state variable into an
  3276.    uploaded object.  */

  3277. void
  3278. parse_tsv_definition (char *line, struct uploaded_tsv **utsvp)
  3279. {
  3280.   char *p, *buf;
  3281.   ULONGEST num, initval, builtin;
  3282.   int end;
  3283.   struct uploaded_tsv *utsv = NULL;

  3284.   buf = alloca (strlen (line));

  3285.   p = line;
  3286.   p = unpack_varlen_hex (p, &num);
  3287.   p++; /* skip a colon */
  3288.   p = unpack_varlen_hex (p, &initval);
  3289.   p++; /* skip a colon */
  3290.   p = unpack_varlen_hex (p, &builtin);
  3291.   p++; /* skip a colon */
  3292.   end = hex2bin (p, (gdb_byte *) buf, strlen (p) / 2);
  3293.   buf[end] = '\0';

  3294.   utsv = get_uploaded_tsv (num, utsvp);
  3295.   utsv->initial_value = initval;
  3296.   utsv->builtin = builtin;
  3297.   utsv->name = xstrdup (buf);
  3298. }

  3299. void
  3300. free_current_marker (void *arg)
  3301. {
  3302.   struct static_tracepoint_marker **marker_p = arg;

  3303.   if (*marker_p != NULL)
  3304.     {
  3305.       release_static_tracepoint_marker (*marker_p);
  3306.       xfree (*marker_p);
  3307.     }
  3308.   else
  3309.     *marker_p = NULL;
  3310. }

  3311. /* Given a line of text defining a static tracepoint marker, parse it
  3312.    into a "static tracepoint marker" object.  Throws an error is
  3313.    parsing fails.  If PP is non-null, it points to one past the end of
  3314.    the parsed marker definition.  */

  3315. void
  3316. parse_static_tracepoint_marker_definition (char *line, char **pp,
  3317.                                            struct static_tracepoint_marker *marker)
  3318. {
  3319.   char *p, *endp;
  3320.   ULONGEST addr;
  3321.   int end;

  3322.   p = line;
  3323.   p = unpack_varlen_hex (p, &addr);
  3324.   p++;  /* skip a colon */

  3325.   marker->gdbarch = target_gdbarch ();
  3326.   marker->address = (CORE_ADDR) addr;

  3327.   endp = strchr (p, ':');
  3328.   if (endp == NULL)
  3329.     error (_("bad marker definition: %s"), line);

  3330.   marker->str_id = xmalloc (endp - p + 1);
  3331.   end = hex2bin (p, (gdb_byte *) marker->str_id, (endp - p + 1) / 2);
  3332.   marker->str_id[end] = '\0';

  3333.   p += 2 * end;
  3334.   p++;  /* skip a colon */

  3335.   marker->extra = xmalloc (strlen (p) + 1);
  3336.   end = hex2bin (p, (gdb_byte *) marker->extra, strlen (p) / 2);
  3337.   marker->extra[end] = '\0';

  3338.   if (pp)
  3339.     *pp = p;
  3340. }

  3341. /* Release a static tracepoint marker's contents.  Note that the
  3342.    object itself isn't released here.  There objects are usually on
  3343.    the stack.  */

  3344. void
  3345. release_static_tracepoint_marker (struct static_tracepoint_marker *marker)
  3346. {
  3347.   xfree (marker->str_id);
  3348.   marker->str_id = NULL;
  3349. }

  3350. /* Print MARKER to gdb_stdout.  */

  3351. static void
  3352. print_one_static_tracepoint_marker (int count,
  3353.                                     struct static_tracepoint_marker *marker)
  3354. {
  3355.   struct command_line *l;
  3356.   struct symbol *sym;

  3357.   char wrap_indent[80];
  3358.   char extra_field_indent[80];
  3359.   struct ui_out *uiout = current_uiout;
  3360.   struct cleanup *bkpt_chain;
  3361.   VEC(breakpoint_p) *tracepoints;

  3362.   struct symtab_and_line sal;

  3363.   init_sal (&sal);

  3364.   sal.pc = marker->address;

  3365.   tracepoints = static_tracepoints_here (marker->address);

  3366.   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "marker");

  3367.   /* A counter field to help readability.  This is not a stable
  3368.      identifier!  */
  3369.   ui_out_field_int (uiout, "count", count);

  3370.   ui_out_field_string (uiout, "marker-id", marker->str_id);

  3371.   ui_out_field_fmt (uiout, "enabled", "%c",
  3372.                     !VEC_empty (breakpoint_p, tracepoints) ? 'y' : 'n');
  3373.   ui_out_spaces (uiout, 2);

  3374.   strcpy (wrap_indent, "                                   ");

  3375.   if (gdbarch_addr_bit (marker->gdbarch) <= 32)
  3376.     strcat (wrap_indent, "           ");
  3377.   else
  3378.     strcat (wrap_indent, "                   ");

  3379.   strcpy (extra_field_indent, "         ");

  3380.   ui_out_field_core_addr (uiout, "addr", marker->gdbarch, marker->address);

  3381.   sal = find_pc_line (marker->address, 0);
  3382.   sym = find_pc_sect_function (marker->address, NULL);
  3383.   if (sym)
  3384.     {
  3385.       ui_out_text (uiout, "in ");
  3386.       ui_out_field_string (uiout, "func",
  3387.                            SYMBOL_PRINT_NAME (sym));
  3388.       ui_out_wrap_hint (uiout, wrap_indent);
  3389.       ui_out_text (uiout, " at ");
  3390.     }
  3391.   else
  3392.     ui_out_field_skip (uiout, "func");

  3393.   if (sal.symtab != NULL)
  3394.     {
  3395.       ui_out_field_string (uiout, "file",
  3396.                            symtab_to_filename_for_display (sal.symtab));
  3397.       ui_out_text (uiout, ":");

  3398.       if (ui_out_is_mi_like_p (uiout))
  3399.         {
  3400.           const char *fullname = symtab_to_fullname (sal.symtab);

  3401.           ui_out_field_string (uiout, "fullname", fullname);
  3402.         }
  3403.       else
  3404.         ui_out_field_skip (uiout, "fullname");

  3405.       ui_out_field_int (uiout, "line", sal.line);
  3406.     }
  3407.   else
  3408.     {
  3409.       ui_out_field_skip (uiout, "fullname");
  3410.       ui_out_field_skip (uiout, "line");
  3411.     }

  3412.   ui_out_text (uiout, "\n");
  3413.   ui_out_text (uiout, extra_field_indent);
  3414.   ui_out_text (uiout, _("Data: \""));
  3415.   ui_out_field_string (uiout, "extra-data", marker->extra);
  3416.   ui_out_text (uiout, "\"\n");

  3417.   if (!VEC_empty (breakpoint_p, tracepoints))
  3418.     {
  3419.       struct cleanup *cleanup_chain;
  3420.       int ix;
  3421.       struct breakpoint *b;

  3422.       cleanup_chain = make_cleanup_ui_out_tuple_begin_end (uiout,
  3423.                                                            "tracepoints-at");

  3424.       ui_out_text (uiout, extra_field_indent);
  3425.       ui_out_text (uiout, _("Probed by static tracepoints: "));
  3426.       for (ix = 0; VEC_iterate(breakpoint_p, tracepoints, ix, b); ix++)
  3427.         {
  3428.           if (ix > 0)
  3429.             ui_out_text (uiout, ", ");
  3430.           ui_out_text (uiout, "#");
  3431.           ui_out_field_int (uiout, "tracepoint-id", b->number);
  3432.         }

  3433.       do_cleanups (cleanup_chain);

  3434.       if (ui_out_is_mi_like_p (uiout))
  3435.         ui_out_field_int (uiout, "number-of-tracepoints",
  3436.                           VEC_length(breakpoint_p, tracepoints));
  3437.       else
  3438.         ui_out_text (uiout, "\n");
  3439.     }
  3440.   VEC_free (breakpoint_p, tracepoints);

  3441.   do_cleanups (bkpt_chain);
  3442. }

  3443. static void
  3444. info_static_tracepoint_markers_command (char *arg, int from_tty)
  3445. {
  3446.   VEC(static_tracepoint_marker_p) *markers;
  3447.   struct cleanup *old_chain;
  3448.   struct static_tracepoint_marker *marker;
  3449.   struct ui_out *uiout = current_uiout;
  3450.   int i;

  3451.   /* We don't have to check target_can_use_agent and agent's capability on
  3452.      static tracepoint here, in order to be compatible with older GDBserver.
  3453.      We don't check USE_AGENT is true or not, because static tracepoints
  3454.      don't work without in-process agent, so we don't bother users to type
  3455.      `set agent on' when to use static tracepoint.  */

  3456.   old_chain
  3457.     = make_cleanup_ui_out_table_begin_end (uiout, 5, -1,
  3458.                                            "StaticTracepointMarkersTable");

  3459.   ui_out_table_header (uiout, 7, ui_left, "counter", "Cnt");

  3460.   ui_out_table_header (uiout, 40, ui_left, "marker-id", "ID");

  3461.   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");
  3462.   if (gdbarch_addr_bit (target_gdbarch ()) <= 32)
  3463.     ui_out_table_header (uiout, 10, ui_left, "addr", "Address");
  3464.   else
  3465.     ui_out_table_header (uiout, 18, ui_left, "addr", "Address");
  3466.   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");

  3467.   ui_out_table_body (uiout);

  3468.   markers = target_static_tracepoint_markers_by_strid (NULL);
  3469.   make_cleanup (VEC_cleanup (static_tracepoint_marker_p), &markers);

  3470.   for (i = 0;
  3471.        VEC_iterate (static_tracepoint_marker_p,
  3472.                     markers, i, marker);
  3473.        i++)
  3474.     {
  3475.       print_one_static_tracepoint_marker (i + 1, marker);
  3476.       release_static_tracepoint_marker (marker);
  3477.     }

  3478.   do_cleanups (old_chain);
  3479. }

  3480. /* The $_sdata convenience variable is a bit special.  We don't know
  3481.    for sure type of the value until we actually have a chance to fetch
  3482.    the data --- the size of the object depends on what has been
  3483.    collected.  We solve this by making $_sdata be an internalvar that
  3484.    creates a new value on access.  */

  3485. /* Return a new value with the correct type for the sdata object of
  3486.    the current trace frame.  Return a void value if there's no object
  3487.    available.  */

  3488. static struct value *
  3489. sdata_make_value (struct gdbarch *gdbarch, struct internalvar *var,
  3490.                   void *ignore)
  3491. {
  3492.   LONGEST size;
  3493.   gdb_byte *buf;

  3494.   /* We need to read the whole object before we know its size.  */
  3495.   size = target_read_alloc (&current_target,
  3496.                             TARGET_OBJECT_STATIC_TRACE_DATA,
  3497.                             NULL, &buf);
  3498.   if (size >= 0)
  3499.     {
  3500.       struct value *v;
  3501.       struct type *type;

  3502.       type = init_vector_type (builtin_type (gdbarch)->builtin_true_char,
  3503.                                size);
  3504.       v = allocate_value (type);
  3505.       memcpy (value_contents_raw (v), buf, size);
  3506.       xfree (buf);
  3507.       return v;
  3508.     }
  3509.   else
  3510.     return allocate_value (builtin_type (gdbarch)->builtin_void);
  3511. }

  3512. #if !defined(HAVE_LIBEXPAT)

  3513. struct traceframe_info *
  3514. parse_traceframe_info (const char *tframe_info)
  3515. {
  3516.   static int have_warned;

  3517.   if (!have_warned)
  3518.     {
  3519.       have_warned = 1;
  3520.       warning (_("Can not parse XML trace frame info; XML support "
  3521.                  "was disabled at compile time"));
  3522.     }

  3523.   return NULL;
  3524. }

  3525. #else /* HAVE_LIBEXPAT */

  3526. #include "xml-support.h"

  3527. /* Handle the start of a <memory> element.  */

  3528. static void
  3529. traceframe_info_start_memory (struct gdb_xml_parser *parser,
  3530.                               const struct gdb_xml_element *element,
  3531.                               void *user_data, VEC(gdb_xml_value_s) *attributes)
  3532. {
  3533.   struct traceframe_info *info = user_data;
  3534.   struct mem_range *r = VEC_safe_push (mem_range_s, info->memory, NULL);
  3535.   ULONGEST *start_p, *length_p;

  3536.   start_p = xml_find_attribute (attributes, "start")->value;
  3537.   length_p = xml_find_attribute (attributes, "length")->value;

  3538.   r->start = *start_p;
  3539.   r->length = *length_p;
  3540. }

  3541. /* Handle the start of a <tvar> element.  */

  3542. static void
  3543. traceframe_info_start_tvar (struct gdb_xml_parser *parser,
  3544.                              const struct gdb_xml_element *element,
  3545.                              void *user_data,
  3546.                              VEC(gdb_xml_value_s) *attributes)
  3547. {
  3548.   struct traceframe_info *info = user_data;
  3549.   const char *id_attrib = xml_find_attribute (attributes, "id")->value;
  3550.   int id = gdb_xml_parse_ulongest (parser, id_attrib);

  3551.   VEC_safe_push (int, info->tvars, id);
  3552. }

  3553. /* Discard the constructed trace frame info (if an error occurs).  */

  3554. static void
  3555. free_result (void *p)
  3556. {
  3557.   struct traceframe_info *result = p;

  3558.   free_traceframe_info (result);
  3559. }

  3560. /* The allowed elements and attributes for an XML memory map.  */

  3561. static const struct gdb_xml_attribute memory_attributes[] = {
  3562.   { "start", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
  3563.   { "length", GDB_XML_AF_NONE, gdb_xml_parse_attr_ulongest, NULL },
  3564.   { NULL, GDB_XML_AF_NONE, NULL, NULL }
  3565. };

  3566. static const struct gdb_xml_attribute tvar_attributes[] = {
  3567.   { "id", GDB_XML_AF_NONE, NULL, NULL },
  3568.   { NULL, GDB_XML_AF_NONE, NULL, NULL }
  3569. };

  3570. static const struct gdb_xml_element traceframe_info_children[] = {
  3571.   { "memory", memory_attributes, NULL,
  3572.     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
  3573.     traceframe_info_start_memory, NULL },
  3574.   { "tvar", tvar_attributes, NULL,
  3575.     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
  3576.     traceframe_info_start_tvar, NULL },
  3577.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  3578. };

  3579. static const struct gdb_xml_element traceframe_info_elements[] = {
  3580.   { "traceframe-info", NULL, traceframe_info_children, GDB_XML_EF_NONE,
  3581.     NULL, NULL },
  3582.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  3583. };

  3584. /* Parse a traceframe-info XML document.  */

  3585. struct traceframe_info *
  3586. parse_traceframe_info (const char *tframe_info)
  3587. {
  3588.   struct traceframe_info *result;
  3589.   struct cleanup *back_to;

  3590.   result = XCNEW (struct traceframe_info);
  3591.   back_to = make_cleanup (free_result, result);

  3592.   if (gdb_xml_parse_quick (_("trace frame info"),
  3593.                            "traceframe-info.dtd", traceframe_info_elements,
  3594.                            tframe_info, result) == 0)
  3595.     {
  3596.       /* Parsed successfully, keep the result.  */
  3597.       discard_cleanups (back_to);

  3598.       return result;
  3599.     }

  3600.   do_cleanups (back_to);
  3601.   return NULL;
  3602. }

  3603. #endif /* HAVE_LIBEXPAT */

  3604. /* Returns the traceframe_info object for the current traceframe.
  3605.    This is where we avoid re-fetching the object from the target if we
  3606.    already have it cached.  */

  3607. struct traceframe_info *
  3608. get_traceframe_info (void)
  3609. {
  3610.   if (traceframe_info == NULL)
  3611.     traceframe_info = target_traceframe_info ();

  3612.   return traceframe_info;
  3613. }

  3614. /* If the target supports the query, return in RESULT the set of
  3615.    collected memory in the current traceframe, found within the LEN
  3616.    bytes range starting at MEMADDR.  Returns true if the target
  3617.    supports the query, otherwise returns false, and RESULT is left
  3618.    undefined.  */

  3619. int
  3620. traceframe_available_memory (VEC(mem_range_s) **result,
  3621.                              CORE_ADDR memaddr, ULONGEST len)
  3622. {
  3623.   struct traceframe_info *info = get_traceframe_info ();

  3624.   if (info != NULL)
  3625.     {
  3626.       struct mem_range *r;
  3627.       int i;

  3628.       *result = NULL;

  3629.       for (i = 0; VEC_iterate (mem_range_s, info->memory, i, r); i++)
  3630.         if (mem_ranges_overlap (r->start, r->length, memaddr, len))
  3631.           {
  3632.             ULONGEST lo1, hi1, lo2, hi2;
  3633.             struct mem_range *nr;

  3634.             lo1 = memaddr;
  3635.             hi1 = memaddr + len;

  3636.             lo2 = r->start;
  3637.             hi2 = r->start + r->length;

  3638.             nr = VEC_safe_push (mem_range_s, *result, NULL);

  3639.             nr->start = max (lo1, lo2);
  3640.             nr->length = min (hi1, hi2) - nr->start;
  3641.           }

  3642.       normalize_mem_ranges (*result);
  3643.       return 1;
  3644.     }

  3645.   return 0;
  3646. }

  3647. /* Implementation of `sdata' variable.  */

  3648. static const struct internalvar_funcs sdata_funcs =
  3649. {
  3650.   sdata_make_value,
  3651.   NULL,
  3652.   NULL
  3653. };

  3654. /* module initialization */
  3655. void
  3656. _initialize_tracepoint (void)
  3657. {
  3658.   struct cmd_list_element *c;

  3659.   /* Explicitly create without lookup, since that tries to create a
  3660.      value with a void typed value, and when we get here, gdbarch
  3661.      isn't initialized yet.  At this point, we're quite sure there
  3662.      isn't another convenience variable of the same name.  */
  3663.   create_internalvar_type_lazy ("_sdata", &sdata_funcs, NULL);

  3664.   traceframe_number = -1;
  3665.   tracepoint_number = -1;

  3666.   add_info ("scope", scope_info,
  3667.             _("List the variables local to a scope"));

  3668.   add_cmd ("tracepoints", class_trace, NULL,
  3669.            _("Tracing of program execution without stopping the program."),
  3670.            &cmdlist);

  3671.   add_com ("tdump", class_trace, trace_dump_command,
  3672.            _("Print everything collected at the current tracepoint."));

  3673.   c = add_com ("tvariable", class_trace, trace_variable_command,_("\
  3674. Define a trace state variable.\n\
  3675. Argument is a $-prefixed name, optionally followed\n\
  3676. by '=' and an expression that sets the initial value\n\
  3677. at the start of tracing."));
  3678.   set_cmd_completer (c, expression_completer);

  3679.   add_cmd ("tvariable", class_trace, delete_trace_variable_command, _("\
  3680. Delete one or more trace state variables.\n\
  3681. Arguments are the names of the variables to delete.\n\
  3682. If no arguments are supplied, delete all variables."), &deletelist);
  3683.   /* FIXME add a trace variable completer.  */

  3684.   add_info ("tvariables", tvariables_info, _("\
  3685. Status of trace state variables and their values.\n\
  3686. "));

  3687.   add_info ("static-tracepoint-markers",
  3688.             info_static_tracepoint_markers_command, _("\
  3689. List target static tracepoints markers.\n\
  3690. "));

  3691.   add_prefix_cmd ("tfind", class_trace, trace_find_command, _("\
  3692. Select a trace frame;\n\
  3693. No argument means forward by one frame; '-' means backward by one frame."),
  3694.                   &tfindlist, "tfind ", 1, &cmdlist);

  3695.   add_cmd ("outside", class_trace, trace_find_outside_command, _("\
  3696. Select a trace frame whose PC is outside the given range (exclusive).\n\
  3697. Usage: tfind outside addr1, addr2"),
  3698.            &tfindlist);

  3699.   add_cmd ("range", class_trace, trace_find_range_command, _("\
  3700. Select a trace frame whose PC is in the given range (inclusive).\n\
  3701. Usage: tfind range addr1,addr2"),
  3702.            &tfindlist);

  3703.   add_cmd ("line", class_trace, trace_find_line_command, _("\
  3704. Select a trace frame by source line.\n\
  3705. Argument can be a line number (with optional source file),\n\
  3706. a function name, or '*' followed by an address.\n\
  3707. Default argument is 'the next source line that was traced'."),
  3708.            &tfindlist);

  3709.   add_cmd ("tracepoint", class_trace, trace_find_tracepoint_command, _("\
  3710. Select a trace frame by tracepoint number.\n\
  3711. Default is the tracepoint for the current trace frame."),
  3712.            &tfindlist);

  3713.   add_cmd ("pc", class_trace, trace_find_pc_command, _("\
  3714. Select a trace frame by PC.\n\
  3715. Default is the current PC, or the PC of the current trace frame."),
  3716.            &tfindlist);

  3717.   add_cmd ("end", class_trace, trace_find_end_command, _("\
  3718. De-select any trace frame and resume 'live' debugging."),
  3719.            &tfindlist);

  3720.   add_alias_cmd ("none", "end", class_trace, 0, &tfindlist);

  3721.   add_cmd ("start", class_trace, trace_find_start_command,
  3722.            _("Select the first trace frame in the trace buffer."),
  3723.            &tfindlist);

  3724.   add_com ("tstatus", class_trace, trace_status_command,
  3725.            _("Display the status of the current trace data collection."));

  3726.   add_com ("tstop", class_trace, trace_stop_command, _("\
  3727. Stop trace data collection.\n\
  3728. Usage: tstop [ <notes> ... ]\n\
  3729. Any arguments supplied are recorded with the trace as a stop reason and\n\
  3730. reported by tstatus (if the target supports trace notes)."));

  3731.   add_com ("tstart", class_trace, trace_start_command, _("\
  3732. Start trace data collection.\n\
  3733. Usage: tstart [ <notes> ... ]\n\
  3734. Any arguments supplied are recorded with the trace as a note and\n\
  3735. reported by tstatus (if the target supports trace notes)."));

  3736.   add_com ("end", class_trace, end_actions_pseudocommand, _("\
  3737. Ends a list of commands or actions.\n\
  3738. Several GDB commands allow you to enter a list of commands or actions.\n\
  3739. Entering \"end\" on a line by itself is the normal way to terminate\n\
  3740. such a list.\n\n\
  3741. Note: the \"end\" command cannot be used at the gdb prompt."));

  3742.   add_com ("while-stepping", class_trace, while_stepping_pseudocommand, _("\
  3743. Specify single-stepping behavior at a tracepoint.\n\
  3744. Argument is number of instructions to trace in single-step mode\n\
  3745. following the tracepoint.  This command is normally followed by\n\
  3746. one or more \"collect\" commands, to specify what to collect\n\
  3747. while single-stepping.\n\n\
  3748. Note: this command can only be used in a tracepoint \"actions\" list."));

  3749.   add_com_alias ("ws", "while-stepping", class_alias, 0);
  3750.   add_com_alias ("stepping", "while-stepping", class_alias, 0);

  3751.   add_com ("collect", class_trace, collect_pseudocommand, _("\
  3752. Specify one or more data items to be collected at a tracepoint.\n\
  3753. Accepts a comma-separated list of (one or more) expressions.  GDB will\n\
  3754. collect all data (variables, registers) referenced by that expression.\n\
  3755. Also accepts the following special arguments:\n\
  3756.     $regs   -- all registers.\n\
  3757.     $args   -- all function arguments.\n\
  3758.     $locals -- all variables local to the block/function scope.\n\
  3759.     $_sdata -- static tracepoint data (ignored for non-static tracepoints).\n\
  3760. Note: this command can only be used in a tracepoint \"actions\" list."));

  3761.   add_com ("teval", class_trace, teval_pseudocommand, _("\
  3762. Specify one or more expressions to be evaluated at a tracepoint.\n\
  3763. Accepts a comma-separated list of (one or more) expressions.\n\
  3764. The result of each evaluation will be discarded.\n\
  3765. Note: this command can only be used in a tracepoint \"actions\" list."));

  3766.   add_com ("actions", class_trace, trace_actions_command, _("\
  3767. Specify the actions to be taken at a tracepoint.\n\
  3768. Tracepoint actions may include collecting of specified data,\n\
  3769. single-stepping, or enabling/disabling other tracepoints,\n\
  3770. depending on target's capabilities."));

  3771.   default_collect = xstrdup ("");
  3772.   add_setshow_string_cmd ("default-collect", class_trace,
  3773.                           &default_collect, _("\
  3774. Set the list of expressions to collect by default"), _("\
  3775. Show the list of expressions to collect by default"), NULL,
  3776.                           NULL, NULL,
  3777.                           &setlist, &showlist);

  3778.   add_setshow_boolean_cmd ("disconnected-tracing", no_class,
  3779.                            &disconnected_tracing, _("\
  3780. Set whether tracing continues after GDB disconnects."), _("\
  3781. Show whether tracing continues after GDB disconnects."), _("\
  3782. Use this to continue a tracing run even if GDB disconnects\n\
  3783. or detaches from the target.  You can reconnect later and look at\n\
  3784. trace data collected in the meantime."),
  3785.                            set_disconnected_tracing,
  3786.                            NULL,
  3787.                            &setlist,
  3788.                            &showlist);

  3789.   add_setshow_boolean_cmd ("circular-trace-buffer", no_class,
  3790.                            &circular_trace_buffer, _("\
  3791. Set target's use of circular trace buffer."), _("\
  3792. Show target's use of circular trace buffer."), _("\
  3793. Use this to make the trace buffer into a circular buffer,\n\
  3794. which will discard traceframes (oldest first) instead of filling\n\
  3795. up and stopping the trace run."),
  3796.                            set_circular_trace_buffer,
  3797.                            NULL,
  3798.                            &setlist,
  3799.                            &showlist);

  3800.   add_setshow_zuinteger_unlimited_cmd ("trace-buffer-size", no_class,
  3801.                                        &trace_buffer_size, _("\
  3802. Set requested size of trace buffer."), _("\
  3803. Show requested size of trace buffer."), _("\
  3804. Use this to choose a size for the trace buffer.  Some targets\n\
  3805. may have fixed or limited buffer sizes.  Specifying \"unlimited\" or -1\n\
  3806. disables any attempt to set the buffer size and lets the target choose."),
  3807.                                        set_trace_buffer_size, NULL,
  3808.                                        &setlist, &showlist);

  3809.   add_setshow_string_cmd ("trace-user", class_trace,
  3810.                           &trace_user, _("\
  3811. Set the user name to use for current and future trace runs"), _("\
  3812. Show the user name to use for current and future trace runs"), NULL,
  3813.                           set_trace_user, NULL,
  3814.                           &setlist, &showlist);

  3815.   add_setshow_string_cmd ("trace-notes", class_trace,
  3816.                           &trace_notes, _("\
  3817. Set notes string to use for current and future trace runs"), _("\
  3818. Show the notes string to use for current and future trace runs"), NULL,
  3819.                           set_trace_notes, NULL,
  3820.                           &setlist, &showlist);

  3821.   add_setshow_string_cmd ("trace-stop-notes", class_trace,
  3822.                           &trace_stop_notes, _("\
  3823. Set notes string to use for future tstop commands"), _("\
  3824. Show the notes string to use for future tstop commands"), NULL,
  3825.                           set_trace_stop_notes, NULL,
  3826.                           &setlist, &showlist);
  3827. }