OpenCores
URL https://opencores.org/ocsvn/openrisc_me/openrisc_me/trunk

Subversion Repositories openrisc_me

[/] [openrisc/] [trunk/] [gnu-src/] [gdb-7.2/] [gdb/] [breakpoint.c] - Rev 395

Go to most recent revision | Compare with Previous | Blame | View Log

/* Everything about breakpoints, for GDB.
 
   Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
   1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
   2008, 2009, 2010 Free Software Foundation, Inc.
 
   This file is part of GDB.
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
 
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
#include "defs.h"
#include "arch-utils.h"
#include <ctype.h>
#include "hashtab.h"
#include "symtab.h"
#include "frame.h"
#include "breakpoint.h"
#include "tracepoint.h"
#include "gdbtypes.h"
#include "expression.h"
#include "gdbcore.h"
#include "gdbcmd.h"
#include "value.h"
#include "command.h"
#include "inferior.h"
#include "gdbthread.h"
#include "target.h"
#include "language.h"
#include "gdb_string.h"
#include "demangle.h"
#include "annotate.h"
#include "symfile.h"
#include "objfiles.h"
#include "source.h"
#include "linespec.h"
#include "completer.h"
#include "gdb.h"
#include "ui-out.h"
#include "cli/cli-script.h"
#include "gdb_assert.h"
#include "block.h"
#include "solib.h"
#include "solist.h"
#include "observer.h"
#include "exceptions.h"
#include "memattr.h"
#include "ada-lang.h"
#include "top.h"
#include "wrapper.h"
#include "valprint.h"
#include "jit.h"
#include "xml-syscall.h"
#include "parser-defs.h"
 
/* readline include files */
#include "readline/readline.h"
#include "readline/history.h"
 
/* readline defines this.  */
#undef savestring
 
#include "mi/mi-common.h"
 
/* Arguments to pass as context to some catch command handlers.  */
#define CATCH_PERMANENT ((void *) (uintptr_t) 0)
#define CATCH_TEMPORARY ((void *) (uintptr_t) 1)
 
/* Prototypes for local functions. */
 
static void enable_delete_command (char *, int);
 
static void enable_once_command (char *, int);
 
static void disable_command (char *, int);
 
static void enable_command (char *, int);
 
static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
						      void *),
				    void *);
 
static void ignore_command (char *, int);
 
static int breakpoint_re_set_one (void *);
 
static void clear_command (char *, int);
 
static void catch_command (char *, int);
 
static void watch_command (char *, int);
 
static int can_use_hardware_watchpoint (struct value *);
 
static void break_command_1 (char *, int, int);
 
static void mention (struct breakpoint *);
 
/* This function is used in gdbtk sources and thus can not be made static.  */
struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
					      struct symtab_and_line,
					      enum bptype);
 
static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
 
static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
					    CORE_ADDR bpaddr,
                                            enum bptype bptype);
 
static void describe_other_breakpoints (struct gdbarch *,
					struct program_space *, CORE_ADDR,
					struct obj_section *, int);
 
static int breakpoint_address_match (struct address_space *aspace1,
				     CORE_ADDR addr1,
				     struct address_space *aspace2,
				     CORE_ADDR addr2);
 
static int watchpoint_locations_match (struct bp_location *loc1,
				       struct bp_location *loc2);
 
static void breakpoints_info (char *, int);
 
static void watchpoints_info (char *, int);
 
static int breakpoint_1 (int, int, int (*) (const struct breakpoint *));
 
static bpstat bpstat_alloc (const struct bp_location *, bpstat);
 
static int breakpoint_cond_eval (void *);
 
static void cleanup_executing_breakpoints (void *);
 
static void commands_command (char *, int);
 
static void condition_command (char *, int);
 
static int get_number_trailer (char **, int);
 
typedef enum
  {
    mark_inserted,
    mark_uninserted
  }
insertion_state_t;
 
static int remove_breakpoint (struct bp_location *, insertion_state_t);
static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
 
static enum print_stop_action print_it_typical (bpstat);
 
static enum print_stop_action print_bp_stop_message (bpstat bs);
 
static int watchpoint_check (void *);
 
static void maintenance_info_breakpoints (char *, int);
 
static int hw_breakpoint_used_count (void);
 
static int hw_watchpoint_used_count (enum bptype, int *);
 
static void hbreak_command (char *, int);
 
static void thbreak_command (char *, int);
 
static void watch_command_1 (char *, int, int);
 
static void rwatch_command (char *, int);
 
static void awatch_command (char *, int);
 
static void do_enable_breakpoint (struct breakpoint *, enum bpdisp);
 
static void stop_command (char *arg, int from_tty);
 
static void stopin_command (char *arg, int from_tty);
 
static void stopat_command (char *arg, int from_tty);
 
static char *ep_parse_optional_if_clause (char **arg);
 
static void catch_exception_command_1 (enum exception_event_kind ex_event, 
				       char *arg, int tempflag, int from_tty);
 
static void tcatch_command (char *arg, int from_tty);
 
static void ep_skip_leading_whitespace (char **s);
 
static void detach_single_step_breakpoints (void);
 
static int single_step_breakpoint_inserted_here_p (struct address_space *,
						   CORE_ADDR pc);
 
static void free_bp_location (struct bp_location *loc);
 
static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
 
static void update_global_location_list (int);
 
static void update_global_location_list_nothrow (int);
 
static int bpstat_remove_bp_location_callback (struct thread_info *th,
					       void *data);
 
static int is_hardware_watchpoint (const struct breakpoint *bpt);
 
static int is_watchpoint (const struct breakpoint *bpt);
 
static void insert_breakpoint_locations (void);
 
static int syscall_catchpoint_p (struct breakpoint *b);
 
static void tracepoints_info (char *, int);
 
static void delete_trace_command (char *, int);
 
static void enable_trace_command (char *, int);
 
static void disable_trace_command (char *, int);
 
static void trace_pass_command (char *, int);
 
/* Assuming we're creating a static tracepoint, does S look like a
   static tracepoint marker spec ("-m MARKER_ID")?  */
#define is_marker_spec(s)						\
  (strncmp (s, "-m", 2) == 0 && ((s)[2] == ' ' || (s)[2] == '\t'))
 
/* A reference-counted struct command_line.  This lets multiple
   breakpoints share a single command list.  */
struct counted_command_line
{
  /* The reference count.  */
  int refc;
 
  /* The command list.  */
  struct command_line *commands;
};
 
struct command_line *
breakpoint_commands (struct breakpoint *b)
{
  return b->commands ? b->commands->commands : NULL;
}
 
/* Flag indicating that a command has proceeded the inferior past the
   current breakpoint.  */
 
static int breakpoint_proceeded;
 
static const char *
bpdisp_text (enum bpdisp disp)
{
  /* NOTE: the following values are a part of MI protocol and represent
     values of 'disp' field returned when inferior stops at a breakpoint.  */
  static char *bpdisps[] = {"del", "dstp", "dis", "keep"};
 
  return bpdisps[(int) disp];
}
 
/* Prototypes for exported functions. */
/* If FALSE, gdb will not use hardware support for watchpoints, even
   if such is available. */
static int can_use_hw_watchpoints;
 
static void
show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
			     struct cmd_list_element *c,
			     const char *value)
{
  fprintf_filtered (file, _("\
Debugger's willingness to use watchpoint hardware is %s.\n"),
		    value);
}
 
/* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
   If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
   for unrecognized breakpoint locations.  
   If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
static enum auto_boolean pending_break_support;
static void
show_pending_break_support (struct ui_file *file, int from_tty,
			    struct cmd_list_element *c,
			    const char *value)
{
  fprintf_filtered (file, _("\
Debugger's behavior regarding pending breakpoints is %s.\n"),
		    value);
}
 
/* If 1, gdb will automatically use hardware breakpoints for breakpoints
   set with "break" but falling in read-only memory. 
   If 0, gdb will warn about such breakpoints, but won't automatically
   use hardware breakpoints.  */
static int automatic_hardware_breakpoints;
static void
show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
				     struct cmd_list_element *c,
				     const char *value)
{
  fprintf_filtered (file, _("\
Automatic usage of hardware breakpoints is %s.\n"),
		    value);
}
 
/* If on, gdb will keep breakpoints inserted even as inferior is
   stopped, and immediately insert any new breakpoints.  If off, gdb
   will insert breakpoints into inferior only when resuming it, and
   will remove breakpoints upon stop.  If auto, GDB will behave as ON
   if in non-stop mode, and as OFF if all-stop mode.*/
 
static const char always_inserted_auto[] = "auto";
static const char always_inserted_on[] = "on";
static const char always_inserted_off[] = "off";
static const char *always_inserted_enums[] = {
  always_inserted_auto,
  always_inserted_off,
  always_inserted_on,
  NULL
};
static const char *always_inserted_mode = always_inserted_auto;
static void
show_always_inserted_mode (struct ui_file *file, int from_tty,
		     struct cmd_list_element *c, const char *value)
{
  if (always_inserted_mode == always_inserted_auto)
    fprintf_filtered (file, _("\
Always inserted breakpoint mode is %s (currently %s).\n"),
		      value,
		      breakpoints_always_inserted_mode () ? "on" : "off");
  else
    fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"), value);
}
 
int
breakpoints_always_inserted_mode (void)
{
  return (always_inserted_mode == always_inserted_on
	  || (always_inserted_mode == always_inserted_auto && non_stop));
}
 
void _initialize_breakpoint (void);
 
/* Are we executing breakpoint commands?  */
static int executing_breakpoint_commands;
 
/* Are overlay event breakpoints enabled? */
static int overlay_events_enabled;
 
/* Walk the following statement or block through all breakpoints.
   ALL_BREAKPOINTS_SAFE does so even if the statment deletes the current
   breakpoint.  */
 
#define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
 
#define ALL_BREAKPOINTS_SAFE(B,TMP)	\
	for (B = breakpoint_chain;	\
	     B ? (TMP=B->next, 1): 0;	\
	     B = TMP)
 
/* Similar iterator for the low-level breakpoints.  SAFE variant is not
   provided so update_global_location_list must not be called while executing
   the block of ALL_BP_LOCATIONS.  */
 
#define ALL_BP_LOCATIONS(B,BP_TMP)					\
	for (BP_TMP = bp_location;					\
	     BP_TMP < bp_location + bp_location_count && (B = *BP_TMP);	\
	     BP_TMP++)
 
/* Iterator for tracepoints only.  */
 
#define ALL_TRACEPOINTS(B)  \
  for (B = breakpoint_chain; B; B = B->next)  \
    if (is_tracepoint (B))
 
/* Chains of all breakpoints defined.  */
 
struct breakpoint *breakpoint_chain;
 
/* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
 
static struct bp_location **bp_location;
 
/* Number of elements of BP_LOCATION.  */
 
static unsigned bp_location_count;
 
/* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and ADDRESS
   for the current elements of BP_LOCATION which get a valid result from
   bp_location_has_shadow.  You can use it for roughly limiting the subrange of
   BP_LOCATION to scan for shadow bytes for an address you need to read.  */
 
static CORE_ADDR bp_location_placed_address_before_address_max;
 
/* Maximum offset plus alignment between
   bp_target_info.PLACED_ADDRESS + bp_target_info.SHADOW_LEN and ADDRESS for
   the current elements of BP_LOCATION which get a valid result from
   bp_location_has_shadow.  You can use it for roughly limiting the subrange of
   BP_LOCATION to scan for shadow bytes for an address you need to read.  */
 
static CORE_ADDR bp_location_shadow_len_after_address_max;
 
/* The locations that no longer correspond to any breakpoint,
   unlinked from bp_location array, but for which a hit
   may still be reported by a target.  */
VEC(bp_location_p) *moribund_locations = NULL;
 
/* Number of last breakpoint made.  */
 
static int breakpoint_count;
 
/* The value of `breakpoint_count' before the last command that
   created breakpoints.  If the last (break-like) command created more
   than one breakpoint, then the difference between BREAKPOINT_COUNT
   and PREV_BREAKPOINT_COUNT is more than one.  */
static int prev_breakpoint_count;
 
/* Number of last tracepoint made.  */
 
static int tracepoint_count;
 
static struct cmd_list_element *breakpoint_set_cmdlist;
static struct cmd_list_element *breakpoint_show_cmdlist;
static struct cmd_list_element *save_cmdlist;
 
/* Return whether a breakpoint is an active enabled breakpoint.  */
static int
breakpoint_enabled (struct breakpoint *b)
{
  return (b->enable_state == bp_enabled);
}
 
/* Set breakpoint count to NUM.  */
 
static void
set_breakpoint_count (int num)
{
  prev_breakpoint_count = breakpoint_count;
  breakpoint_count = num;
  set_internalvar_integer (lookup_internalvar ("bpnum"), num);
}
 
/* Used by `start_rbreak_breakpoints' below, to record the current
   breakpoint count before "rbreak" creates any breakpoint.  */
static int rbreak_start_breakpoint_count;
 
/* Called at the start an "rbreak" command to record the first
   breakpoint made.  */
 
void
start_rbreak_breakpoints (void)
{
  rbreak_start_breakpoint_count = breakpoint_count;
}
 
/* Called at the end of an "rbreak" command to record the last
   breakpoint made.  */
 
void
end_rbreak_breakpoints (void)
{
  prev_breakpoint_count = rbreak_start_breakpoint_count;
}
 
/* Used in run_command to zero the hit count when a new run starts. */
 
void
clear_breakpoint_hit_counts (void)
{
  struct breakpoint *b;
 
  ALL_BREAKPOINTS (b)
    b->hit_count = 0;
}
 
/* Allocate a new counted_command_line with reference count of 1.
   The new structure owns COMMANDS.  */
 
static struct counted_command_line *
alloc_counted_command_line (struct command_line *commands)
{
  struct counted_command_line *result
    = xmalloc (sizeof (struct counted_command_line));
 
  result->refc = 1;
  result->commands = commands;
  return result;
}
 
/* Increment reference count.  This does nothing if CMD is NULL.  */
 
static void
incref_counted_command_line (struct counted_command_line *cmd)
{
  if (cmd)
    ++cmd->refc;
}
 
/* Decrement reference count.  If the reference count reaches 0,
   destroy the counted_command_line.  Sets *CMDP to NULL.  This does
   nothing if *CMDP is NULL.  */
 
static void
decref_counted_command_line (struct counted_command_line **cmdp)
{
  if (*cmdp)
    {
      if (--(*cmdp)->refc == 0)
	{
	  free_command_lines (&(*cmdp)->commands);
	  xfree (*cmdp);
	}
      *cmdp = NULL;
    }
}
 
/* A cleanup function that calls decref_counted_command_line.  */
 
static void
do_cleanup_counted_command_line (void *arg)
{
  decref_counted_command_line (arg);
}
 
/* Create a cleanup that calls decref_counted_command_line on the
   argument.  */
 
static struct cleanup *
make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
{
  return make_cleanup (do_cleanup_counted_command_line, cmdp);
}
 
/* Default address, symtab and line to put a breakpoint at
   for "break" command with no arg.
   if default_breakpoint_valid is zero, the other three are
   not valid, and "break" with no arg is an error.
 
   This set by print_stack_frame, which calls set_default_breakpoint.  */
 
int default_breakpoint_valid;
CORE_ADDR default_breakpoint_address;
struct symtab *default_breakpoint_symtab;
int default_breakpoint_line;
struct program_space *default_breakpoint_pspace;
 

/* *PP is a string denoting a breakpoint.  Get the number of the breakpoint.
   Advance *PP after the string and any trailing whitespace.
 
   Currently the string can either be a number or "$" followed by the name
   of a convenience variable.  Making it an expression wouldn't work well
   for map_breakpoint_numbers (e.g. "4 + 5 + 6").
 
   If the string is a NULL pointer, that denotes the last breakpoint.
 
   TRAILER is a character which can be found after the number; most
   commonly this is `-'.  If you don't want a trailer, use \0.  */ 
static int
get_number_trailer (char **pp, int trailer)
{
  int retval = 0;	/* default */
  char *p = *pp;
 
  if (p == NULL)
    /* Empty line means refer to the last breakpoint.  */
    return breakpoint_count;
  else if (*p == '$')
    {
      /* Make a copy of the name, so we can null-terminate it
         to pass to lookup_internalvar().  */
      char *varname;
      char *start = ++p;
      LONGEST val;
 
      while (isalnum (*p) || *p == '_')
	p++;
      varname = (char *) alloca (p - start + 1);
      strncpy (varname, start, p - start);
      varname[p - start] = '\0';
      if (get_internalvar_integer (lookup_internalvar (varname), &val))
	retval = (int) val;
      else
	{
	  printf_filtered (_("Convenience variable must have integer value.\n"));
	  retval = 0;
	}
    }
  else
    {
      if (*p == '-')
	++p;
      while (*p >= '0' && *p <= '9')
	++p;
      if (p == *pp)
	/* There is no number here.  (e.g. "cond a == b").  */
	{
	  /* Skip non-numeric token */
	  while (*p && !isspace((int) *p))
	    ++p;
	  /* Return zero, which caller must interpret as error. */
	  retval = 0;
	}
      else
	retval = atoi (*pp);
    }
  if (!(isspace (*p) || *p == '\0' || *p == trailer))
    {
      /* Trailing junk: return 0 and let caller print error msg. */
      while (!(isspace (*p) || *p == '\0' || *p == trailer))
	++p;
      retval = 0;
    }
  while (isspace (*p))
    p++;
  *pp = p;
  return retval;
}
 
 
/* Like get_number_trailer, but don't allow a trailer.  */
int
get_number (char **pp)
{
  return get_number_trailer (pp, '\0');
}
 
/* Parse a number or a range.
 * A number will be of the form handled by get_number.
 * A range will be of the form <number1> - <number2>, and 
 * will represent all the integers between number1 and number2,
 * inclusive.
 *
 * While processing a range, this fuction is called iteratively;
 * At each call it will return the next value in the range.
 *
 * At the beginning of parsing a range, the char pointer PP will
 * be advanced past <number1> and left pointing at the '-' token.
 * Subsequent calls will not advance the pointer until the range
 * is completed.  The call that completes the range will advance
 * pointer PP past <number2>.
 */
 
int 
get_number_or_range (char **pp)
{
  static int last_retval, end_value;
  static char *end_ptr;
  static int in_range = 0;
 
  if (**pp != '-')
    {
      /* Default case: pp is pointing either to a solo number, 
	 or to the first number of a range.  */
      last_retval = get_number_trailer (pp, '-');
      if (**pp == '-')
	{
	  char **temp;
 
	  /* This is the start of a range (<number1> - <number2>).
	     Skip the '-', parse and remember the second number,
	     and also remember the end of the final token.  */
 
	  temp = &end_ptr; 
	  end_ptr = *pp + 1; 
	  while (isspace ((int) *end_ptr))
	    end_ptr++;	/* skip white space */
	  end_value = get_number (temp);
	  if (end_value < last_retval) 
	    {
	      error (_("inverted range"));
	    }
	  else if (end_value == last_retval)
	    {
	      /* degenerate range (number1 == number2).  Advance the
		 token pointer so that the range will be treated as a
		 single number.  */ 
	      *pp = end_ptr;
	    }
	  else
	    in_range = 1;
	}
    }
  else if (! in_range)
    error (_("negative value"));
  else
    {
      /* pp points to the '-' that betokens a range.  All
	 number-parsing has already been done.  Return the next
	 integer value (one greater than the saved previous value).
	 Do not advance the token pointer 'pp' until the end of range
	 is reached.  */
 
      if (++last_retval == end_value)
	{
	  /* End of range reached; advance token pointer.  */
	  *pp = end_ptr;
	  in_range = 0;
	}
    }
  return last_retval;
}
 
/* Return the breakpoint with the specified number, or NULL
   if the number does not refer to an existing breakpoint.  */
 
struct breakpoint *
get_breakpoint (int num)
{
  struct breakpoint *b;
 
  ALL_BREAKPOINTS (b)
    if (b->number == num)
      return b;
 
  return NULL;
}
 

 
void
set_breakpoint_condition (struct breakpoint *b, char *exp,
			  int from_tty)
{
  struct bp_location *loc = b->loc;
 
  for (; loc; loc = loc->next)
    {
      xfree (loc->cond);
      loc->cond = NULL;
    }
  xfree (b->cond_string);
  b->cond_string = NULL;
  xfree (b->cond_exp);
  b->cond_exp = NULL;
 
  if (*exp == 0)
    {
      if (from_tty)
	printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
    }
  else
    {
      char *arg = exp;
 
      /* I don't know if it matters whether this is the string the user
	 typed in or the decompiled expression.  */
      b->cond_string = xstrdup (arg);
      b->condition_not_parsed = 0;
 
      if (is_watchpoint (b))
	{
	  innermost_block = NULL;
	  arg = exp;
	  b->cond_exp = parse_exp_1 (&arg, 0, 0);
	  if (*arg)
	    error (_("Junk at end of expression"));
	  b->cond_exp_valid_block = innermost_block;
	}
      else
	{
	  for (loc = b->loc; loc; loc = loc->next)
	    {
	      arg = exp;
	      loc->cond =
		parse_exp_1 (&arg, block_for_pc (loc->address), 0);
	      if (*arg)
		error (_("Junk at end of expression"));
	    }
	}
    }
  breakpoints_changed ();
  observer_notify_breakpoint_modified (b->number);
}
 
/* condition N EXP -- set break condition of breakpoint N to EXP.  */
 
static void
condition_command (char *arg, int from_tty)
{
  struct breakpoint *b;
  char *p;
  int bnum;
 
  if (arg == 0)
    error_no_arg (_("breakpoint number"));
 
  p = arg;
  bnum = get_number (&p);
  if (bnum == 0)
    error (_("Bad breakpoint argument: '%s'"), arg);
 
  ALL_BREAKPOINTS (b)
    if (b->number == bnum)
      {
	set_breakpoint_condition (b, p, from_tty);
	return;
      }
 
  error (_("No breakpoint number %d."), bnum);
}
 
/* Check that COMMAND do not contain commands that are suitable
   only for tracepoints and not suitable for ordinary breakpoints.
   Throw if any such commands is found.
*/
static void
check_no_tracepoint_commands (struct command_line *commands)
{
  struct command_line *c;
 
  for (c = commands; c; c = c->next)
    {
      int i;
 
      if (c->control_type == while_stepping_control)
	error (_("The 'while-stepping' command can only be used for tracepoints"));
 
      for (i = 0; i < c->body_count; ++i)
	check_no_tracepoint_commands ((c->body_list)[i]);
 
      /* Not that command parsing removes leading whitespace and comment
	 lines and also empty lines. So, we only need to check for
	 command directly.  */
      if (strstr (c->line, "collect ") == c->line)
	error (_("The 'collect' command can only be used for tracepoints"));
 
      if (strstr (c->line, "teval ") == c->line)
	error (_("The 'teval' command can only be used for tracepoints"));
    }
}
 
/* Encapsulate tests for different types of tracepoints.  */
 
int
is_tracepoint (const struct breakpoint *b)
{
  return (b->type == bp_tracepoint
	  || b->type == bp_fast_tracepoint
	  || b->type == bp_static_tracepoint);
}
 
/* A helper function that validsates that COMMANDS are valid for a
   breakpoint.  This function will throw an exception if a problem is
   found.  */
 
static void
validate_commands_for_breakpoint (struct breakpoint *b,
				  struct command_line *commands)
{
  if (is_tracepoint (b))
    {
      /* We need to verify that each top-level element of commands
	 is valid for tracepoints, that there's at most one while-stepping
	 element, and that while-stepping's body has valid tracing commands
	 excluding nested while-stepping.  */
      struct command_line *c;
      struct command_line *while_stepping = 0;
      for (c = commands; c; c = c->next)
	{
	  if (c->control_type == while_stepping_control)
	    {
	      if (b->type == bp_fast_tracepoint)
		error (_("\
The 'while-stepping' command cannot be used for fast tracepoint"));
	      else if (b->type == bp_static_tracepoint)
		error (_("\
The 'while-stepping' command cannot be used for static tracepoint"));
 
	      if (while_stepping)
		error (_("The 'while-stepping' command can be used only once"));
	      else
		while_stepping = c;
	    }
	}
      if (while_stepping)
	{
	  struct command_line *c2;
 
	  gdb_assert (while_stepping->body_count == 1);
	  c2 = while_stepping->body_list[0];
	  for (; c2; c2 = c2->next)
	    {
	      if (c2->control_type == while_stepping_control)
		error (_("The 'while-stepping' command cannot be nested"));
	    }
	}
    }
  else
    {
      check_no_tracepoint_commands (commands);
    }
}
 
/* Return a vector of all the static tracepoints set at ADDR.  The
   caller is responsible for releasing the vector.  */
 
VEC(breakpoint_p) *
static_tracepoints_here (CORE_ADDR addr)
{
  struct breakpoint *b;
  VEC(breakpoint_p) *found = 0;
  struct bp_location *loc;
 
  ALL_BREAKPOINTS (b)
    if (b->type == bp_static_tracepoint)
      {
	for (loc = b->loc; loc; loc = loc->next)
	  if (loc->address == addr)
	    VEC_safe_push(breakpoint_p, found, b);
      }
 
  return found;
}
 
/* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
   validate that only allowed commands are included.
*/
 
void
breakpoint_set_commands (struct breakpoint *b, struct command_line *commands)
{
  validate_commands_for_breakpoint (b, commands);
 
  decref_counted_command_line (&b->commands);
  b->commands = alloc_counted_command_line (commands);
  breakpoints_changed ();
  observer_notify_breakpoint_modified (b->number);
}
 
void
check_tracepoint_command (char *line, void *closure)
{
  struct breakpoint *b = closure;
 
  validate_actionline (&line, b);
}
 
/* A structure used to pass information through
   map_breakpoint_numbers.  */
 
struct commands_info
{
  /* True if the command was typed at a tty.  */
  int from_tty;
 
  /* The breakpoint range spec.  */
  char *arg;
 
  /* Non-NULL if the body of the commands are being read from this
     already-parsed command.  */
  struct command_line *control;
 
  /* The command lines read from the user, or NULL if they have not
     yet been read.  */
  struct counted_command_line *cmd;
};
 
/* A callback for map_breakpoint_numbers that sets the commands for
   commands_command.  */
 
static void
do_map_commands_command (struct breakpoint *b, void *data)
{
  struct commands_info *info = data;
 
  if (info->cmd == NULL)
    {
      struct command_line *l;
 
      if (info->control != NULL)
	l = copy_command_lines (info->control->body_list[0]);
      else
	{
	  struct cleanup *old_chain;
	  char *str;
 
	  str = xstrprintf (_("Type commands for breakpoint(s) %s, one per line."),
			    info->arg);
 
	  old_chain = make_cleanup (xfree, str);
 
	  l = read_command_lines (str,
				  info->from_tty, 1,
				  (is_tracepoint (b)
				   ? check_tracepoint_command : 0),
				  b);
 
	  do_cleanups (old_chain);
	}
 
      info->cmd = alloc_counted_command_line (l);
    }
 
  /* If a breakpoint was on the list more than once, we don't need to
     do anything.  */
  if (b->commands != info->cmd)
    {
      validate_commands_for_breakpoint (b, info->cmd->commands);
      incref_counted_command_line (info->cmd);
      decref_counted_command_line (&b->commands);
      b->commands = info->cmd;
      breakpoints_changed ();
      observer_notify_breakpoint_modified (b->number);
    }
}
 
static void
commands_command_1 (char *arg, int from_tty, struct command_line *control)
{
  struct cleanup *cleanups;
  struct commands_info info;
 
  info.from_tty = from_tty;
  info.control = control;
  info.cmd = NULL;
  /* If we read command lines from the user, then `info' will hold an
     extra reference to the commands that we must clean up.  */
  cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
 
  if (arg == NULL || !*arg)
    {
      if (breakpoint_count - prev_breakpoint_count > 1)
	arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, breakpoint_count);
      else if (breakpoint_count > 0)
	arg = xstrprintf ("%d", breakpoint_count);
      else
	{
	  /* So that we don't try to free the incoming non-NULL
	     argument in the cleanup below.  Mapping breakpoint
	     numbers will fail in this case.  */
	  arg = NULL;
	}
    }
  else
    /* The command loop has some static state, so we need to preserve
       our argument.  */
    arg = xstrdup (arg);
 
  if (arg != NULL)
    make_cleanup (xfree, arg);
 
  info.arg = arg;
 
  map_breakpoint_numbers (arg, do_map_commands_command, &info);
 
  if (info.cmd == NULL)
    error (_("No breakpoints specified."));
 
  do_cleanups (cleanups);
}
 
static void
commands_command (char *arg, int from_tty)
{
  commands_command_1 (arg, from_tty, NULL);
}
 
/* Like commands_command, but instead of reading the commands from
   input stream, takes them from an already parsed command structure.
 
   This is used by cli-script.c to DTRT with breakpoint commands
   that are part of if and while bodies.  */
enum command_control_type
commands_from_control_command (char *arg, struct command_line *cmd)
{
  commands_command_1 (arg, 0, cmd);
  return simple_control;
}
 
/* Return non-zero if BL->TARGET_INFO contains valid information.  */
 
static int
bp_location_has_shadow (struct bp_location *bl)
{
  if (bl->loc_type != bp_loc_software_breakpoint)
    return 0;
  if (!bl->inserted)
    return 0;
  if (bl->target_info.shadow_len == 0)
    /* bp isn't valid, or doesn't shadow memory.  */
    return 0;
  return 1;
}
 
/* Update BUF, which is LEN bytes read from the target address MEMADDR,
   by replacing any memory breakpoints with their shadowed contents.
 
   The range of shadowed area by each bp_location is:
     b->address - bp_location_placed_address_before_address_max
     up to b->address + bp_location_shadow_len_after_address_max
   The range we were requested to resolve shadows for is:
     memaddr ... memaddr + len
   Thus the safe cutoff boundaries for performance optimization are
     memaddr + len <= b->address - bp_location_placed_address_before_address_max
   and:
     b->address + bp_location_shadow_len_after_address_max <= memaddr  */
 
void
breakpoint_restore_shadows (gdb_byte *buf, ULONGEST memaddr, LONGEST len)
{
  /* Left boundary, right boundary and median element of our binary search.  */
  unsigned bc_l, bc_r, bc;
 
  /* Find BC_L which is a leftmost element which may affect BUF content.  It is
     safe to report lower value but a failure to report higher one.  */
 
  bc_l = 0;
  bc_r = bp_location_count;
  while (bc_l + 1 < bc_r)
    {
      struct bp_location *b;
 
      bc = (bc_l + bc_r) / 2;
      b = bp_location[bc];
 
      /* Check first B->ADDRESS will not overflow due to the added constant.
	 Then advance the left boundary only if we are sure the BC element can
	 in no way affect the BUF content (MEMADDR to MEMADDR + LEN range).
 
	 Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety offset so that
	 we cannot miss a breakpoint with its shadow range tail still reaching
	 MEMADDR.  */
 
      if (b->address + bp_location_shadow_len_after_address_max >= b->address
	  && b->address + bp_location_shadow_len_after_address_max <= memaddr)
	bc_l = bc;
      else
	bc_r = bc;
    }
 
  /* Now do full processing of the found relevant range of elements.  */
 
  for (bc = bc_l; bc < bp_location_count; bc++)
  {
    struct bp_location *b = bp_location[bc];
    CORE_ADDR bp_addr = 0;
    int bp_size = 0;
    int bptoffset = 0;
 
    /* bp_location array has B->OWNER always non-NULL.  */
    if (b->owner->type == bp_none)
      warning (_("reading through apparently deleted breakpoint #%d?"),
              b->owner->number);
 
    /* Performance optimization: any futher element can no longer affect BUF
       content.  */
 
    if (b->address >= bp_location_placed_address_before_address_max
        && memaddr + len <= b->address
			    - bp_location_placed_address_before_address_max)
      break;
 
    if (!bp_location_has_shadow (b))
      continue;
    if (!breakpoint_address_match (b->target_info.placed_address_space, 0,
				   current_program_space->aspace, 0))
      continue;
 
    /* Addresses and length of the part of the breakpoint that
       we need to copy.  */
    bp_addr = b->target_info.placed_address;
    bp_size = b->target_info.shadow_len;
 
    if (bp_addr + bp_size <= memaddr)
      /* The breakpoint is entirely before the chunk of memory we
         are reading.  */
      continue;
 
    if (bp_addr >= memaddr + len)
      /* The breakpoint is entirely after the chunk of memory we are
         reading. */
      continue;
 
    /* Offset within shadow_contents.  */
    if (bp_addr < memaddr)
      {
	/* Only copy the second part of the breakpoint.  */
	bp_size -= memaddr - bp_addr;
	bptoffset = memaddr - bp_addr;
	bp_addr = memaddr;
      }
 
    if (bp_addr + bp_size > memaddr + len)
      {
	/* Only copy the first part of the breakpoint.  */
	bp_size -= (bp_addr + bp_size) - (memaddr + len);
      }
 
    memcpy (buf + bp_addr - memaddr,
	    b->target_info.shadow_contents + bptoffset, bp_size);
  }
}

 
/* A wrapper function for inserting catchpoints.  */
static void
insert_catchpoint (struct ui_out *uo, void *args)
{
  struct breakpoint *b = (struct breakpoint *) args;
 
  gdb_assert (b->type == bp_catchpoint);
  gdb_assert (b->ops != NULL && b->ops->insert != NULL);
 
  b->ops->insert (b);
}
 
/* Return true if BPT is of any hardware watchpoint kind.  */
 
static int
is_hardware_watchpoint (const struct breakpoint *bpt)
{
  return (bpt->type == bp_hardware_watchpoint
	  || bpt->type == bp_read_watchpoint
	  || bpt->type == bp_access_watchpoint);
}
 
/* Return true if BPT is of any watchpoint kind, hardware or
   software.  */
 
static int
is_watchpoint (const struct breakpoint *bpt)
{
  return (is_hardware_watchpoint (bpt)
	  || bpt->type == bp_watchpoint);
}
 
/* Assuming that B is a watchpoint: returns true if the current thread
   and its running state are safe to evaluate or update watchpoint B.
   Watchpoints on local expressions need to be evaluated in the
   context of the thread that was current when the watchpoint was
   created, and, that thread needs to be stopped to be able to select
   the correct frame context.  Watchpoints on global expressions can
   be evaluated on any thread, and in any state.  It is presently left
   to the target allowing memory accesses when threads are
   running.  */
 
static int
watchpoint_in_thread_scope (struct breakpoint *b)
{
  return (ptid_equal (b->watchpoint_thread, null_ptid)
	  || (ptid_equal (inferior_ptid, b->watchpoint_thread)
	      && !is_executing (inferior_ptid)));
}
 
/* Assuming that B is a watchpoint:
   - Reparse watchpoint expression, if REPARSE is non-zero
   - Evaluate expression and store the result in B->val
   - Evaluate the condition if there is one, and store the result
     in b->loc->cond.
   - Update the list of values that must be watched in B->loc.
 
   If the watchpoint disposition is disp_del_at_next_stop, then do nothing.
   If this is local watchpoint that is out of scope, delete it.
 
   Even with `set breakpoint always-inserted on' the watchpoints are removed
   + inserted on each stop here.  Normal breakpoints must never be removed
   because they might be missed by a running thread when debugging in non-stop
   mode.  On the other hand, hardware watchpoints (is_hardware_watchpoint;
   processed here) are specific to each LWP since they are stored in each LWP's
   hardware debug registers.  Therefore, such LWP must be stopped first in
   order to be able to modify its hardware watchpoints.
 
   Hardware watchpoints must be reset exactly once after being presented to the
   user.  It cannot be done sooner, because it would reset the data used to
   present the watchpoint hit to the user.  And it must not be done later
   because it could display the same single watchpoint hit during multiple GDB
   stops.  Note that the latter is relevant only to the hardware watchpoint
   types bp_read_watchpoint and bp_access_watchpoint.  False hit by
   bp_hardware_watchpoint is not user-visible - its hit is suppressed if the
   memory content has not changed.
 
   The following constraints influence the location where we can reset hardware
   watchpoints:
 
   * target_stopped_by_watchpoint and target_stopped_data_address are called
     several times when GDB stops.
 
   [linux]
   * Multiple hardware watchpoints can be hit at the same time, causing GDB to
     stop.  GDB only presents one hardware watchpoint hit at a time as the
     reason for stopping, and all the other hits are presented later, one after
     the other, each time the user requests the execution to be resumed.
     Execution is not resumed for the threads still having pending hit event
     stored in LWP_INFO->STATUS.  While the watchpoint is already removed from
     the inferior on the first stop the thread hit event is kept being reported
     from its cached value by linux_nat_stopped_data_address until the real
     thread resume happens after the watchpoint gets presented and thus its
     LWP_INFO->STATUS gets reset.
 
   Therefore the hardware watchpoint hit can get safely reset on the watchpoint
   removal from inferior.  */
 
static void
update_watchpoint (struct breakpoint *b, int reparse)
{
  int within_current_scope;
  struct frame_id saved_frame_id;
  int frame_saved;
 
  /* If this is a local watchpoint, we only want to check if the
     watchpoint frame is in scope if the current thread is the thread
     that was used to create the watchpoint.  */
  if (!watchpoint_in_thread_scope (b))
    return;
 
  /* We don't free locations.  They are stored in bp_location array and
     update_global_locations will eventually delete them and remove
     breakpoints if needed.  */
  b->loc = NULL;
 
  if (b->disposition == disp_del_at_next_stop)
    return;
 
  frame_saved = 0;
 
  /* Determine if the watchpoint is within scope.  */
  if (b->exp_valid_block == NULL)
    within_current_scope = 1;
  else
    {
      struct frame_info *fi;
 
      /* Save the current frame's ID so we can restore it after
         evaluating the watchpoint expression on its own frame.  */
      /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
         took a frame parameter, so that we didn't have to change the
         selected frame.  */
      frame_saved = 1;
      saved_frame_id = get_frame_id (get_selected_frame (NULL));
 
      fi = frame_find_by_id (b->watchpoint_frame);
      within_current_scope = (fi != NULL);
      if (within_current_scope)
	select_frame (fi);
    }
 
  if (within_current_scope && reparse)
    {
      char *s;
      if (b->exp)
	{
	  xfree (b->exp);
	  b->exp = NULL;
	}
      s = b->exp_string;
      b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
      /* If the meaning of expression itself changed, the old value is
	 no longer relevant.  We don't want to report a watchpoint hit
	 to the user when the old value and the new value may actually
	 be completely different objects.  */
      value_free (b->val);
      b->val = NULL;
      b->val_valid = 0;
 
      /* Note that unlike with breakpoints, the watchpoint's condition
	 expression is stored in the breakpoint object, not in the
	 locations (re)created below.  */
      if (b->cond_string != NULL)
	{
	  if (b->cond_exp != NULL)
	    {
	      xfree (b->cond_exp);
	      b->cond_exp = NULL;
	    }
 
	  s = b->cond_string;
	  b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
	}
    }
 
  /* If we failed to parse the expression, for example because
     it refers to a global variable in a not-yet-loaded shared library,
     don't try to insert watchpoint.  We don't automatically delete
     such watchpoint, though, since failure to parse expression
     is different from out-of-scope watchpoint.  */
  if ( !target_has_execution)
    {
      /* Without execution, memory can't change.  No use to try and
	 set watchpoint locations.  The watchpoint will be reset when
	 the target gains execution, through breakpoint_re_set.  */
    }
  else if (within_current_scope && b->exp)
    {
      int pc = 0;
      struct value *val_chain, *v, *result, *next;
      struct program_space *frame_pspace;
 
      fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
 
      /* Avoid setting b->val if it's already set.  The meaning of
	 b->val is 'the last value' user saw, and we should update
	 it only if we reported that last value to user.  As it
	 happens, the code that reports it updates b->val directly.  */
      if (!b->val_valid)
	{
	  b->val = v;
	  b->val_valid = 1;
	}
 
	/* Change the type of breakpoint between hardware assisted or an
	   ordinary watchpoint depending on the hardware support and free
	   hardware slots.  REPARSE is set when the inferior is started.  */
	if ((b->type == bp_watchpoint || b->type == bp_hardware_watchpoint)
	    && reparse)
	  {
	    int i, mem_cnt, other_type_used;
 
	    /* We need to determine how many resources are already used
	       for all other hardware watchpoints to see if we still have
	       enough resources to also fit this watchpoint in as well.
	       To avoid the hw_watchpoint_used_count call below from counting
	       this watchpoint, make sure that it is marked as a software
	       watchpoint.  */
	    b->type = bp_watchpoint;
	    i = hw_watchpoint_used_count (bp_hardware_watchpoint,
					  &other_type_used);
	    mem_cnt = can_use_hardware_watchpoint (val_chain);
 
	    if (!mem_cnt)
	      b->type = bp_watchpoint;
	    else
	      {
		int target_resources_ok = target_can_use_hardware_watchpoint
		  (bp_hardware_watchpoint, i + mem_cnt, other_type_used);
		if (target_resources_ok <= 0)
		  b->type = bp_watchpoint;
		else
		  b->type = bp_hardware_watchpoint;
	      }
	  }
 
      frame_pspace = get_frame_program_space (get_selected_frame (NULL));
 
      /* Look at each value on the value chain.  */
      for (v = val_chain; v; v = next)
	{
	  /* If it's a memory location, and GDB actually needed
	     its contents to evaluate the expression, then we
	     must watch it.  If the first value returned is
	     still lazy, that means an error occurred reading it;
	     watch it anyway in case it becomes readable.  */
	  if (VALUE_LVAL (v) == lval_memory
	      && (v == val_chain || ! value_lazy (v)))
	    {
	      struct type *vtype = check_typedef (value_type (v));
 
	      /* We only watch structs and arrays if user asked
		 for it explicitly, never if they just happen to
		 appear in the middle of some value chain.  */
	      if (v == result
		  || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
		      && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
		{
		  CORE_ADDR addr;
		  int len, type;
		  struct bp_location *loc, **tmp;
 
		  addr = value_address (v);
		  len = TYPE_LENGTH (value_type (v));
		  type = hw_write;
		  if (b->type == bp_read_watchpoint)
		    type = hw_read;
		  else if (b->type == bp_access_watchpoint)
		    type = hw_access;
 
		  loc = allocate_bp_location (b);
		  for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
		    ;
		  *tmp = loc;
		  loc->gdbarch = get_type_arch (value_type (v));
 
		  loc->pspace = frame_pspace;
		  loc->address = addr;
		  loc->length = len;
		  loc->watchpoint_type = type;
		}
	    }
 
	  next = value_next (v);
	  if (v != b->val)
	    value_free (v);
	}
 
      /* If a software watchpoint is not watching any memory, then the
	 above left it without any location set up.  But,
	 bpstat_stop_status requires a location to be able to report
	 stops, so make sure there's at least a dummy one.  */
      if (b->type == bp_watchpoint && b->loc == NULL)
	{
	  b->loc = allocate_bp_location (b);
	  b->loc->pspace = frame_pspace;
	  b->loc->address = -1;
	  b->loc->length = -1;
	  b->loc->watchpoint_type = -1;
	}
    }
  else if (!within_current_scope)
    {
      printf_filtered (_("\
Watchpoint %d deleted because the program has left the block\n\
in which its expression is valid.\n"),
		       b->number);
      if (b->related_breakpoint)
	{
	  b->related_breakpoint->disposition = disp_del_at_next_stop;
	  b->related_breakpoint->related_breakpoint = NULL;
	  b->related_breakpoint= NULL;
	}
      b->disposition = disp_del_at_next_stop;
    }
 
  /* Restore the selected frame.  */
  if (frame_saved)
    select_frame (frame_find_by_id (saved_frame_id));
}
 
 
/* Returns 1 iff breakpoint location should be
   inserted in the inferior.  */
static int
should_be_inserted (struct bp_location *bpt)
{
  if (bpt->owner == NULL || !breakpoint_enabled (bpt->owner))
    return 0;
 
  if (bpt->owner->disposition == disp_del_at_next_stop)
    return 0;
 
  if (!bpt->enabled || bpt->shlib_disabled || bpt->duplicate)
    return 0;
 
  /* This is set for example, when we're attached to the parent of a
     vfork, and have detached from the child.  The child is running
     free, and we expect it to do an exec or exit, at which point the
     OS makes the parent schedulable again (and the target reports
     that the vfork is done).  Until the child is done with the shared
     memory region, do not insert breakpoints in the parent, otherwise
     the child could still trip on the parent's breakpoints.  Since
     the parent is blocked anyway, it won't miss any breakpoint.  */
  if (bpt->pspace->breakpoints_not_allowed)
    return 0;
 
  /* Tracepoints are inserted by the target at a time of its choosing,
     not by us.  */
  if (is_tracepoint (bpt->owner))
    return 0;
 
  return 1;
}
 
/* Insert a low-level "breakpoint" of some type.  BPT is the breakpoint.
   Any error messages are printed to TMP_ERROR_STREAM; and DISABLED_BREAKS,
   and HW_BREAKPOINT_ERROR are used to report problems.
 
   NOTE drow/2003-09-09: This routine could be broken down to an object-style
   method for each breakpoint or catchpoint type.  */
static int
insert_bp_location (struct bp_location *bpt,
		    struct ui_file *tmp_error_stream,
		    int *disabled_breaks,
		    int *hw_breakpoint_error)
{
  int val = 0;
 
  if (!should_be_inserted (bpt) || bpt->inserted)
    return 0;
 
  /* Initialize the target-specific information.  */
  memset (&bpt->target_info, 0, sizeof (bpt->target_info));
  bpt->target_info.placed_address = bpt->address;
  bpt->target_info.placed_address_space = bpt->pspace->aspace;
 
  if (bpt->loc_type == bp_loc_software_breakpoint
      || bpt->loc_type == bp_loc_hardware_breakpoint)
    {
      if (bpt->owner->type != bp_hardware_breakpoint)
	{
	  /* If the explicitly specified breakpoint type
	     is not hardware breakpoint, check the memory map to see
	     if the breakpoint address is in read only memory or not.
	     Two important cases are:
	     - location type is not hardware breakpoint, memory
	     is readonly.  We change the type of the location to
	     hardware breakpoint.
	     - location type is hardware breakpoint, memory is read-write.
	     This means we've previously made the location hardware one, but
	     then the memory map changed, so we undo.
 
	     When breakpoints are removed, remove_breakpoints will
	     use location types we've just set here, the only possible
	     problem is that memory map has changed during running program,
	     but it's not going to work anyway with current gdb.  */
	  struct mem_region *mr 
	    = lookup_mem_region (bpt->target_info.placed_address);
 
	  if (mr)
	    {
	      if (automatic_hardware_breakpoints)
		{
		  enum bp_loc_type new_type;
 
		  if (mr->attrib.mode != MEM_RW)
		    new_type = bp_loc_hardware_breakpoint;
		  else 
		    new_type = bp_loc_software_breakpoint;
 
		  if (new_type != bpt->loc_type)
		    {
		      static int said = 0;
 
		      bpt->loc_type = new_type;
		      if (!said)
			{
			  fprintf_filtered (gdb_stdout, _("\
Note: automatically using hardware breakpoints for read-only addresses.\n"));
			  said = 1;
			}
		    }
		}
	      else if (bpt->loc_type == bp_loc_software_breakpoint
		       && mr->attrib.mode != MEM_RW)	    
		warning (_("cannot set software breakpoint at readonly address %s"),
			 paddress (bpt->gdbarch, bpt->address));
	    }
	}
 
      /* First check to see if we have to handle an overlay.  */
      if (overlay_debugging == ovly_off
	  || bpt->section == NULL
	  || !(section_is_overlay (bpt->section)))
	{
	  /* No overlay handling: just set the breakpoint.  */
 
	  if (bpt->loc_type == bp_loc_hardware_breakpoint)
	    val = target_insert_hw_breakpoint (bpt->gdbarch,
					       &bpt->target_info);
	  else
	    val = target_insert_breakpoint (bpt->gdbarch,
					    &bpt->target_info);
	}
      else
	{
	  /* This breakpoint is in an overlay section.  
	     Shall we set a breakpoint at the LMA?  */
	  if (!overlay_events_enabled)
	    {
	      /* Yes -- overlay event support is not active, 
		 so we must try to set a breakpoint at the LMA.
		 This will not work for a hardware breakpoint.  */
	      if (bpt->loc_type == bp_loc_hardware_breakpoint)
		warning (_("hardware breakpoint %d not supported in overlay!"),
			 bpt->owner->number);
	      else
		{
		  CORE_ADDR addr = overlay_unmapped_address (bpt->address,
							     bpt->section);
		  /* Set a software (trap) breakpoint at the LMA.  */
		  bpt->overlay_target_info = bpt->target_info;
		  bpt->overlay_target_info.placed_address = addr;
		  val = target_insert_breakpoint (bpt->gdbarch,
						  &bpt->overlay_target_info);
		  if (val != 0)
		    fprintf_unfiltered (tmp_error_stream,
					"Overlay breakpoint %d failed: in ROM?\n",
					bpt->owner->number);
		}
	    }
	  /* Shall we set a breakpoint at the VMA? */
	  if (section_is_mapped (bpt->section))
	    {
	      /* Yes.  This overlay section is mapped into memory.  */
	      if (bpt->loc_type == bp_loc_hardware_breakpoint)
		val = target_insert_hw_breakpoint (bpt->gdbarch,
						   &bpt->target_info);
	      else
		val = target_insert_breakpoint (bpt->gdbarch,
						&bpt->target_info);
	    }
	  else
	    {
	      /* No.  This breakpoint will not be inserted.  
		 No error, but do not mark the bp as 'inserted'.  */
	      return 0;
	    }
	}
 
      if (val)
	{
	  /* Can't set the breakpoint.  */
	  if (solib_name_from_address (bpt->pspace, bpt->address))
	    {
	      /* See also: disable_breakpoints_in_shlibs. */
	      val = 0;
	      bpt->shlib_disabled = 1;
	      if (!*disabled_breaks)
		{
		  fprintf_unfiltered (tmp_error_stream, 
				      "Cannot insert breakpoint %d.\n", 
				      bpt->owner->number);
		  fprintf_unfiltered (tmp_error_stream, 
				      "Temporarily disabling shared library breakpoints:\n");
		}
	      *disabled_breaks = 1;
	      fprintf_unfiltered (tmp_error_stream,
				  "breakpoint #%d\n", bpt->owner->number);
	    }
	  else
	    {
	      if (bpt->loc_type == bp_loc_hardware_breakpoint)
		{
		  *hw_breakpoint_error = 1;
		  fprintf_unfiltered (tmp_error_stream, 
				      "Cannot insert hardware breakpoint %d.\n",
				      bpt->owner->number);
		}
	      else
		{
		  fprintf_unfiltered (tmp_error_stream, 
				      "Cannot insert breakpoint %d.\n", 
				      bpt->owner->number);
		  fprintf_filtered (tmp_error_stream, 
				    "Error accessing memory address ");
		  fputs_filtered (paddress (bpt->gdbarch, bpt->address),
				  tmp_error_stream);
		  fprintf_filtered (tmp_error_stream, ": %s.\n",
				    safe_strerror (val));
		}
 
	    }
	}
      else
	bpt->inserted = 1;
 
      return val;
    }
 
  else if (bpt->loc_type == bp_loc_hardware_watchpoint
	   /* NOTE drow/2003-09-08: This state only exists for removing
	      watchpoints.  It's not clear that it's necessary... */
	   && bpt->owner->disposition != disp_del_at_next_stop)
    {
      val = target_insert_watchpoint (bpt->address,
				      bpt->length,
				      bpt->watchpoint_type,
				      bpt->owner->cond_exp);
 
      /* If trying to set a read-watchpoint, and it turns out it's not
	 supported, try emulating one with an access watchpoint.  */
      if (val == 1 && bpt->watchpoint_type == hw_read)
	{
	  struct bp_location *loc, **loc_temp;
 
	  /* But don't try to insert it, if there's already another
	     hw_access location that would be considered a duplicate
	     of this one.  */
	  ALL_BP_LOCATIONS (loc, loc_temp)
	    if (loc != bpt
		&& loc->watchpoint_type == hw_access
		&& watchpoint_locations_match (bpt, loc))
	      {
		bpt->duplicate = 1;
		bpt->inserted = 1;
		bpt->target_info = loc->target_info;
		bpt->watchpoint_type = hw_access;
		val = 0;
		break;
	      }
 
	  if (val == 1)
	    {
	      val = target_insert_watchpoint (bpt->address,
					      bpt->length,
					      hw_access,
					      bpt->owner->cond_exp);
	      if (val == 0)
		bpt->watchpoint_type = hw_access;
	    }
	}
 
      bpt->inserted = (val == 0);
    }
 
  else if (bpt->owner->type == bp_catchpoint)
    {
      struct gdb_exception e = catch_exception (uiout, insert_catchpoint,
						bpt->owner, RETURN_MASK_ERROR);
      exception_fprintf (gdb_stderr, e, "warning: inserting catchpoint %d: ",
			 bpt->owner->number);
      if (e.reason < 0)
	bpt->owner->enable_state = bp_disabled;
      else
	bpt->inserted = 1;
 
      /* We've already printed an error message if there was a problem
	 inserting this catchpoint, and we've disabled the catchpoint,
	 so just return success.  */
      return 0;
    }
 
  return 0;
}
 
/* This function is called when program space PSPACE is about to be
   deleted.  It takes care of updating breakpoints to not reference
   PSPACE anymore.  */
 
void
breakpoint_program_space_exit (struct program_space *pspace)
{
  struct breakpoint *b, *b_temp;
  struct bp_location *loc, **loc_temp;
 
  /* Remove any breakpoint that was set through this program space.  */
  ALL_BREAKPOINTS_SAFE (b, b_temp)
    {
      if (b->pspace == pspace)
	delete_breakpoint (b);
    }
 
  /* Breakpoints set through other program spaces could have locations
     bound to PSPACE as well.  Remove those.  */
  ALL_BP_LOCATIONS (loc, loc_temp)
    {
      struct bp_location *tmp;
 
      if (loc->pspace == pspace)
	{
	  /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
	  if (loc->owner->loc == loc)
	    loc->owner->loc = loc->next;
	  else
	    for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
	      if (tmp->next == loc)
		{
		  tmp->next = loc->next;
		  break;
		}
	}
    }
 
  /* Now update the global location list to permanently delete the
     removed locations above.  */
  update_global_location_list (0);
}
 
/* Make sure all breakpoints are inserted in inferior.
   Throws exception on any error.
   A breakpoint that is already inserted won't be inserted
   again, so calling this function twice is safe.  */
void
insert_breakpoints (void)
{
  struct breakpoint *bpt;
 
  ALL_BREAKPOINTS (bpt)
    if (is_hardware_watchpoint (bpt))
      update_watchpoint (bpt, 0 /* don't reparse. */);
 
  update_global_location_list (1);
 
  /* update_global_location_list does not insert breakpoints when
     always_inserted_mode is not enabled.  Explicitly insert them
     now.  */
  if (!breakpoints_always_inserted_mode ())
    insert_breakpoint_locations ();
}
 
/* insert_breakpoints is used when starting or continuing the program.
   remove_breakpoints is used when the program stops.
   Both return zero if successful,
   or an `errno' value if could not write the inferior.  */
 
static void
insert_breakpoint_locations (void)
{
  struct breakpoint *bpt;
  struct bp_location *b, **bp_tmp;
  int error = 0;
  int val = 0;
  int disabled_breaks = 0;
  int hw_breakpoint_error = 0;
 
  struct ui_file *tmp_error_stream = mem_fileopen ();
  struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
 
  /* Explicitly mark the warning -- this will only be printed if
     there was an error.  */
  fprintf_unfiltered (tmp_error_stream, "Warning:\n");
 
  save_current_space_and_thread ();
 
  ALL_BP_LOCATIONS (b, bp_tmp)
    {
      if (!should_be_inserted (b) || b->inserted)
	continue;
 
      /* There is no point inserting thread-specific breakpoints if the
	 thread no longer exists.  ALL_BP_LOCATIONS bp_location has B->OWNER
	 always non-NULL.  */
      if (b->owner->thread != -1
	  && !valid_thread_id (b->owner->thread))
	continue;
 
      switch_to_program_space_and_thread (b->pspace);
 
      /* For targets that support global breakpoints, there's no need
	 to select an inferior to insert breakpoint to.  In fact, even
	 if we aren't attached to any process yet, we should still
	 insert breakpoints.  */
      if (!gdbarch_has_global_breakpoints (target_gdbarch)
	  && ptid_equal (inferior_ptid, null_ptid))
	continue;
 
      val = insert_bp_location (b, tmp_error_stream,
				    &disabled_breaks,
				    &hw_breakpoint_error);
      if (val)
	error = val;
    }
 
  /* If we failed to insert all locations of a watchpoint,
     remove them, as half-inserted watchpoint is of limited use.  */
  ALL_BREAKPOINTS (bpt)  
    {
      int some_failed = 0;
      struct bp_location *loc;
 
      if (!is_hardware_watchpoint (bpt))
	continue;
 
      if (!breakpoint_enabled (bpt))
	continue;
 
      if (bpt->disposition == disp_del_at_next_stop)
	continue;
 
      for (loc = bpt->loc; loc; loc = loc->next)
	if (!loc->inserted && should_be_inserted (loc))
	  {
	    some_failed = 1;
	    break;
	  }
      if (some_failed)
	{
	  for (loc = bpt->loc; loc; loc = loc->next)
	    if (loc->inserted)
	      remove_breakpoint (loc, mark_uninserted);
 
	  hw_breakpoint_error = 1;
	  fprintf_unfiltered (tmp_error_stream,
			      "Could not insert hardware watchpoint %d.\n", 
			      bpt->number);
	  error = -1;
	}
    }
 
  if (error)
    {
      /* If a hardware breakpoint or watchpoint was inserted, add a
         message about possibly exhausted resources.  */
      if (hw_breakpoint_error)
	{
	  fprintf_unfiltered (tmp_error_stream, 
			      "Could not insert hardware breakpoints:\n\
You may have requested too many hardware breakpoints/watchpoints.\n");
	}
      target_terminal_ours_for_output ();
      error_stream (tmp_error_stream);
    }
 
  do_cleanups (cleanups);
}
 
int
remove_breakpoints (void)
{
  struct bp_location *b, **bp_tmp;
  int val = 0;
 
  ALL_BP_LOCATIONS (b, bp_tmp)
  {
    if (b->inserted)
      val |= remove_breakpoint (b, mark_uninserted);
  }
  return val;
}
 
/* Remove breakpoints of process PID.  */
 
int
remove_breakpoints_pid (int pid)
{
  struct bp_location *b, **b_tmp;
  int val;
  struct inferior *inf = find_inferior_pid (pid);
 
  ALL_BP_LOCATIONS (b, b_tmp)
  {
    if (b->pspace != inf->pspace)
      continue;
 
    if (b->inserted)
      {
	val = remove_breakpoint (b, mark_uninserted);
	if (val != 0)
	  return val;
      }
  }
  return 0;
}
 
int
remove_hw_watchpoints (void)
{
  struct bp_location *b, **bp_tmp;
  int val = 0;
 
  ALL_BP_LOCATIONS (b, bp_tmp)
  {
    if (b->inserted && b->loc_type == bp_loc_hardware_watchpoint)
      val |= remove_breakpoint (b, mark_uninserted);
  }
  return val;
}
 
int
reattach_breakpoints (int pid)
{
  struct cleanup *old_chain;
  struct bp_location *b, **bp_tmp;
  int val;
  struct ui_file *tmp_error_stream = mem_fileopen ();
  int dummy1 = 0, dummy2 = 0;
  struct inferior *inf;
  struct thread_info *tp;
 
  tp = any_live_thread_of_process (pid);
  if (tp == NULL)
    return 1;
 
  inf = find_inferior_pid (pid);
  old_chain = save_inferior_ptid ();
 
  inferior_ptid = tp->ptid;
 
  make_cleanup_ui_file_delete (tmp_error_stream);
 
  ALL_BP_LOCATIONS (b, bp_tmp)
  {
    if (b->pspace != inf->pspace)
      continue;
 
    if (b->inserted)
      {
	b->inserted = 0;
	val = insert_bp_location (b, tmp_error_stream,
				  &dummy1, &dummy2);
	if (val != 0)
	  {
	    do_cleanups (old_chain);
	    return val;
	  }
      }
  }
  do_cleanups (old_chain);
  return 0;
}
 
static int internal_breakpoint_number = -1;
 
static struct breakpoint *
create_internal_breakpoint (struct gdbarch *gdbarch,
			    CORE_ADDR address, enum bptype type)
{
  struct symtab_and_line sal;
  struct breakpoint *b;
 
  init_sal (&sal);		/* initialize to zeroes */
 
  sal.pc = address;
  sal.section = find_pc_overlay (sal.pc);
  sal.pspace = current_program_space;
 
  b = set_raw_breakpoint (gdbarch, sal, type);
  b->number = internal_breakpoint_number--;
  b->disposition = disp_donttouch;
 
  return b;
}
 
static void
create_overlay_event_breakpoint (char *func_name)
{
  struct objfile *objfile;
 
  ALL_OBJFILES (objfile)
    {
      struct breakpoint *b;
      struct minimal_symbol *m;
 
      m = lookup_minimal_symbol_text (func_name, objfile);
      if (m == NULL)
        continue;
 
      b = create_internal_breakpoint (get_objfile_arch (objfile),
				      SYMBOL_VALUE_ADDRESS (m),
                                      bp_overlay_event);
      b->addr_string = xstrdup (func_name);
 
      if (overlay_debugging == ovly_auto)
        {
          b->enable_state = bp_enabled;
          overlay_events_enabled = 1;
        }
      else
       {
         b->enable_state = bp_disabled;
         overlay_events_enabled = 0;
       }
    }
  update_global_location_list (1);
}
 
static void
create_longjmp_master_breakpoint (char *func_name)
{
  struct program_space *pspace;
  struct objfile *objfile;
  struct cleanup *old_chain;
 
  old_chain = save_current_program_space ();
 
  ALL_PSPACES (pspace)
  ALL_OBJFILES (objfile)
    {
      struct breakpoint *b;
      struct minimal_symbol *m;
 
      if (!gdbarch_get_longjmp_target_p (get_objfile_arch (objfile)))
	continue;
 
      set_current_program_space (pspace);
 
      m = lookup_minimal_symbol_text (func_name, objfile);
      if (m == NULL)
        continue;
 
      b = create_internal_breakpoint (get_objfile_arch (objfile),
				      SYMBOL_VALUE_ADDRESS (m),
                                      bp_longjmp_master);
      b->addr_string = xstrdup (func_name);
      b->enable_state = bp_disabled;
    }
  update_global_location_list (1);
 
  do_cleanups (old_chain);
}
 
/* Create a master std::terminate breakpoint.  The actual function
   looked for is named FUNC_NAME.  */
static void
create_std_terminate_master_breakpoint (const char *func_name)
{
  struct program_space *pspace;
  struct objfile *objfile;
  struct cleanup *old_chain;
 
  old_chain = save_current_program_space ();
 
  ALL_PSPACES (pspace)
    ALL_OBJFILES (objfile)
    {
      struct breakpoint *b;
      struct minimal_symbol *m;
 
      set_current_program_space (pspace);
 
      m = lookup_minimal_symbol (func_name, NULL, objfile);
      if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
			&& MSYMBOL_TYPE (m) != mst_file_text))
        continue;
 
      b = create_internal_breakpoint (get_objfile_arch (objfile),
				      SYMBOL_VALUE_ADDRESS (m),
                                      bp_std_terminate_master);
      b->addr_string = xstrdup (func_name);
      b->enable_state = bp_disabled;
    }
  update_global_location_list (1);
 
  do_cleanups (old_chain);
}
 
void
update_breakpoints_after_exec (void)
{
  struct breakpoint *b;
  struct breakpoint *temp;
  struct bp_location *bploc, **bplocp_tmp;
 
  /* We're about to delete breakpoints from GDB's lists.  If the
     INSERTED flag is true, GDB will try to lift the breakpoints by
     writing the breakpoints' "shadow contents" back into memory.  The
     "shadow contents" are NOT valid after an exec, so GDB should not
     do that.  Instead, the target is responsible from marking
     breakpoints out as soon as it detects an exec.  We don't do that
     here instead, because there may be other attempts to delete
     breakpoints after detecting an exec and before reaching here.  */
  ALL_BP_LOCATIONS (bploc, bplocp_tmp)
    if (bploc->pspace == current_program_space)
      gdb_assert (!bploc->inserted);
 
  ALL_BREAKPOINTS_SAFE (b, temp)
  {
    if (b->pspace != current_program_space)
      continue;
 
    /* Solib breakpoints must be explicitly reset after an exec(). */
    if (b->type == bp_shlib_event)
      {
	delete_breakpoint (b);
	continue;
      }
 
    /* JIT breakpoints must be explicitly reset after an exec(). */
    if (b->type == bp_jit_event)
      {
	delete_breakpoint (b);
	continue;
      }
 
    /* Thread event breakpoints must be set anew after an exec(),
       as must overlay event and longjmp master breakpoints.  */
    if (b->type == bp_thread_event || b->type == bp_overlay_event
	|| b->type == bp_longjmp_master || b->type == bp_std_terminate_master)
      {
	delete_breakpoint (b);
	continue;
      }
 
    /* Step-resume breakpoints are meaningless after an exec(). */
    if (b->type == bp_step_resume)
      {
	delete_breakpoint (b);
	continue;
      }
 
    /* Longjmp and longjmp-resume breakpoints are also meaningless
       after an exec.  */
    if (b->type == bp_longjmp || b->type == bp_longjmp_resume)
      {
	delete_breakpoint (b);
	continue;
      }
 
    if (b->type == bp_catchpoint)
      {
        /* For now, none of the bp_catchpoint breakpoints need to
           do anything at this point.  In the future, if some of
           the catchpoints need to something, we will need to add
           a new method, and call this method from here.  */
        continue;
      }
 
    /* bp_finish is a special case.  The only way we ought to be able
       to see one of these when an exec() has happened, is if the user
       caught a vfork, and then said "finish".  Ordinarily a finish just
       carries them to the call-site of the current callee, by setting
       a temporary bp there and resuming.  But in this case, the finish
       will carry them entirely through the vfork & exec.
 
       We don't want to allow a bp_finish to remain inserted now.  But
       we can't safely delete it, 'cause finish_command has a handle to
       the bp on a bpstat, and will later want to delete it.  There's a
       chance (and I've seen it happen) that if we delete the bp_finish
       here, that its storage will get reused by the time finish_command
       gets 'round to deleting the "use to be a bp_finish" breakpoint.
       We really must allow finish_command to delete a bp_finish.
 
       In the absense of a general solution for the "how do we know
       it's safe to delete something others may have handles to?"
       problem, what we'll do here is just uninsert the bp_finish, and
       let finish_command delete it.
 
       (We know the bp_finish is "doomed" in the sense that it's
       momentary, and will be deleted as soon as finish_command sees
       the inferior stopped.  So it doesn't matter that the bp's
       address is probably bogus in the new a.out, unlike e.g., the
       solib breakpoints.)  */
 
    if (b->type == bp_finish)
      {
	continue;
      }
 
    /* Without a symbolic address, we have little hope of the
       pre-exec() address meaning the same thing in the post-exec()
       a.out. */
    if (b->addr_string == NULL)
      {
	delete_breakpoint (b);
	continue;
      }
  }
  /* FIXME what about longjmp breakpoints?  Re-create them here?  */
  create_overlay_event_breakpoint ("_ovly_debug_event");
  create_longjmp_master_breakpoint ("longjmp");
  create_longjmp_master_breakpoint ("_longjmp");
  create_longjmp_master_breakpoint ("siglongjmp");
  create_longjmp_master_breakpoint ("_siglongjmp");
  create_std_terminate_master_breakpoint ("std::terminate()");
}
 
int
detach_breakpoints (int pid)
{
  struct bp_location *b, **bp_tmp;
  int val = 0;
  struct cleanup *old_chain = save_inferior_ptid ();
  struct inferior *inf = current_inferior ();
 
  if (pid == PIDGET (inferior_ptid))
    error (_("Cannot detach breakpoints of inferior_ptid"));
 
  /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
  inferior_ptid = pid_to_ptid (pid);
  ALL_BP_LOCATIONS (b, bp_tmp)
  {
    if (b->pspace != inf->pspace)
      continue;
 
    if (b->inserted)
      val |= remove_breakpoint_1 (b, mark_inserted);
  }
 
  /* Detach single-step breakpoints as well.  */
  detach_single_step_breakpoints ();
 
  do_cleanups (old_chain);
  return val;
}
 
/* Remove the breakpoint location B from the current address space.
   Note that this is used to detach breakpoints from a child fork.
   When we get here, the child isn't in the inferior list, and neither
   do we have objects to represent its address space --- we should
   *not* look at b->pspace->aspace here.  */
 
static int
remove_breakpoint_1 (struct bp_location *b, insertion_state_t is)
{
  int val;
 
  /* B is never in moribund_locations by our callers.  */
  gdb_assert (b->owner != NULL);
 
  if (b->owner->enable_state == bp_permanent)
    /* Permanent breakpoints cannot be inserted or removed.  */
    return 0;
 
  /* The type of none suggests that owner is actually deleted.
     This should not ever happen.  */
  gdb_assert (b->owner->type != bp_none);
 
  if (b->loc_type == bp_loc_software_breakpoint
      || b->loc_type == bp_loc_hardware_breakpoint)
    {
      /* "Normal" instruction breakpoint: either the standard
	 trap-instruction bp (bp_breakpoint), or a
	 bp_hardware_breakpoint.  */
 
      /* First check to see if we have to handle an overlay.  */
      if (overlay_debugging == ovly_off
	  || b->section == NULL
	  || !(section_is_overlay (b->section)))
	{
	  /* No overlay handling: just remove the breakpoint.  */
 
	  if (b->loc_type == bp_loc_hardware_breakpoint)
	    val = target_remove_hw_breakpoint (b->gdbarch, &b->target_info);
	  else
	    val = target_remove_breakpoint (b->gdbarch, &b->target_info);
	}
      else
	{
	  /* This breakpoint is in an overlay section.  
	     Did we set a breakpoint at the LMA?  */
	  if (!overlay_events_enabled)
	      {
		/* Yes -- overlay event support is not active, so we
		   should have set a breakpoint at the LMA.  Remove it.  
		*/
		/* Ignore any failures: if the LMA is in ROM, we will
		   have already warned when we failed to insert it.  */
		if (b->loc_type == bp_loc_hardware_breakpoint)
		  target_remove_hw_breakpoint (b->gdbarch,
					       &b->overlay_target_info);
		else
		  target_remove_breakpoint (b->gdbarch,
					    &b->overlay_target_info);
	      }
	  /* Did we set a breakpoint at the VMA? 
	     If so, we will have marked the breakpoint 'inserted'.  */
	  if (b->inserted)
	    {
	      /* Yes -- remove it.  Previously we did not bother to
		 remove the breakpoint if the section had been
		 unmapped, but let's not rely on that being safe.  We
		 don't know what the overlay manager might do.  */
	      if (b->loc_type == bp_loc_hardware_breakpoint)
		val = target_remove_hw_breakpoint (b->gdbarch,
						   &b->target_info);
 
	      /* However, we should remove *software* breakpoints only
		 if the section is still mapped, or else we overwrite
		 wrong code with the saved shadow contents.  */
	      else if (section_is_mapped (b->section))
		val = target_remove_breakpoint (b->gdbarch,
						&b->target_info);
	      else
		val = 0;
	    }
	  else
	    {
	      /* No -- not inserted, so no need to remove.  No error.  */
	      val = 0;
	    }
	}
 
      /* In some cases, we might not be able to remove a breakpoint
	 in a shared library that has already been removed, but we
	 have not yet processed the shlib unload event.  */
      if (val && solib_name_from_address (b->pspace, b->address))
	val = 0;
 
      if (val)
	return val;
      b->inserted = (is == mark_inserted);
    }
  else if (b->loc_type == bp_loc_hardware_watchpoint)
    {
      b->inserted = (is == mark_inserted);
      val = target_remove_watchpoint (b->address, b->length,
				      b->watchpoint_type, b->owner->cond_exp);
 
      /* Failure to remove any of the hardware watchpoints comes here.  */
      if ((is == mark_uninserted) && (b->inserted))
	warning (_("Could not remove hardware watchpoint %d."),
		 b->owner->number);
    }
  else if (b->owner->type == bp_catchpoint
           && breakpoint_enabled (b->owner)
           && !b->duplicate)
    {
      gdb_assert (b->owner->ops != NULL && b->owner->ops->remove != NULL);
 
      val = b->owner->ops->remove (b->owner);
      if (val)
	return val;
      b->inserted = (is == mark_inserted);
    }
 
  return 0;
}
 
static int
remove_breakpoint (struct bp_location *b, insertion_state_t is)
{
  int ret;
  struct cleanup *old_chain;
 
  /* B is never in moribund_locations by our callers.  */
  gdb_assert (b->owner != NULL);
 
  if (b->owner->enable_state == bp_permanent)
    /* Permanent breakpoints cannot be inserted or removed.  */
    return 0;
 
  /* The type of none suggests that owner is actually deleted.
     This should not ever happen.  */
  gdb_assert (b->owner->type != bp_none);
 
  old_chain = save_current_space_and_thread ();
 
  switch_to_program_space_and_thread (b->pspace);
 
  ret = remove_breakpoint_1 (b, is);
 
  do_cleanups (old_chain);
  return ret;
}
 
/* Clear the "inserted" flag in all breakpoints.  */
 
void
mark_breakpoints_out (void)
{
  struct bp_location *bpt, **bptp_tmp;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
    if (bpt->pspace == current_program_space)
      bpt->inserted = 0;
}
 
/* Clear the "inserted" flag in all breakpoints and delete any
   breakpoints which should go away between runs of the program.
 
   Plus other such housekeeping that has to be done for breakpoints
   between runs.
 
   Note: this function gets called at the end of a run (by
   generic_mourn_inferior) and when a run begins (by
   init_wait_for_inferior). */
 
 
 
void
breakpoint_init_inferior (enum inf_context context)
{
  struct breakpoint *b, *temp;
  struct bp_location *bpt, **bptp_tmp;
  int ix;
  struct program_space *pspace = current_program_space;
 
  /* If breakpoint locations are shared across processes, then there's
     nothing to do.  */
  if (gdbarch_has_global_breakpoints (target_gdbarch))
    return;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
  {
    /* ALL_BP_LOCATIONS bp_location has BPT->OWNER always non-NULL.  */
    if (bpt->pspace == pspace
	&& bpt->owner->enable_state != bp_permanent)
      bpt->inserted = 0;
  }
 
  ALL_BREAKPOINTS_SAFE (b, temp)
  {
    if (b->loc && b->loc->pspace != pspace)
      continue;
 
    switch (b->type)
      {
      case bp_call_dummy:
 
	/* If the call dummy breakpoint is at the entry point it will
	   cause problems when the inferior is rerun, so we better get
	   rid of it.  */
 
      case bp_watchpoint_scope:
 
	/* Also get rid of scope breakpoints.  */
 
      case bp_shlib_event:
 
	/* Also remove solib event breakpoints.  Their addresses may
	   have changed since the last time we ran the program.
	   Actually we may now be debugging against different target;
	   and so the solib backend that installed this breakpoint may
	   not be used in by the target.  E.g.,
 
	   (gdb) file prog-linux
	   (gdb) run               # native linux target
	   ...
	   (gdb) kill
	   (gdb) file prog-win.exe
	   (gdb) tar rem :9999     # remote Windows gdbserver.
	*/
 
	delete_breakpoint (b);
	break;
 
      case bp_watchpoint:
      case bp_hardware_watchpoint:
      case bp_read_watchpoint:
      case bp_access_watchpoint:
 
	/* Likewise for watchpoints on local expressions.  */
	if (b->exp_valid_block != NULL)
	  delete_breakpoint (b);
	else if (context == inf_starting) 
	  {
	    /* Reset val field to force reread of starting value
	       in insert_breakpoints.  */
	    if (b->val)
	      value_free (b->val);
	    b->val = NULL;
	    b->val_valid = 0;
	  }
	break;
      default:
	break;
      }
  }
 
  /* Get rid of the moribund locations.  */
  for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bpt); ++ix)
    free_bp_location (bpt);
  VEC_free (bp_location_p, moribund_locations);
}
 
/* These functions concern about actual breakpoints inserted in the
   target --- to e.g. check if we need to do decr_pc adjustment or if
   we need to hop over the bkpt --- so we check for address space
   match, not program space.  */
 
/* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
   exists at PC.  It returns ordinary_breakpoint_here if it's an
   ordinary breakpoint, or permanent_breakpoint_here if it's a
   permanent breakpoint.
   - When continuing from a location with an ordinary breakpoint, we
     actually single step once before calling insert_breakpoints.
   - When continuing from a localion with a permanent breakpoint, we
     need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
     the target, to advance the PC past the breakpoint.  */
 
enum breakpoint_here
breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
{
  struct bp_location *bpt, **bptp_tmp;
  int any_breakpoint_here = 0;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
    {
      if (bpt->loc_type != bp_loc_software_breakpoint
	  && bpt->loc_type != bp_loc_hardware_breakpoint)
	continue;
 
      /* ALL_BP_LOCATIONS bp_location has BPT->OWNER always non-NULL.  */
      if ((breakpoint_enabled (bpt->owner)
	   || bpt->owner->enable_state == bp_permanent)
	  && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
				       aspace, pc))
	{
	  if (overlay_debugging 
	      && section_is_overlay (bpt->section) 
	      && !section_is_mapped (bpt->section))
	    continue;		/* unmapped overlay -- can't be a match */
	  else if (bpt->owner->enable_state == bp_permanent)
	    return permanent_breakpoint_here;
	  else
	    any_breakpoint_here = 1;
	}
    }
 
  return any_breakpoint_here ? ordinary_breakpoint_here : 0;
}
 
/* Return true if there's a moribund breakpoint at PC.  */
 
int
moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
{
  struct bp_location *loc;
  int ix;
 
  for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
    if (breakpoint_address_match (loc->pspace->aspace, loc->address,
				  aspace,  pc))
      return 1;
 
  return 0;
}
 
/* Returns non-zero if there's a breakpoint inserted at PC, which is
   inserted using regular breakpoint_chain / bp_location array mechanism.
   This does not check for single-step breakpoints, which are
   inserted and removed using direct target manipulation.  */
 
int
regular_breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
{
  struct bp_location *bpt, **bptp_tmp;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
    {
      if (bpt->loc_type != bp_loc_software_breakpoint
	  && bpt->loc_type != bp_loc_hardware_breakpoint)
	continue;
 
      if (bpt->inserted
	  && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
				       aspace, pc))
	{
	  if (overlay_debugging 
	      && section_is_overlay (bpt->section) 
	      && !section_is_mapped (bpt->section))
	    continue;		/* unmapped overlay -- can't be a match */
	  else
	    return 1;
	}
    }
  return 0;
}
 
/* Returns non-zero iff there's either regular breakpoint
   or a single step breakpoint inserted at PC.  */
 
int
breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
{
  if (regular_breakpoint_inserted_here_p (aspace, pc))
    return 1;
 
  if (single_step_breakpoint_inserted_here_p (aspace, pc))
    return 1;
 
  return 0;
}
 
/* This function returns non-zero iff there is a software breakpoint
   inserted at PC.  */
 
int
software_breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
{
  struct bp_location *bpt, **bptp_tmp;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
    {
      if (bpt->loc_type != bp_loc_software_breakpoint)
	continue;
 
      if (bpt->inserted
	  && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
				       aspace, pc))
	{
	  if (overlay_debugging 
	      && section_is_overlay (bpt->section) 
	      && !section_is_mapped (bpt->section))
	    continue;		/* unmapped overlay -- can't be a match */
	  else
	    return 1;
	}
    }
 
  /* Also check for software single-step breakpoints.  */
  if (single_step_breakpoint_inserted_here_p (aspace, pc))
    return 1;
 
  return 0;
}
 
int
hardware_watchpoint_inserted_in_range (struct address_space *aspace,
				       CORE_ADDR addr, ULONGEST len)
{
  struct breakpoint *bpt;
 
  ALL_BREAKPOINTS (bpt)
    {
      struct bp_location *loc;
 
      if (bpt->type != bp_hardware_watchpoint
	  && bpt->type != bp_access_watchpoint)
	continue;
 
      if (!breakpoint_enabled (bpt))
	continue;
 
      for (loc = bpt->loc; loc; loc = loc->next)
	if (loc->pspace->aspace == aspace && loc->inserted)
	  {
	    CORE_ADDR l, h;
 
	    /* Check for intersection.  */
	    l = max (loc->address, addr);
	    h = min (loc->address + loc->length, addr + len);
	    if (l < h)
	      return 1;
	  }
    }
  return 0;
}
 
/* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
   PC is valid for process/thread PTID.  */
 
int
breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
			 ptid_t ptid)
{
  struct bp_location *bpt, **bptp_tmp;
  /* The thread and task IDs associated to PTID, computed lazily.  */
  int thread = -1;
  int task = 0;
 
  ALL_BP_LOCATIONS (bpt, bptp_tmp)
    {
      if (bpt->loc_type != bp_loc_software_breakpoint
	  && bpt->loc_type != bp_loc_hardware_breakpoint)
	continue;
 
      /* ALL_BP_LOCATIONS bp_location has BPT->OWNER always non-NULL.  */
      if (!breakpoint_enabled (bpt->owner)
	  && bpt->owner->enable_state != bp_permanent)
	continue;
 
      if (!breakpoint_address_match (bpt->pspace->aspace, bpt->address,
				     aspace, pc))
	continue;
 
      if (bpt->owner->thread != -1)
	{
	  /* This is a thread-specific breakpoint.  Check that ptid
	     matches that thread.  If thread hasn't been computed yet,
	     it is now time to do so.  */
	  if (thread == -1)
	    thread = pid_to_thread_id (ptid);
	  if (bpt->owner->thread != thread)
	    continue;
	}
 
      if (bpt->owner->task != 0)
        {
	  /* This is a task-specific breakpoint.  Check that ptid
	     matches that task.  If task hasn't been computed yet,
	     it is now time to do so.  */
	  if (task == 0)
	    task = ada_get_task_number (ptid);
	  if (bpt->owner->task != task)
	    continue;
        }
 
      if (overlay_debugging 
	  && section_is_overlay (bpt->section) 
	  && !section_is_mapped (bpt->section))
	continue;	    /* unmapped overlay -- can't be a match */
 
      return 1;
    }
 
  return 0;
}

 
/* bpstat stuff.  External routines' interfaces are documented
   in breakpoint.h.  */
 
int
ep_is_catchpoint (struct breakpoint *ep)
{
  return (ep->type == bp_catchpoint);
}
 
void 
bpstat_free (bpstat bs)
{
  if (bs->old_val != NULL)
    value_free (bs->old_val);
  decref_counted_command_line (&bs->commands);
  xfree (bs);
}
 
/* Clear a bpstat so that it says we are not at any breakpoint.
   Also free any storage that is part of a bpstat.  */
 
void
bpstat_clear (bpstat *bsp)
{
  bpstat p;
  bpstat q;
 
  if (bsp == 0)
    return;
  p = *bsp;
  while (p != NULL)
    {
      q = p->next;
      bpstat_free (p);
      p = q;
    }
  *bsp = NULL;
}
 
/* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
   is part of the bpstat is copied as well.  */
 
bpstat
bpstat_copy (bpstat bs)
{
  bpstat p = NULL;
  bpstat tmp;
  bpstat retval = NULL;
 
  if (bs == NULL)
    return bs;
 
  for (; bs != NULL; bs = bs->next)
    {
      tmp = (bpstat) xmalloc (sizeof (*tmp));
      memcpy (tmp, bs, sizeof (*tmp));
      incref_counted_command_line (tmp->commands);
      if (bs->old_val != NULL)
	{
	  tmp->old_val = value_copy (bs->old_val);
	  release_value (tmp->old_val);
	}
 
      if (p == NULL)
	/* This is the first thing in the chain.  */
	retval = tmp;
      else
	p->next = tmp;
      p = tmp;
    }
  p->next = NULL;
  return retval;
}
 
/* Find the bpstat associated with this breakpoint */
 
bpstat
bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
{
  if (bsp == NULL)
    return NULL;
 
  for (; bsp != NULL; bsp = bsp->next)
    {
      if (bsp->breakpoint_at && bsp->breakpoint_at->owner == breakpoint)
	return bsp;
    }
  return NULL;
}
 
/* Put in *NUM the breakpoint number of the first breakpoint we are stopped
   at.  *BSP upon return is a bpstat which points to the remaining
   breakpoints stopped at (but which is not guaranteed to be good for
   anything but further calls to bpstat_num).
   Return 0 if passed a bpstat which does not indicate any breakpoints.
   Return -1 if stopped at a breakpoint that has been deleted since
   we set it.
   Return 1 otherwise.  */
 
int
bpstat_num (bpstat *bsp, int *num)
{
  struct breakpoint *b;
 
  if ((*bsp) == NULL)
    return 0;			/* No more breakpoint values */
 
  /* We assume we'll never have several bpstats that
     correspond to a single breakpoint -- otherwise, 
     this function might return the same number more
     than once and this will look ugly.  */
  b = (*bsp)->breakpoint_at ? (*bsp)->breakpoint_at->owner : NULL;
  *bsp = (*bsp)->next;
  if (b == NULL)
    return -1;			/* breakpoint that's been deleted since */
 
  *num = b->number;		/* We have its number */
  return 1;
}
 
/* Modify BS so that the actions will not be performed.  */
 
void
bpstat_clear_actions (bpstat bs)
{
  for (; bs != NULL; bs = bs->next)
    {
      decref_counted_command_line (&bs->commands);
      bs->commands_left = NULL;
      if (bs->old_val != NULL)
	{
	  value_free (bs->old_val);
	  bs->old_val = NULL;
	}
    }
}
 
/* Called when a command is about to proceed the inferior.  */
 
static void
breakpoint_about_to_proceed (void)
{
  if (!ptid_equal (inferior_ptid, null_ptid))
    {
      struct thread_info *tp = inferior_thread ();
 
      /* Allow inferior function calls in breakpoint commands to not
	 interrupt the command list.  When the call finishes
	 successfully, the inferior will be standing at the same
	 breakpoint as if nothing happened.  */
      if (tp->in_infcall)
	return;
    }
 
  breakpoint_proceeded = 1;
}
 
/* Stub for cleaning up our state if we error-out of a breakpoint command */
static void
cleanup_executing_breakpoints (void *ignore)
{
  executing_breakpoint_commands = 0;
}
 
/* Execute all the commands associated with all the breakpoints at this
   location.  Any of these commands could cause the process to proceed
   beyond this point, etc.  We look out for such changes by checking
   the global "breakpoint_proceeded" after each command.
 
   Returns true if a breakpoint command resumed the inferior.  In that
   case, it is the caller's responsibility to recall it again with the
   bpstat of the current thread.  */
 
static int
bpstat_do_actions_1 (bpstat *bsp)
{
  bpstat bs;
  struct cleanup *old_chain;
  int again = 0;
 
  /* Avoid endless recursion if a `source' command is contained
     in bs->commands.  */
  if (executing_breakpoint_commands)
    return 0;
 
  executing_breakpoint_commands = 1;
  old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
 
  /* This pointer will iterate over the list of bpstat's. */
  bs = *bsp;
 
  breakpoint_proceeded = 0;
  for (; bs != NULL; bs = bs->next)
    {
      struct counted_command_line *ccmd;
      struct command_line *cmd;
      struct cleanup *this_cmd_tree_chain;
 
      /* Take ownership of the BSP's command tree, if it has one.
 
         The command tree could legitimately contain commands like
         'step' and 'next', which call clear_proceed_status, which
         frees stop_bpstat's command tree.  To make sure this doesn't
         free the tree we're executing out from under us, we need to
         take ownership of the tree ourselves.  Since a given bpstat's
         commands are only executed once, we don't need to copy it; we
         can clear the pointer in the bpstat, and make sure we free
         the tree when we're done.  */
      ccmd = bs->commands;
      bs->commands = NULL;
      this_cmd_tree_chain
	= make_cleanup_decref_counted_command_line (&ccmd);
      cmd = bs->commands_left;
      bs->commands_left = NULL;
 
      while (cmd != NULL)
	{
	  execute_control_command (cmd);
 
	  if (breakpoint_proceeded)
	    break;
	  else
	    cmd = cmd->next;
	}
 
      /* We can free this command tree now.  */
      do_cleanups (this_cmd_tree_chain);
 
      if (breakpoint_proceeded)
	{
	  if (target_can_async_p ())
	    /* If we are in async mode, then the target might be still
	       running, not stopped at any breakpoint, so nothing for
	       us to do here -- just return to the event loop.  */
	    ;
	  else
	    /* In sync mode, when execute_control_command returns
	       we're already standing on the next breakpoint.
	       Breakpoint commands for that stop were not run, since
	       execute_command does not run breakpoint commands --
	       only command_line_handler does, but that one is not
	       involved in execution of breakpoint commands.  So, we
	       can now execute breakpoint commands.  It should be
	       noted that making execute_command do bpstat actions is
	       not an option -- in this case we'll have recursive
	       invocation of bpstat for each breakpoint with a
	       command, and can easily blow up GDB stack.  Instead, we
	       return true, which will trigger the caller to recall us
	       with the new stop_bpstat.  */
	    again = 1;
	  break;
	}
    }
  do_cleanups (old_chain);
  return again;
}
 
void
bpstat_do_actions (void)
{
  /* Do any commands attached to breakpoint we are stopped at.  */
  while (!ptid_equal (inferior_ptid, null_ptid)
	 && target_has_execution
	 && !is_exited (inferior_ptid)
	 && !is_executing (inferior_ptid))
    /* Since in sync mode, bpstat_do_actions may resume the inferior,
       and only return when it is stopped at the next breakpoint, we
       keep doing breakpoint actions until it returns false to
       indicate the inferior was not resumed.  */
    if (!bpstat_do_actions_1 (&inferior_thread ()->stop_bpstat))
      break;
}
 
/* Print out the (old or new) value associated with a watchpoint.  */
 
static void
watchpoint_value_print (struct value *val, struct ui_file *stream)
{
  if (val == NULL)
    fprintf_unfiltered (stream, _("<unreadable>"));
  else
    {
      struct value_print_options opts;
      get_user_print_options (&opts);
      value_print (val, stream, &opts);
    }
}
 
/* This is the normal print function for a bpstat.  In the future,
   much of this logic could (should?) be moved to bpstat_stop_status,
   by having it set different print_it values.
 
   Current scheme: When we stop, bpstat_print() is called.  It loops
   through the bpstat list of things causing this stop, calling the
   print_bp_stop_message function on each one. The behavior of the
   print_bp_stop_message function depends on the print_it field of
   bpstat. If such field so indicates, call this function here.
 
   Return values from this routine (ultimately used by bpstat_print()
   and normal_stop() to decide what to do): 
   PRINT_NOTHING: Means we already printed all we needed to print,
   don't print anything else.
   PRINT_SRC_ONLY: Means we printed something, and we do *not* desire
   that something to be followed by a location.
   PRINT_SCR_AND_LOC: Means we printed something, and we *do* desire
   that something to be followed by a location.
   PRINT_UNKNOWN: Means we printed nothing or we need to do some more
   analysis.  */
 
static enum print_stop_action
print_it_typical (bpstat bs)
{
  struct cleanup *old_chain;
  struct breakpoint *b;
  const struct bp_location *bl;
  struct ui_stream *stb;
  int bp_temp = 0;
  enum print_stop_action result;
 
  /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
     which has since been deleted.  */
  if (bs->breakpoint_at == NULL)
    return PRINT_UNKNOWN;
  bl = bs->breakpoint_at;
 
  /* bl->owner can be NULL if it was a momentary breakpoint
     which has since been placed into moribund_locations.  */
  if (bl->owner == NULL)
    return PRINT_UNKNOWN;
  b = bl->owner;
 
  stb = ui_out_stream_new (uiout);
  old_chain = make_cleanup_ui_out_stream_delete (stb);
 
  switch (b->type)
    {
    case bp_breakpoint:
    case bp_hardware_breakpoint:
      bp_temp = bs->breakpoint_at->owner->disposition == disp_del;
      if (bl->address != bl->requested_address)
	breakpoint_adjustment_warning (bl->requested_address,
	                               bl->address,
				       b->number, 1);
      annotate_breakpoint (b->number);
      if (bp_temp) 
	ui_out_text (uiout, "\nTemporary breakpoint ");
      else
	ui_out_text (uiout, "\nBreakpoint ");
      if (ui_out_is_mi_like_p (uiout))
	{
	  ui_out_field_string (uiout, "reason", 
			  async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
	  ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
	}
      ui_out_field_int (uiout, "bkptno", b->number);
      ui_out_text (uiout, ", ");
      result = PRINT_SRC_AND_LOC;
      break;
 
    case bp_shlib_event:
      /* Did we stop because the user set the stop_on_solib_events
	 variable?  (If so, we report this as a generic, "Stopped due
	 to shlib event" message.) */
      printf_filtered (_("Stopped due to shared library event\n"));
      result = PRINT_NOTHING;
      break;
 
    case bp_thread_event:
      /* Not sure how we will get here. 
	 GDB should not stop for these breakpoints.  */
      printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
      result = PRINT_NOTHING;
      break;
 
    case bp_overlay_event:
      /* By analogy with the thread event, GDB should not stop for these. */
      printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
      result = PRINT_NOTHING;
      break;
 
    case bp_longjmp_master:
      /* These should never be enabled.  */
      printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
      result = PRINT_NOTHING;
      break;
 
    case bp_std_terminate_master:
      /* These should never be enabled.  */
      printf_filtered (_("std::terminate Master Breakpoint: gdb should not stop!\n"));
      result = PRINT_NOTHING;
      break;
 
    case bp_watchpoint:
    case bp_hardware_watchpoint:
      annotate_watchpoint (b->number);
      if (ui_out_is_mi_like_p (uiout))
	ui_out_field_string
	  (uiout, "reason",
	   async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
      mention (b);
      make_cleanup_ui_out_tuple_begin_end (uiout, "value");
      ui_out_text (uiout, "\nOld value = ");
      watchpoint_value_print (bs->old_val, stb->stream);
      ui_out_field_stream (uiout, "old", stb);
      ui_out_text (uiout, "\nNew value = ");
      watchpoint_value_print (b->val, stb->stream);
      ui_out_field_stream (uiout, "new", stb);
      ui_out_text (uiout, "\n");
      /* More than one watchpoint may have been triggered.  */
      result = PRINT_UNKNOWN;
      break;
 
    case bp_read_watchpoint:
      if (ui_out_is_mi_like_p (uiout))
	ui_out_field_string
	  (uiout, "reason",
	   async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
      mention (b);
      make_cleanup_ui_out_tuple_begin_end (uiout, "value");
      ui_out_text (uiout, "\nValue = ");
      watchpoint_value_print (b->val, stb->stream);
      ui_out_field_stream (uiout, "value", stb);
      ui_out_text (uiout, "\n");
      result = PRINT_UNKNOWN;
      break;
 
    case bp_access_watchpoint:
      if (bs->old_val != NULL)
	{
	  annotate_watchpoint (b->number);
	  if (ui_out_is_mi_like_p (uiout))
	    ui_out_field_string
	      (uiout, "reason",
	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
	  mention (b);
	  make_cleanup_ui_out_tuple_begin_end (uiout, "value");
	  ui_out_text (uiout, "\nOld value = ");
	  watchpoint_value_print (bs->old_val, stb->stream);
	  ui_out_field_stream (uiout, "old", stb);
	  ui_out_text (uiout, "\nNew value = ");
	}
      else 
	{
	  mention (b);
	  if (ui_out_is_mi_like_p (uiout))
	    ui_out_field_string
	      (uiout, "reason",
	       async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
	  make_cleanup_ui_out_tuple_begin_end (uiout, "value");
	  ui_out_text (uiout, "\nValue = ");
	}
      watchpoint_value_print (b->val, stb->stream);
      ui_out_field_stream (uiout, "new", stb);
      ui_out_text (uiout, "\n");
      result = PRINT_UNKNOWN;
      break;
 
    /* Fall through, we don't deal with these types of breakpoints
       here. */
 
    case bp_finish:
      if (ui_out_is_mi_like_p (uiout))
	ui_out_field_string
	  (uiout, "reason",
	   async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
      result = PRINT_UNKNOWN;
      break;
 
    case bp_until:
      if (ui_out_is_mi_like_p (uiout))
	ui_out_field_string
	  (uiout, "reason",
	   async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
      result = PRINT_UNKNOWN;
      break;
 
    case bp_none:
    case bp_longjmp:
    case bp_longjmp_resume:
    case bp_step_resume:
    case bp_watchpoint_scope:
    case bp_call_dummy:
    case bp_std_terminate:
    case bp_tracepoint:
    case bp_fast_tracepoint:
    case bp_jit_event:
    default:
      result = PRINT_UNKNOWN;
      break;
    }
 
  do_cleanups (old_chain);
  return result;
}
 
/* Generic routine for printing messages indicating why we
   stopped. The behavior of this function depends on the value
   'print_it' in the bpstat structure.  Under some circumstances we
   may decide not to print anything here and delegate the task to
   normal_stop(). */
 
static enum print_stop_action
print_bp_stop_message (bpstat bs)
{
  switch (bs->print_it)
    {
    case print_it_noop:
      /* Nothing should be printed for this bpstat entry. */
      return PRINT_UNKNOWN;
      break;
 
    case print_it_done:
      /* We still want to print the frame, but we already printed the
         relevant messages. */
      return PRINT_SRC_AND_LOC;
      break;
 
    case print_it_normal:
      {
	const struct bp_location *bl = bs->breakpoint_at;
	struct breakpoint *b = bl ? bl->owner : NULL;
 
	/* Normal case.  Call the breakpoint's print_it method, or
	   print_it_typical.  */
	/* FIXME: how breakpoint can ever be NULL here?  */
	if (b != NULL && b->ops != NULL && b->ops->print_it != NULL)
	  return b->ops->print_it (b);
	else
	  return print_it_typical (bs);
      }
	break;
 
    default:
      internal_error (__FILE__, __LINE__,
		      _("print_bp_stop_message: unrecognized enum value"));
      break;
    }
}
 
/* Print a message indicating what happened.  This is called from
   normal_stop().  The input to this routine is the head of the bpstat
   list - a list of the eventpoints that caused this stop.  This
   routine calls the generic print routine for printing a message
   about reasons for stopping.  This will print (for example) the
   "Breakpoint n," part of the output.  The return value of this
   routine is one of:
 
   PRINT_UNKNOWN: Means we printed nothing
   PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
   code to print the location. An example is 
   "Breakpoint 1, " which should be followed by
   the location.
   PRINT_SRC_ONLY: Means we printed something, but there is no need
   to also print the location part of the message.
   An example is the catch/throw messages, which
   don't require a location appended to the end.  
   PRINT_NOTHING: We have done some printing and we don't need any 
   further info to be printed.*/
 
enum print_stop_action
bpstat_print (bpstat bs)
{
  int val;
 
  /* Maybe another breakpoint in the chain caused us to stop.
     (Currently all watchpoints go on the bpstat whether hit or not.
     That probably could (should) be changed, provided care is taken
     with respect to bpstat_explains_signal).  */
  for (; bs; bs = bs->next)
    {
      val = print_bp_stop_message (bs);
      if (val == PRINT_SRC_ONLY 
	  || val == PRINT_SRC_AND_LOC 
	  || val == PRINT_NOTHING)
	return val;
    }
 
  /* We reached the end of the chain, or we got a null BS to start
     with and nothing was printed. */
  return PRINT_UNKNOWN;
}
 
/* Evaluate the expression EXP and return 1 if value is zero.
   This is used inside a catch_errors to evaluate the breakpoint condition. 
   The argument is a "struct expression *" that has been cast to char * to 
   make it pass through catch_errors.  */
 
static int
breakpoint_cond_eval (void *exp)
{
  struct value *mark = value_mark ();
  int i = !value_true (evaluate_expression ((struct expression *) exp));
 
  value_free_to_mark (mark);
  return i;
}
 
/* Allocate a new bpstat and chain it to the current one.  */
 
static bpstat
bpstat_alloc (const struct bp_location *bl, bpstat cbs /* Current "bs" value */ )
{
  bpstat bs;
 
  bs = (bpstat) xmalloc (sizeof (*bs));
  cbs->next = bs;
  bs->breakpoint_at = bl;
  /* If the condition is false, etc., don't do the commands.  */
  bs->commands = NULL;
  bs->commands_left = NULL;
  bs->old_val = NULL;
  bs->print_it = print_it_normal;
  return bs;
}

/* The target has stopped with waitstatus WS.  Check if any hardware
   watchpoints have triggered, according to the target.  */
 
int
watchpoints_triggered (struct target_waitstatus *ws)
{
  int stopped_by_watchpoint = target_stopped_by_watchpoint ();
  CORE_ADDR addr;
  struct breakpoint *b;
 
  if (!stopped_by_watchpoint)
    {
      /* We were not stopped by a watchpoint.  Mark all watchpoints
	 as not triggered.  */
      ALL_BREAKPOINTS (b)
	if (is_hardware_watchpoint (b))
	  b->watchpoint_triggered = watch_triggered_no;
 
      return 0;
    }
 
  if (!target_stopped_data_address (&current_target, &addr))
    {
      /* We were stopped by a watchpoint, but we don't know where.
	 Mark all watchpoints as unknown.  */
      ALL_BREAKPOINTS (b)
	if (is_hardware_watchpoint (b))
	  b->watchpoint_triggered = watch_triggered_unknown;
 
      return stopped_by_watchpoint;
    }
 
  /* The target could report the data address.  Mark watchpoints
     affected by this data address as triggered, and all others as not
     triggered.  */
 
  ALL_BREAKPOINTS (b)
    if (is_hardware_watchpoint (b))
      {
	struct bp_location *loc;
 
	b->watchpoint_triggered = watch_triggered_no;
	for (loc = b->loc; loc; loc = loc->next)
	  /* Exact match not required.  Within range is
	     sufficient.  */
	  if (target_watchpoint_addr_within_range (&current_target,
						   addr, loc->address,
						   loc->length))
	    {
	      b->watchpoint_triggered = watch_triggered_yes;
	      break;
	    }
      }
 
  return 1;
}
 
/* Possible return values for watchpoint_check (this can't be an enum
   because of check_errors).  */
/* The watchpoint has been deleted.  */
#define WP_DELETED 1
/* The value has changed.  */
#define WP_VALUE_CHANGED 2
/* The value has not changed.  */
#define WP_VALUE_NOT_CHANGED 3
/* Ignore this watchpoint, no matter if the value changed or not.  */
#define WP_IGNORE 4
 
#define BP_TEMPFLAG 1
#define BP_HARDWAREFLAG 2
 
/* Evaluate watchpoint condition expression and check if its value changed.
 
   P should be a pointer to struct bpstat, but is defined as a void *
   in order for this function to be usable with catch_errors.  */
 
static int
watchpoint_check (void *p)
{
  bpstat bs = (bpstat) p;
  struct breakpoint *b;
  struct frame_info *fr;
  int within_current_scope;
 
  /* BS is built for existing struct breakpoint.  */
  gdb_assert (bs->breakpoint_at != NULL);
  gdb_assert (bs->breakpoint_at->owner != NULL);
  b = bs->breakpoint_at->owner;
 
  /* If this is a local watchpoint, we only want to check if the
     watchpoint frame is in scope if the current thread is the thread
     that was used to create the watchpoint.  */
  if (!watchpoint_in_thread_scope (b))
    return WP_IGNORE;
 
  if (b->exp_valid_block == NULL)
    within_current_scope = 1;
  else
    {
      struct frame_info *frame = get_current_frame ();
      struct gdbarch *frame_arch = get_frame_arch (frame);
      CORE_ADDR frame_pc = get_frame_pc (frame);
 
      /* in_function_epilogue_p() returns a non-zero value if we're still
	 in the function but the stack frame has already been invalidated.
	 Since we can't rely on the values of local variables after the
	 stack has been destroyed, we are treating the watchpoint in that
	 state as `not changed' without further checking.  Don't mark
	 watchpoints as changed if the current frame is in an epilogue -
	 even if they are in some other frame, our view of the stack
	 is likely to be wrong and frame_find_by_id could error out.  */
      if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
	return WP_IGNORE;
 
      fr = frame_find_by_id (b->watchpoint_frame);
      within_current_scope = (fr != NULL);
 
      /* If we've gotten confused in the unwinder, we might have
	 returned a frame that can't describe this variable.  */
      if (within_current_scope)
	{
	  struct symbol *function;
 
	  function = get_frame_function (fr);
	  if (function == NULL
	      || !contained_in (b->exp_valid_block,
				SYMBOL_BLOCK_VALUE (function)))
	    within_current_scope = 0;
	}
 
      if (within_current_scope)
	/* If we end up stopping, the current frame will get selected
	   in normal_stop.  So this call to select_frame won't affect
	   the user.  */
	select_frame (fr);
    }
 
  if (within_current_scope)
    {
      /* We use value_{,free_to_}mark because it could be a
         *long* time before we return to the command level and
         call free_all_values.  We can't call free_all_values because
         we might be in the middle of evaluating a function call.  */
 
      int pc = 0;
      struct value *mark = value_mark ();
      struct value *new_val;
 
      fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
 
      /* We use value_equal_contents instead of value_equal because the latter
	 coerces an array to a pointer, thus comparing just the address of the
	 array instead of its contents.  This is not what we want.  */
      if ((b->val != NULL) != (new_val != NULL)
	  || (b->val != NULL && !value_equal_contents (b->val, new_val)))
	{
	  if (new_val != NULL)
	    {
	      release_value (new_val);
	      value_free_to_mark (mark);
	    }
	  bs->old_val = b->val;
	  b->val = new_val;
	  b->val_valid = 1;
	  return WP_VALUE_CHANGED;
	}
      else
	{
	  /* Nothing changed.  */
	  value_free_to_mark (mark);
	  return WP_VALUE_NOT_CHANGED;
	}
    }
  else
    {
      /* This seems like the only logical thing to do because
         if we temporarily ignored the watchpoint, then when
         we reenter the block in which it is valid it contains
         garbage (in the case of a function, it may have two
         garbage values, one before and one after the prologue).
         So we can't even detect the first assignment to it and
         watch after that (since the garbage may or may not equal
         the first value assigned).  */
      /* We print all the stop information in print_it_typical(), but
	 in this case, by the time we call print_it_typical() this bp
	 will be deleted already. So we have no choice but print the
	 information here. */
      if (ui_out_is_mi_like_p (uiout))
	ui_out_field_string
	  (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
      ui_out_text (uiout, "\nWatchpoint ");
      ui_out_field_int (uiout, "wpnum", b->number);
      ui_out_text (uiout, " deleted because the program has left the block in\n\
which its expression is valid.\n");     
 
      if (b->related_breakpoint)
	{
	  b->related_breakpoint->disposition = disp_del_at_next_stop;
	  b->related_breakpoint->related_breakpoint = NULL;
	  b->related_breakpoint = NULL;
	}
      b->disposition = disp_del_at_next_stop;
 
      return WP_DELETED;
    }
}
 
/* Return true if it looks like target has stopped due to hitting
   breakpoint location BL.  This function does not check if we
   should stop, only if BL explains the stop.   */
static int
bpstat_check_location (const struct bp_location *bl,
		       struct address_space *aspace, CORE_ADDR bp_addr)
{
  struct breakpoint *b = bl->owner;
 
  /* BL is from existing struct breakpoint.  */
  gdb_assert (b != NULL);
 
  /* By definition, the inferior does not report stops at
     tracepoints.  */
  if (is_tracepoint (b))
    return 0;
 
  if (!is_watchpoint (b)
      && b->type != bp_hardware_breakpoint
      && b->type != bp_catchpoint)	/* a non-watchpoint bp */
    {
      if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
				     aspace, bp_addr))
	return 0;
      if (overlay_debugging		/* unmapped overlay section */
	  && section_is_overlay (bl->section) 
	  && !section_is_mapped (bl->section))
	return 0;
    }
 
  /* Continuable hardware watchpoints are treated as non-existent if the
     reason we stopped wasn't a hardware watchpoint (we didn't stop on
     some data address).  Otherwise gdb won't stop on a break instruction
     in the code (not from a breakpoint) when a hardware watchpoint has
     been defined.  Also skip watchpoints which we know did not trigger
     (did not match the data address).  */
 
  if (is_hardware_watchpoint (b)
      && b->watchpoint_triggered == watch_triggered_no)
    return 0;
 
  if (b->type == bp_hardware_breakpoint)
    {
      if (bl->address != bp_addr)
	return 0;
      if (overlay_debugging		/* unmapped overlay section */
	  && section_is_overlay (bl->section) 
	  && !section_is_mapped (bl->section))
	return 0;
    }
 
  if (b->type == bp_catchpoint)
    {
      gdb_assert (b->ops != NULL && b->ops->breakpoint_hit != NULL);
      if (!b->ops->breakpoint_hit (b))
        return 0;
    }
 
  return 1;
}
 
/* If BS refers to a watchpoint, determine if the watched values
   has actually changed, and we should stop.  If not, set BS->stop
   to 0.  */
static void
bpstat_check_watchpoint (bpstat bs)
{
  const struct bp_location *bl;
  struct breakpoint *b;
 
  /* BS is built for existing struct breakpoint.  */
  bl = bs->breakpoint_at;
  gdb_assert (bl != NULL);
  b = bl->owner;
  gdb_assert (b != NULL);
 
  if (is_watchpoint (b))
    {
      int must_check_value = 0;
 
      if (b->type == bp_watchpoint)
	/* For a software watchpoint, we must always check the
	   watched value.  */
	must_check_value = 1;
      else if (b->watchpoint_triggered == watch_triggered_yes)
	/* We have a hardware watchpoint (read, write, or access)
	   and the target earlier reported an address watched by
	   this watchpoint.  */
	must_check_value = 1;
      else if (b->watchpoint_triggered == watch_triggered_unknown
	       && b->type == bp_hardware_watchpoint)
	/* We were stopped by a hardware watchpoint, but the target could
	   not report the data address.  We must check the watchpoint's
	   value.  Access and read watchpoints are out of luck; without
	   a data address, we can't figure it out.  */
	must_check_value = 1;
 
      if (must_check_value)
	{
	  char *message = xstrprintf ("Error evaluating expression for watchpoint %d\n",
				      b->number);
	  struct cleanup *cleanups = make_cleanup (xfree, message);
	  int e = catch_errors (watchpoint_check, bs, message,
				RETURN_MASK_ALL);

Go to most recent revision | Compare with Previous | Blame | View Log

powered by: WebSVN 2.1.0

© copyright 1999-2025 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.